repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kharrison/CodeExamples
ScrollGuide/ScrollGuide/ForecastViewController.swift
1
5503
// Copyright © 2018 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE 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 final class ForecastViewController: UIViewController { private enum ViewMetrics { static let margin: CGFloat = 20.0 static let backgroundColor = UIColor(named: "SkyBlue") } private let forecastView: ForecastView = { let view = ForecastView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = ViewMetrics.backgroundColor return view }() private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(forecastView) return scrollView }() private let infoButton: UIButton = { let button = UIButton(type: .infoDark) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(showInfo(_:)), for: .touchUpInside) return button }() var forecast: Forecast? { didSet { updateView() } } private func updateView() { if let forecast = forecast { forecastView.titleLabel.text = forecast.title forecastView.summaryLabel.text = forecast.summary forecastView.imageView.image = forecast.icon() forecastView.imageView.sizeToFit() } } override func viewDidLoad() { super.viewDidLoad() setupView() updateView() } private func setupView() { view.backgroundColor = ViewMetrics.backgroundColor forecastView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: ViewMetrics.margin, leading: ViewMetrics.margin, bottom: ViewMetrics.margin, trailing: ViewMetrics.margin) view.addSubview(scrollView) scrollView.addSubview(infoButton) let frameGuide = scrollView.frameLayoutGuide let contentGuide = scrollView.contentLayoutGuide // Classic scroll view setup using scroll view anchors // NSLayoutConstraint.activate([ // scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), // scrollView.topAnchor.constraint(equalTo: view.topAnchor), // scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), // scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), // // scrollView.leadingAnchor.constraint(equalTo: forecastView.leadingAnchor), // scrollView.topAnchor.constraint(equalTo: forecastView.topAnchor), // scrollView.trailingAnchor.constraint(equalTo: forecastView.trailingAnchor), // scrollView.bottomAnchor.constraint(equalTo: forecastView.bottomAnchor), // // forecastView.widthAnchor.constraint(equalTo: scrollView.widthAnchor) // ]) // Scroll view layout guides (iOS 11) NSLayoutConstraint.activate([ frameGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor), frameGuide.topAnchor.constraint(equalTo: view.topAnchor), frameGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor), frameGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor), contentGuide.leadingAnchor.constraint(equalTo: forecastView.leadingAnchor), contentGuide.topAnchor.constraint(equalTo: forecastView.topAnchor), contentGuide.trailingAnchor.constraint(equalTo: forecastView.trailingAnchor), contentGuide.bottomAnchor.constraint(equalTo: forecastView.bottomAnchor), contentGuide.widthAnchor.constraint(equalTo: frameGuide.widthAnchor), infoButton.leadingAnchor.constraint(equalTo: scrollView.layoutMarginsGuide.leadingAnchor), infoButton.topAnchor.constraint(equalTo: scrollView.layoutMarginsGuide.topAnchor) ]) } } extension ForecastViewController { @objc private func showInfo(_ sender: UIButton) { print("Show Info") } }
bsd-3-clause
dbea28676796a36bc0e924b114c717b1
43.016
183
0.714649
5.210227
false
false
false
false
hotchner/MarkdownView
MarkdownView/MarkdownView.swift
1
4751
import UIKit import WebKit open class MarkdownView: UIView { private var webView: WKWebView? public var isScrollEnabled: Bool = true { didSet { webView?.scrollView.isScrollEnabled = isScrollEnabled } } public var onTouchLink: ((URLRequest) -> Bool)? public var onRendered: ((CGFloat) -> Void)? public convenience init() { self.init(frame: CGRect.zero) } override init (frame: CGRect) { super.init(frame : frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func load(markdown: String?, enableImage: Bool = true) { guard let markdown = markdown else { return } let bundle = Bundle(for: MarkdownView.self) var htmlURL: URL? if bundle.bundleIdentifier?.hasPrefix("org.cocoapods") == true { htmlURL = bundle.url(forResource: "index", withExtension: "html", subdirectory: "MarkdownView.bundle") } else { htmlURL = bundle.url(forResource: "index", withExtension: "html") } if let url = htmlURL { let templateRequest = URLRequest(url: url) let escapedMarkdown = self.escape(markdown: markdown) ?? "" let imageOption = enableImage ? "true" : "false" let script = "window.showMarkdown('\(escapedMarkdown)', \(imageOption));" let userScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true) let controller = WKUserContentController() controller.addUserScript(userScript) let configuration = WKWebViewConfiguration() configuration.userContentController = controller let wv = WKWebView(frame: self.bounds, configuration: configuration) wv.scrollView.isScrollEnabled = self.isScrollEnabled wv.translatesAutoresizingMaskIntoConstraints = false wv.navigationDelegate = self addSubview(wv) if #available(iOS 9.0, *) { wv.topAnchor.constraint(equalTo: self.topAnchor).isActive = true wv.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true wv.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true wv.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true } else { NSLayoutConstraint(item: wv, attribute: .top, relatedBy: .equal, toItem: self, attribute: .topMargin, multiplier: 1.0, constant: 0.0).isActive = true NSLayoutConstraint(item: wv, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottomMargin, multiplier: 1.0, constant: 0.0).isActive = true NSLayoutConstraint(item: wv, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leadingMargin, multiplier: 1.0, constant: 0.0).isActive = true NSLayoutConstraint(item: wv, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailingMargin, multiplier: 1.0, constant: 0.0).isActive = true } wv.backgroundColor = self.backgroundColor self.webView = wv wv.load(templateRequest) } else { // TODO: raise error } } private func escape(markdown: String) -> String? { return markdown.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) } } extension MarkdownView: WKNavigationDelegate { public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { let script = "document.body.offsetHeight;" webView.evaluateJavaScript(script) { [weak self] result, error in if let _ = error { return } if let height = result as? CGFloat { self?.onRendered?(height) } } } public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { switch navigationAction.navigationType { case .linkActivated: if let onTouchLink = onTouchLink, onTouchLink(navigationAction.request) { decisionHandler(.allow) } else { decisionHandler(.cancel) } default: decisionHandler(.allow) } } }
mit
a4e890c83a2dbd80c2b340038f1c90dd
31.765517
162
0.585982
5.284761
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Home/Views/HomePlaylistCell.swift
1
2343
// // HomePlaylistCell.swift // MusicApp // // Created by Hưng Đỗ on 7/1/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import Action class HomePlaylistCell: UITableViewCell { @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() collectionView.dataSource = self collectionView.delegate = self let layout = collectionView.collectionViewLayout as? HomePlaylistCollectionViewLayout layout?.delegate = self } var playlists: [Playlist] = [] { didSet { collectionView.reloadData() } } var onPlaylistDidSelect: Action<Playlist, Void>! } extension HomePlaylistCell: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let max = kHomePlaylistCollectionViewLayoutMaximumElements return playlists.count > max ? max : playlists.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var identifier = String(describing: HomePlaylistItemCell.self) if indexPath.item == 0 { identifier = "Large\(identifier)" } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) if let cell = cell as? PlaylistItemCell { let playlist = playlists[indexPath.item] cell.configure(name: playlist.name, singer: playlist.singer, image: playlist.avatar) } return cell } } extension HomePlaylistCell: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let playlist = playlists[indexPath.item] onPlaylistDidSelect.execute(playlist) } } extension HomePlaylistCell: HomePlaylistCollectionViewLayoutDelegate, HomePlaylistCellOptions { func itemSizeForCollectionView(_ collectionView: UICollectionView) -> CGFloat { return width(of: collectionView) } func itemPaddingForCollectionView(_ collectionView: UICollectionView) -> CGFloat { return itemPadding } }
mit
c2a7ea278e853344733a5d59065db990
28.225
121
0.674936
5.514151
false
false
false
false
mamaral/MATextFieldCell
MATextFieldCell Example/MATextFieldCell Example/AppDelegate.swift
1
2623
// // AppDelegate.swift // MATextFieldCell Example // // Created by Mike on 6/13/14. // Copyright (c) 2014 Mike Amaral. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() let mainViewController: OptionsViewController = OptionsViewController() let navigationController: UINavigationController = UINavigationController(rootViewController: mainViewController) self.window!.rootViewController = navigationController return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
0131ecc1f0d9da0805df6644d1aad7af
47.574074
285
0.742661
5.854911
false
false
false
false
gbuela/github-users-coord
github-users/AppCoordinator.swift
1
2634
// // AppCoordinator.swift // github-users // // Created by German Buela on 6/5/16. // Copyright © 2016 German Buela. All rights reserved. // import UIKit import ReactiveCocoa let (flowSignal, flowObserver) = Signal<FlowEvent, NoError>.pipe() enum FlowEvent { case AppStart case LoadedList(users:[User]) case SelectedUser(user:User) } extension FlowEvent { func loadViewModel(network: NetworkProtocol) -> AnyObject? { var vm : AnyObject? switch self { case .AppStart: vm = HomeViewModel(network) case .LoadedList(let users): vm = UsersViewModel(users: users) case .SelectedUser(let user): vm = DetailViewModel(network, user: user) } return vm } } extension FlowEvent { func loadFromStoryboard(name:String) -> UIViewController { return UIStoryboard(name: "Main", bundle: nil) .instantiateViewControllerWithIdentifier(name) } func loadViewController(network: NetworkProtocol) -> AnyObject? { var vc : AnyObject? switch self { case .AppStart: let hvc = self.loadFromStoryboard("Home") as! HomeViewController hvc.viewModel = self.loadViewModel(network) as? HomeViewModel vc = hvc case .LoadedList: let uvc = self.loadFromStoryboard("Users") as! UsersViewController uvc.viewModel = self.loadViewModel(network) as? UsersViewModel vc = uvc case .SelectedUser: let dvc = self.loadFromStoryboard("Detail") as! DetailViewController dvc.viewModel = self.loadViewModel(network) as? DetailViewModel vc = dvc } return vc } } protocol Presenter { func present(viewController: AnyObject) } struct Coordinator { let presenter: Presenter let network: NetworkProtocol func start() { flowSignal.observeNext { next in if let vc = next.loadViewController(self.network) { dispatch_async(dispatch_get_main_queue(), { self.presenter.present(vc) }) } else { print("Could not load VC for event \(next)") } } flowObserver.sendNext(FlowEvent.AppStart) } } struct AppPresenter : Presenter { let navigation: UINavigationController func present(viewController: AnyObject) { if let vc = viewController as? UIViewController { self.navigation.pushViewController(vc, animated: true) } } }
gpl-3.0
4027b8759e451f41eabace7ff113102f
25.069307
80
0.602735
4.701786
false
false
false
false
eldesperado/SpareTimeAlarmApp
SpareTimeMusicApp/RepeatDateSelectionViewController.swift
1
3940
// // RepeatDateSelectionViewController.swift // SpareTimeAlarmApp // // Created by Pham Nguyen Nhat Trung on 8/10/15. // Copyright (c) 2015 Pham Nguyen Nhat Trung. All rights reserved. // import UIKit class RepeatDateSelectionViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let numberOfDates = 7 var repeatDates: RepeatDate? @IBOutlet weak var tableView: UITableView! @IBOutlet weak var backgroundImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() setupView() } let unwindSegueId = "doneRepeatDatesSelectionUnwindSegue" override func viewWillDisappear(animated: Bool) { // Detect whether back button is pressed or not, if pressed, perform unwind segue if ((navigationController!.viewControllers ).indexOf(self) == nil) { // back button was pressed. We know this is true because self is no longer // in the navigation stack. performSegueWithIdentifier(unwindSegueId, sender: repeatDates) } super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UITableViewDelegates func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfDates } let cellIdentifier = "repeatDateCell" func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: RepeatDateSelectionTableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RepeatDateSelectionTableViewCell // If RepeatDate has info, edit repeat dates let dateNumber = indexPath.row + 1 cell.configureCell(dateNumber, repeatDate: repeatDates) return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell: RepeatDateSelectionTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as! RepeatDateSelectionTableViewCell cell.checkIconImageView.hidden = !cell.checkIconImageView.hidden if let date = repeatDates { let dateNumber = indexPath.row + 1 switch (dateNumber) { case NumberToDate.Monday.date: date.isMon = !date.isMon.boolValue case NumberToDate.Tuesday.date: date.isTue = !date.isTue.boolValue case NumberToDate.Wednesday.date: date.isWed = !date.isWed.boolValue case NumberToDate.Thursday.date: date.isThu = !date.isThu.boolValue case NumberToDate.Friday.date: date.isFri = !date.isFri.boolValue case NumberToDate.Saturday.date: date.isSat = !date.isSat.boolValue case NumberToDate.Sunday.date: date.isSun = !date.isSun.boolValue default: break } } } // MARK: Setup Views private func setupView() { if let component = ThemeManager.getSharedInstance().getThemeComponent(ThemeComponent.ThemeAttribute.BackgroundImage) as? UIImage { backgroundImageView.image = component } observeTheme() } private func observeTheme() { ThemeObserver.onMainThread(self) { [weak self] notification in // Set theme if let component = ThemeManager.getSharedInstance().getThemeComponent(ThemeComponent.ThemeAttribute.BackgroundImage) as? UIImage { self?.backgroundImageView.image = component // Animate Change self?.backgroundImageView.layer.animateThemeChangeAnimation() } } } // MARK: Navigation Configuration func configureNavigation() { } // MARK: Deinit deinit { ThemeObserver.unregister(self) } }
mit
21c812f7f26b699b7a52b0b99c1d157c
32.675214
170
0.723858
4.962217
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/ERC20Kit/Domain/Account/ERC20ReceiveAddress.swift
1
1687
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import EthereumKit import MoneyKit import PlatformKit import RxSwift struct ERC20ReceiveAddress: CryptoReceiveAddress, QRCodeMetadataProvider { var address: String { eip681URI.method.destination ?? eip681URI.address } var qrCodeMetadata: QRCodeMetadata { QRCodeMetadata(content: address, title: address) } let asset: CryptoCurrency let label: String let onTxCompleted: TxCompleted let eip681URI: EIP681URI init?( asset: CryptoCurrency, eip681URI: EIP681URI, label: String, onTxCompleted: @escaping TxCompleted ) { guard Self.validateCryptoCurrency(eip681URI: eip681URI, cryptoCurrency: asset) else { return nil } self.asset = asset self.eip681URI = eip681URI self.label = label self.onTxCompleted = onTxCompleted } init?( asset: CryptoCurrency, address: String, label: String, onTxCompleted: @escaping TxCompleted ) { guard let eip681URI = EIP681URI(address: address, cryptoCurrency: asset) else { return nil } self.init(asset: asset, eip681URI: eip681URI, label: label, onTxCompleted: onTxCompleted) } /// When creating a ERC20ReceiveAddress, the EIP681URI must be for .ethereum or the specific CryptoCurrency required. private static func validateCryptoCurrency( eip681URI: EIP681URI, cryptoCurrency: CryptoCurrency ) -> Bool { eip681URI.cryptoCurrency == .ethereum || eip681URI.cryptoCurrency == cryptoCurrency } }
lgpl-3.0
b8eb1f5b7e2fb70e1a9207ba5cd17106
27.576271
121
0.664887
4.644628
false
false
false
false
Clean-Swift/WhenToMock
WhenToMock/Scenes/User/UserRouter.swift
1
2009
// // UserRouter.swift // WhenToMock // // Created by Raymond Law on 10/26/15. // Copyright (c) 2015 Raymond Law. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol UserRouterInput { func navigateToSomewhere() } class UserRouter { weak var viewController: UserViewController! // MARK: Navigation func navigateToSomewhere() { // NOTE: Teach the router how to navigate to another scene. Some examples follow: // 1. Trigger a storyboard segue // viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil) // 2. Present another view controller programmatically // viewController.presentViewController(someWhereViewController, animated: true, completion: nil) // 3. Ask the navigation controller to push another view controller onto the stack // viewController.navigationController?.pushViewController(someWhereViewController, animated: true) // 4. Present a view controller from a different storyboard // let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil) // let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController // viewController.navigationController?.pushViewController(someWhereViewController, animated: true) } // MARK: Communication func passDataToNextScene(segue: UIStoryboardSegue) { // NOTE: Teach the router which scenes it can communicate with if segue.identifier == "ShowSomewhereScene" { passDataToSomewhereScene(segue) } } func passDataToSomewhereScene(segue: UIStoryboardSegue) { // NOTE: Teach the router how to pass data to the next scene // let someWhereViewController = segue.destinationViewController as! SomeWhereViewController // someWhereViewController.output.name = viewController.output.name } }
mit
2f58d56f467707011706a3ec099063cb
31.403226
110
0.738676
5.286842
false
false
false
false
nzaghini/mastering-reuse-viper
Weather/Modules/WeatherLocation/Core/Interactor/WeatherLocationInteractor.swift
2
1819
import Foundation public enum FindLocationResult { case success(locations: [Location]) case failure(reason: Error) } /// The weather location module interactor public protocol WeatherLocationInteractor { /// Allows location search based on text /// /// - parameter text: the location text /// - parameter completion: the result of location search func findLocation(_ text: String, completion: @escaping (FindLocationResult) -> Void) /// Allows selection of location /// /// - parameter location: the weather location model func selectLocation(_ location: Location) } class WeatherLocationCitiesInteractor: WeatherLocationInteractor { let locationService: LocationService let locationStoreService: LocationStoreService init(locationService: LocationService, locationStoreService: LocationStoreService) { self.locationService = locationService self.locationStoreService = locationStoreService } func findLocation(_ text: String, completion: @escaping (FindLocationResult) -> Void) { self.locationService.fetchLocations(withName: text) { (locations, error) in var result: FindLocationResult! if let error = error { result = FindLocationResult.failure(reason: error) } else if let locations = locations { result = FindLocationResult.success(locations: locations) } else { let error = NSError(domain: NSURLErrorDomain, code: 500, userInfo: nil) result = FindLocationResult.failure(reason: error) } completion(result) } } func selectLocation(_ location: Location) { self.locationStoreService.addLocation(location) } }
mit
a93dc49834ed8464d065eb23d228312c
34.666667
91
0.662452
5.334311
false
false
false
false
JaSpa/swift
test/Constraints/lvalues.swift
7
8278
// RUN: %target-typecheck-verify-swift func f0(_ x: inout Int) {} func f1<T>(_ x: inout T) {} func f2(_ x: inout X) {} func f2(_ x: inout Double) {} class Reftype { var property: Double { get {} set {} } } struct X { subscript(i: Int) -> Float { get {} set {} } var property: Double { get {} set {} } func genuflect() {} } struct Y { subscript(i: Int) -> Float { get {} set {} } subscript(f: Float) -> Int { get {} set {} } } var i : Int var f : Float var x : X var y : Y func +=(lhs: inout X, rhs : X) {} func +=(lhs: inout Double, rhs : Double) {} prefix func ++(rhs: inout X) {} postfix func ++(lhs: inout X) {} f0(&i) f1(&i) f1(&x[i]) f1(&x.property) f1(&y[i]) // Missing '&' f0(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{4-4=&}} f1(y[i]) // expected-error{{passing value of type 'Float' to an inout parameter requires explicit '&'}} {{4-4=&}} // Assignment operators x += x ++x var yi = y[i] // Non-settable lvalues var non_settable_x : X { return x } struct Z { var non_settable_x: X { get {} } var non_settable_reftype: Reftype { get {} } var settable_x : X subscript(i: Int) -> Double { get {} } subscript(_: (i: Int, j: Int)) -> X { get {} } } var z : Z func fz() -> Z {} func fref() -> Reftype {} // non-settable var is non-settable: // - assignment non_settable_x = x // expected-error{{cannot assign to value: 'non_settable_x' is a get-only property}} // - inout (mono) f2(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout (generic) f1(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout assignment non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++non_settable_x // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // non-settable property is non-settable: z.non_settable_x = x // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++z.non_settable_x // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // non-settable subscript is non-settable: z[0] = 0.0 // expected-error{{cannot assign through subscript: subscript is get-only}} f2(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} f1(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} z[0] += 0.0 // expected-error{{left side of mutating operator isn't mutable: subscript is get-only}} ++z[0] // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} // settable property of an rvalue value type is non-settable: fz().settable_x = x // expected-error{{cannot assign to property: 'fz' returns immutable value}} f2(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} f1(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} fz().settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'fz' returns immutable value}} ++fz().settable_x // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} // settable property of an rvalue reference type IS SETTABLE: fref().property = 0.0 f2(&fref().property) f1(&fref().property) fref().property += 0.0 fref().property += 1 // settable property of a non-settable value type is non-settable: z.non_settable_x.property = 1.0 // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x.property += 1.0 // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++z.non_settable_x.property // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // settable property of a non-settable reference type IS SETTABLE: z.non_settable_reftype.property = 1.0 f2(&z.non_settable_reftype.property) f1(&z.non_settable_reftype.property) z.non_settable_reftype.property += 1.0 z.non_settable_reftype.property += 1 // regressions with non-settable subscripts in value contexts _ = z[0] == 0 var d : Double d = z[0] // regressions with subscripts that return generic types var xs:[X] _ = xs[0].property struct A<T> { subscript(i: Int) -> T { get {} } } struct B { subscript(i: Int) -> Int { get {} } } var a:A<B> _ = a[0][0] // Instance members of struct metatypes. struct FooStruct { func instanceFunc0() {} } func testFooStruct() { FooStruct.instanceFunc0(FooStruct())() } // Don't load from explicit lvalues. func takesInt(_ x: Int) {} func testInOut(_ arg: inout Int) { var x : Int takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} } // Don't infer inout types. var ir = &i // expected-error{{variable has type 'inout Int' which includes nested inout parameters}} \ // expected-error{{'&' can only appear immediately in a call argument list}} var ir2 = ((&i)) // expected-error{{variable has type 'inout Int' which includes nested inout parameters}} \ // expected-error{{'&' can only appear immediately in a call argument list}} // <rdar://problem/17133089> func takeArrayRef(_ x: inout Array<String>) { } // rdar://22308291 takeArrayRef(["asdf", "1234"]) // expected-error{{contextual type 'inout Array<String>' cannot be used with array literal}} // <rdar://problem/19835413> Reference to value from array changed func rdar19835413() { func f1(_ p: UnsafeMutableRawPointer) {} func f2(_ a: [Int], i: Int, pi: UnsafeMutablePointer<Int>) { var a = a f1(&a) f1(&a[i]) f1(&a[0]) f1(pi) f1(pi) } } // <rdar://problem/21877598> Crash when accessing stored property without // setter from constructor protocol Radish { var root: Int { get } } public struct Kale : Radish { public let root : Int public init() { let _ = Kale().root self.root = 0 } } func testImmutableUnsafePointer(_ p: UnsafePointer<Int>) { p.pointee = 1 // expected-error {{cannot assign to property: 'pointee' is a get-only property}} p[0] = 1 // expected-error {{cannot assign through subscript: subscript is get-only}} } // <https://bugs.swift.org/browse/SR-7> Inferring closure param type to // inout crashes compiler let g = { x in f0(x) } // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{19-19=&}} // <rdar://problem/17245353> Crash with optional closure taking inout func rdar17245353() { typealias Fn = (inout Int) -> () func getFn() -> Fn? { return nil } let _: (inout UInt, UInt) -> Void = { $0 += $1 } } // <rdar://problem/23131768> Bugs related to closures with inout parameters func rdar23131768() { func f(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f { $0 += 1 } // Crashes compiler func f2(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f2 { $0 = $0 + 1 } // previously error: Cannot convert value of type '_ -> ()' to expected type '(inout Int) -> Void' func f3(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f3 { (v: inout Int) -> Void in v += 1 } } // <rdar://problem/23331567> Swift: Compiler crash related to closures with inout parameter. func r23331567(_ fn: (_ x: inout Int) -> Void) { var a = 0 fn(&a) } r23331567 { $0 += 1 }
apache-2.0
9ce7f23243c84f4e3d4d7342ae000091
34.225532
139
0.671177
3.284921
false
false
false
false
vector-im/riot-ios
Riot/Modules/KeyBackup/Setup/Passphrase/KeyBackupSetupPassphraseViewController.swift
2
15760
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class KeyBackupSetupPassphraseViewController: UIViewController { // MARK: - Constants private enum Constants { static let animationDuration: TimeInterval = 0.3 } // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private weak var formBackgroundView: UIView! @IBOutlet private weak var passphraseTitleLabel: UILabel! @IBOutlet private weak var passphraseTextField: UITextField! @IBOutlet private weak var passphraseAdditionalInfoView: UIView! @IBOutlet private weak var passphraseStrengthView: PasswordStrengthView! @IBOutlet private weak var passphraseAdditionalLabel: UILabel! @IBOutlet private weak var formSeparatorView: UIView! @IBOutlet private weak var confirmPassphraseTitleLabel: UILabel! @IBOutlet private weak var confirmPassphraseTextField: UITextField! @IBOutlet private weak var confirmPassphraseAdditionalInfoView: UIView! @IBOutlet private weak var confirmPassphraseAdditionalLabel: UILabel! @IBOutlet private weak var setPassphraseButtonBackgroundView: UIView! @IBOutlet private weak var setPassphraseButton: UIButton! @IBOutlet private weak var setUpRecoveryKeyInfoLabel: UILabel! @IBOutlet private weak var setUpRecoveryKeyButton: UIButton! // MARK: Private private var isFirstViewAppearing: Bool = true private var isPassphraseTextFieldEditedOnce: Bool = false private var isConfirmPassphraseTextFieldEditedOnce: Bool = false private var keyboardAvoider: KeyboardAvoider? private var viewModel: KeyBackupSetupPassphraseViewModelType! private var theme: Theme! private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private weak var skipAlertController: UIAlertController? // MARK: - Setup class func instantiate(with viewModel: KeyBackupSetupPassphraseViewModelType) -> KeyBackupSetupPassphraseViewController { let viewController = StoryboardScene.KeyBackupSetupPassphraseViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = VectorL10n.keyBackupSetupTitle self.vc_removeBackTitle() self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.keyboardAvoider?.startAvoiding() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.isFirstViewAppearing { self.isFirstViewAppearing = false } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.view.endEditing(true) self.keyboardAvoider?.stopAvoiding() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if self.isFirstViewAppearing { // Workaround to layout passphraseStrengthView corner radius self.passphraseStrengthView.setNeedsLayout() } } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.titleLabel.textColor = theme.textPrimaryColor self.informationLabel.textColor = theme.textPrimaryColor self.formBackgroundView.backgroundColor = theme.backgroundColor self.passphraseTitleLabel.textColor = theme.textPrimaryColor theme.applyStyle(onTextField: self.passphraseTextField) self.passphraseTextField.attributedPlaceholder = NSAttributedString(string: VectorL10n.keyBackupSetupPassphrasePassphrasePlaceholder, attributes: [.foregroundColor: theme.placeholderTextColor]) self.updatePassphraseAdditionalLabel() self.formSeparatorView.backgroundColor = theme.lineBreakColor self.confirmPassphraseTitleLabel.textColor = theme.textPrimaryColor theme.applyStyle(onTextField: self.confirmPassphraseTextField) self.confirmPassphraseTextField.attributedPlaceholder = NSAttributedString(string: VectorL10n.keyBackupSetupPassphraseConfirmPassphraseTitle, attributes: [.foregroundColor: theme.placeholderTextColor]) self.updateConfirmPassphraseAdditionalLabel() self.setPassphraseButton.backgroundColor = theme.backgroundColor theme.applyStyle(onButton: self.setPassphraseButton) self.setUpRecoveryKeyInfoLabel.textColor = theme.textPrimaryColor theme.applyStyle(onButton: self.setUpRecoveryKeyButton) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.navigationItem.rightBarButtonItem = cancelBarButtonItem self.scrollView.keyboardDismissMode = .interactive self.titleLabel.text = VectorL10n.keyBackupSetupPassphraseTitle self.informationLabel.text = VectorL10n.keyBackupSetupPassphraseInfo self.passphraseTitleLabel.text = VectorL10n.keyBackupSetupPassphrasePassphraseTitle self.passphraseTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) self.passphraseStrengthView.strength = self.viewModel.passphraseStrength self.passphraseAdditionalInfoView.isHidden = true self.confirmPassphraseTitleLabel.text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseTitle self.confirmPassphraseTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) self.confirmPassphraseAdditionalInfoView.isHidden = true self.setPassphraseButton.vc_enableMultiLinesTitle() self.setPassphraseButton.setTitle(VectorL10n.keyBackupSetupPassphraseSetPassphraseAction, for: .normal) self.updateSetPassphraseButton() } private func showPassphraseAdditionalInfo(animated: Bool) { guard self.passphraseAdditionalInfoView.isHidden else { return } UIView.animate(withDuration: Constants.animationDuration) { self.passphraseAdditionalInfoView.isHidden = false } } private func showConfirmPassphraseAdditionalInfo(animated: Bool) { guard self.confirmPassphraseAdditionalInfoView.isHidden else { return } UIView.animate(withDuration: Constants.animationDuration) { self.confirmPassphraseAdditionalInfoView.isHidden = false } } private func hideConfirmPassphraseAdditionalInfo(animated: Bool) { guard self.confirmPassphraseAdditionalInfoView.isHidden == false else { return } UIView.animate(withDuration: Constants.animationDuration) { self.confirmPassphraseAdditionalInfoView.isHidden = true } } private func updatePassphraseStrengthView() { self.passphraseStrengthView.strength = self.viewModel.passphraseStrength } private func updatePassphraseAdditionalLabel() { let text: String let textColor: UIColor if self.viewModel.isPassphraseValid { text = VectorL10n.keyBackupSetupPassphrasePassphraseValid textColor = self.theme.tintColor } else { text = VectorL10n.keyBackupSetupPassphrasePassphraseInvalid textColor = self.theme.noticeColor } self.passphraseAdditionalLabel.text = text self.passphraseAdditionalLabel.textColor = textColor } private func updateConfirmPassphraseAdditionalLabel() { let text: String let textColor: UIColor if self.viewModel.isConfirmPassphraseValid { text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseValid textColor = self.theme.tintColor } else { text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseInvalid textColor = self.theme.noticeColor } self.confirmPassphraseAdditionalLabel.text = text self.confirmPassphraseAdditionalLabel.textColor = textColor } private func updateSetPassphraseButton() { self.setPassphraseButton.isEnabled = self.viewModel.isFormValid } private func render(viewState: KeyBackupSetupPassphraseViewState) { switch viewState { case .loading: self.renderLoading() case .loaded: self.renderLoaded() case .error(let error): self.render(error: error) } } private func renderLoading() { self.view.endEditing(true) self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded() { self.activityPresenter.removeCurrentActivityIndicator(animated: true) } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.hideSkipAlert(animated: false) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } private func showSkipAlert() { guard self.skipAlertController == nil else { return } let alertController = UIAlertController(title: VectorL10n.keyBackupSetupSkipAlertTitle, message: VectorL10n.keyBackupSetupSkipAlertMessage, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: VectorL10n.continue, style: .cancel, handler: { action in self.viewModel.process(viewAction: .skipAlertContinue) })) alertController.addAction(UIAlertAction(title: VectorL10n.keyBackupSetupSkipAlertSkipAction, style: .default, handler: { action in self.viewModel.process(viewAction: .skipAlertSkip) })) self.present(alertController, animated: true, completion: nil) self.skipAlertController = alertController } private func hideSkipAlert(animated: Bool) { self.skipAlertController?.dismiss(animated: true, completion: nil) } // MARK: - Actions @IBAction private func passphraseVisibilityButtonAction(_ sender: Any) { guard self.isPassphraseTextFieldEditedOnce else { return } self.passphraseTextField.isSecureTextEntry = !self.passphraseTextField.isSecureTextEntry // TODO: Use this when project will be migrated to Swift 4.2 // self.passphraseTextField.isSecureTextEntry.toggle() } @objc private func textFieldDidChange(_ textField: UITextField) { if textField == self.passphraseTextField { self.viewModel.passphrase = textField.text self.updatePassphraseAdditionalLabel() self.updatePassphraseStrengthView() // Show passphrase additional info at first character entered if self.isPassphraseTextFieldEditedOnce == false && textField.text?.isEmpty == false { self.isPassphraseTextFieldEditedOnce = true self.showPassphraseAdditionalInfo(animated: true) } } else { self.viewModel.confirmPassphrase = textField.text } // Show confirm passphrase additional info if needed self.updateConfirmPassphraseAdditionalLabel() if self.viewModel.confirmPassphrase?.isEmpty == false && self.viewModel.isPassphraseValid { self.showConfirmPassphraseAdditionalInfo(animated: true) } else { self.hideConfirmPassphraseAdditionalInfo(animated: true) } // Enable validate button if form is valid self.updateSetPassphraseButton() } @IBAction private func setPassphraseButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .setupPassphrase) } @IBAction private func setUpRecoveryKeyButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .setupRecoveryKey) } private func cancelButtonAction() { self.viewModel.process(viewAction: .skip) } } // MARK: - UITextFieldDelegate extension KeyBackupSetupPassphraseViewController: UITextFieldDelegate { func textFieldShouldClear(_ textField: UITextField) -> Bool { self.textFieldDidChange(textField) return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == self.passphraseTextField { self.confirmPassphraseTextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return true } } // MARK: - KeyBackupSetupPassphraseViewModelViewDelegate extension KeyBackupSetupPassphraseViewController: KeyBackupSetupPassphraseViewModelViewDelegate { func keyBackupSetupPassphraseViewModel(_ viewModel: KeyBackupSetupPassphraseViewModelType, didUpdateViewState viewSate: KeyBackupSetupPassphraseViewState) { self.render(viewState: viewSate) } func keyBackupSetupPassphraseViewModelShowSkipAlert(_ viewModel: KeyBackupSetupPassphraseViewModelType) { self.showSkipAlert() } }
apache-2.0
dab3ceb9b6973d158dfd48bd4499f5f4
37.345499
160
0.683756
5.940445
false
false
false
false
ton-katsu/ImageLoaderSwift
ImageLoaderExample/SuspendSampleViewController.swift
1
2865
// // SuspendSampleViewController.swift // ImageLoaderExample // // Created by Hirohisa Kawasaki on 12/18/14. // Copyright (c) 2014 Hirohisa Kawasaki. All rights reserved. // import UIKit import ImageLoader class SuspendSampleViewController: UITableViewController { var URLs = [NSURL]() override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") let buttonItem = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "play") navigationItem.rightBarButtonItem = buttonItem } func play() { toggle(loading: true) startLoading() } func pause() { toggle(loading: false) pauseLoading() } func toggle(#loading: Bool) { var buttonItem = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "play") if loading == true { buttonItem = UIBarButtonItem(barButtonSystemItem: .Pause, target: self, action: "pause") } navigationItem.rightBarButtonItem = buttonItem } func startLoading() { let start = URLs.count for i in start...start+10 { let URL = NSURL.imageURL(i) ImageLoader.load(URL).completionHandler { completedURL, image, error, cacheType in self.insertRow(completedURL) } } } func pauseLoading() { let end = URLs.count for i in end-10...end { let URL = NSURL.imageURL(i) ImageLoader.suspend(URL) } } func insertRow(URL: NSURL) { dispatch_async(dispatch_get_main_queue(), { let indexPath = NSIndexPath(forRow: self.URLs.count, inSection: 0) self.URLs.append(URL) self.tableView.beginUpdates() self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) self.tableView.endUpdates() var state = ImageLoader.state if state == .Ready { self.toggle(loading: false) } }) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let URL = self.URLs[indexPath.row] let placeholder = UIImage(named: "black.jpg")! cell.textLabel?.text = URL.absoluteString if let image = ImageLoader.cache(URL) { cell.imageView?.image = image } return cell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return URLs.count } }
mit
b0759d79a9825cbf934454550f987ab5
26.825243
118
0.623386
4.965338
false
false
false
false
yllan/Cadence
Cadence/ManualController.swift
1
2813
// // ManualController.swift // Cadence // // Created by Yung-Luen Lan on 10/13/15. // Copyright © 2015 yllan. All rights reserved. // import Foundation import UIKit class ManualController: UIViewController, UIScrollViewDelegate { var scrollView: UIScrollView! var scrollFromBeign = false var scrollFromEnd = false override func viewDidLoad() { super.viewDidLoad() self.view.opaque = true self.view.backgroundColor = UIColor.clearColor() self.scrollView = UIScrollView(frame: self.view.bounds) self.scrollView.backgroundColor = UIColor.clearColor() self.scrollView.showsVerticalScrollIndicator = false self.scrollView.delegate = self self.view.addSubview(self.scrollView) let manualImage = UIImage.init(named: "Manual") let imageView = UIImageView(image: manualImage) imageView.backgroundColor = UIColor.whiteColor() self.scrollView.addSubview(imageView) imageView.frame = CGRectMake((self.scrollView.frame.size.width - (manualImage?.size.width)!) / 2, 0, (manualImage?.size.width)!, (manualImage?.size.height)!) self.scrollView.contentSize = CGSizeMake(max(self.scrollView.frame.size.width, (manualImage?.size.width)!), (manualImage?.size.height)!) } func scrollViewWillBeginDragging(scrollView: UIScrollView) { scrollFromBeign = (scrollView.contentOffset.y <= 0) scrollFromEnd = (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let threshold: CGFloat = 2.0 if (scrollFromBeign && velocity.y <= -threshold) { let v = scrollView.snapshotViewAfterScreenUpdates(false) scrollView.hidden = true self.view.addSubview(v) UIView.animateWithDuration(0.5, animations: { () -> Void in v.frame = CGRectOffset(self.view.frame, 0, self.view.frame.size.height * 2) }, completion: { (finished) -> Void in self.dismissViewControllerAnimated(false) {} }) } else if (scrollFromEnd && velocity.y >= threshold) { let v = scrollView.snapshotViewAfterScreenUpdates(false) scrollView.hidden = true self.view.addSubview(v) UIView.animateWithDuration(0.5, animations: { () -> Void in v.frame = CGRectOffset(self.view.frame, 0, -self.view.frame.size.height * 2) }, completion: { (finished) -> Void in self.dismissViewControllerAnimated(false) {} }) } } }
bsd-2-clause
3085b6484bbc09c9fa7e2583e7a9a9fc
40.367647
165
0.641892
4.710218
false
false
false
false
ashleybrgr/surfPlay
surfPlay/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationLineScaleParty.swift
14
2669
// // NVActivityIndicatorAnimationLineScaleParty.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 class NVActivityIndicatorAnimationLineScaleParty: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let lineSize = size.width / 7 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let durations: [CFTimeInterval] = [1.26, 0.43, 1.01, 0.73] let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0.77, 0.29, 0.28, 0.74] let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) // Animation let animation = CAKeyframeAnimation(keyPath: "transform.scale") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.5, 1] animation.repeatCount = HUGE animation.isRemovedOnCompletion = false for i in 0 ..< 4 { let line = NVActivityIndicatorShape.line.layerWith(size: CGSize(width: lineSize, height: size.height), color: color) let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height) animation.beginTime = beginTime + beginTimes[i] animation.duration = durations[i] line.frame = frame line.add(animation, forKey: "animation") layer.addSublayer(line) } } }
apache-2.0
4a400ee28efc158f6661f9eeb7d21aca
42.754098
128
0.698389
4.500843
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift
3
10370
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf // http://keccak.noekeon.org/specs_summary.html // #if os(Linux) || os(Android) || os(FreeBSD) import Glibc #else import Darwin #endif public final class SHA3: DigestType { let round_constants: Array<UInt64> = [ 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, ] public let blockSize: Int public let digestLength: Int public let markByte: UInt8 fileprivate var accumulated = Array<UInt8>() fileprivate var accumulatedHash: Array<UInt64> public enum Variant { case sha224, sha256, sha384, sha512, keccak224, keccak256, keccak384, keccak512 var digestLength: Int { return 100 - (blockSize / 2) } var blockSize: Int { return (1600 - outputLength * 2) / 8 } var markByte: UInt8 { switch self { case .sha224, .sha256, .sha384, .sha512: return 0x06 // 0x1F for SHAKE case .keccak224, .keccak256, .keccak384, .keccak512: return 0x01 } } public var outputLength: Int { switch self { case .sha224, .keccak224: return 224 case .sha256, .keccak256: return 256 case .sha384, .keccak384: return 384 case .sha512, .keccak512: return 512 } } } public init(variant: SHA3.Variant) { blockSize = variant.blockSize digestLength = variant.digestLength markByte = variant.markByte accumulatedHash = Array<UInt64>(repeating: 0, count: digestLength) } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try update(withBytes: bytes.slice, isLast: true) } catch { return [] } } /// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z<w, let /// C[x,z]=A[x, 0,z] ⊕ A[x, 1,z] ⊕ A[x, 2,z] ⊕ A[x, 3,z] ⊕ A[x, 4,z]. /// 2. For all pairs (x, z) such that 0≤x<5 and 0≤z<w let /// D[x,z]=C[(x1) mod 5, z] ⊕ C[(x+1) mod 5, (z –1) mod w]. /// 3. For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let /// A′[x, y,z] = A[x, y,z] ⊕ D[x,z]. private func θ(_ a: inout Array<UInt64>) { let c = UnsafeMutablePointer<UInt64>.allocate(capacity: 5) c.initialize(repeating: 0, count: 5) defer { c.deinitialize(count: 5) c.deallocate() } let d = UnsafeMutablePointer<UInt64>.allocate(capacity: 5) d.initialize(repeating: 0, count: 5) defer { d.deinitialize(count: 5) d.deallocate() } for i in 0..<5 { c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20] } d[0] = rotateLeft(c[1], by: 1) ^ c[4] d[1] = rotateLeft(c[2], by: 1) ^ c[0] d[2] = rotateLeft(c[3], by: 1) ^ c[1] d[3] = rotateLeft(c[4], by: 1) ^ c[2] d[4] = rotateLeft(c[0], by: 1) ^ c[3] for i in 0..<5 { a[i] ^= d[i] a[i &+ 5] ^= d[i] a[i &+ 10] ^= d[i] a[i &+ 15] ^= d[i] a[i &+ 20] ^= d[i] } } /// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z] private func π(_ a: inout Array<UInt64>) { let a1 = a[1] a[1] = a[6] a[6] = a[9] a[9] = a[22] a[22] = a[14] a[14] = a[20] a[20] = a[2] a[2] = a[12] a[12] = a[13] a[13] = a[19] a[19] = a[23] a[23] = a[15] a[15] = a[4] a[4] = a[24] a[24] = a[21] a[21] = a[8] a[8] = a[16] a[16] = a[5] a[5] = a[3] a[3] = a[18] a[18] = a[17] a[17] = a[11] a[11] = a[7] a[7] = a[10] a[10] = a1 } /// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let /// A′[x, y,z] = A[x, y,z] ⊕ ((A[(x+1) mod 5, y, z] ⊕ 1) ⋅ A[(x+2) mod 5, y, z]) private func χ(_ a: inout Array<UInt64>) { for i in stride(from: 0, to: 25, by: 5) { let a0 = a[0 &+ i] let a1 = a[1 &+ i] a[0 &+ i] ^= ~a1 & a[2 &+ i] a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i] a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i] a[3 &+ i] ^= ~a[4 &+ i] & a0 a[4 &+ i] ^= ~a0 & a1 } } private func ι(_ a: inout Array<UInt64>, round: Int) { a[0] ^= round_constants[round] } fileprivate func process(block chunk: ArraySlice<UInt64>, currentHash hh: inout Array<UInt64>) { // expand hh[0] ^= chunk[0].littleEndian hh[1] ^= chunk[1].littleEndian hh[2] ^= chunk[2].littleEndian hh[3] ^= chunk[3].littleEndian hh[4] ^= chunk[4].littleEndian hh[5] ^= chunk[5].littleEndian hh[6] ^= chunk[6].littleEndian hh[7] ^= chunk[7].littleEndian hh[8] ^= chunk[8].littleEndian if blockSize > 72 { // 72 / 8, sha-512 hh[9] ^= chunk[9].littleEndian hh[10] ^= chunk[10].littleEndian hh[11] ^= chunk[11].littleEndian hh[12] ^= chunk[12].littleEndian if blockSize > 104 { // 104 / 8, sha-384 hh[13] ^= chunk[13].littleEndian hh[14] ^= chunk[14].littleEndian hh[15] ^= chunk[15].littleEndian hh[16] ^= chunk[16].littleEndian if blockSize > 136 { // 136 / 8, sha-256 hh[17] ^= chunk[17].littleEndian // FULL_SHA3_FAMILY_SUPPORT if blockSize > 144 { // 144 / 8, sha-224 hh[18] ^= chunk[18].littleEndian hh[19] ^= chunk[19].littleEndian hh[20] ^= chunk[20].littleEndian hh[21] ^= chunk[21].littleEndian hh[22] ^= chunk[22].littleEndian hh[23] ^= chunk[23].littleEndian hh[24] ^= chunk[24].littleEndian } } } } // Keccak-f for round in 0..<24 { θ(&hh) hh[1] = rotateLeft(hh[1], by: 1) hh[2] = rotateLeft(hh[2], by: 62) hh[3] = rotateLeft(hh[3], by: 28) hh[4] = rotateLeft(hh[4], by: 27) hh[5] = rotateLeft(hh[5], by: 36) hh[6] = rotateLeft(hh[6], by: 44) hh[7] = rotateLeft(hh[7], by: 6) hh[8] = rotateLeft(hh[8], by: 55) hh[9] = rotateLeft(hh[9], by: 20) hh[10] = rotateLeft(hh[10], by: 3) hh[11] = rotateLeft(hh[11], by: 10) hh[12] = rotateLeft(hh[12], by: 43) hh[13] = rotateLeft(hh[13], by: 25) hh[14] = rotateLeft(hh[14], by: 39) hh[15] = rotateLeft(hh[15], by: 41) hh[16] = rotateLeft(hh[16], by: 45) hh[17] = rotateLeft(hh[17], by: 15) hh[18] = rotateLeft(hh[18], by: 21) hh[19] = rotateLeft(hh[19], by: 8) hh[20] = rotateLeft(hh[20], by: 18) hh[21] = rotateLeft(hh[21], by: 2) hh[22] = rotateLeft(hh[22], by: 61) hh[23] = rotateLeft(hh[23], by: 56) hh[24] = rotateLeft(hh[24], by: 14) π(&hh) χ(&hh) ι(&hh, round: round) } } } extension SHA3: Updatable { public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { accumulated += bytes if isLast { // Add padding let markByteIndex = accumulated.count // We need to always pad the input. Even if the input is a multiple of blockSize. let r = blockSize * 8 let q = (r / 8) - (accumulated.count % (r / 8)) accumulated += Array<UInt8>(repeating: 0, count: q) accumulated[markByteIndex] |= markByte accumulated[self.accumulated.count - 1] |= 0x80 } var processedBytes = 0 for chunk in accumulated.batched(by: blockSize) { if isLast || (accumulated.count - processedBytes) >= blockSize { process(block: chunk.toUInt64Array().slice, currentHash: &accumulatedHash) processedBytes += chunk.count } } accumulated.removeFirst(processedBytes) // TODO: verify performance, reduce vs for..in let result = accumulatedHash.reduce(Array<UInt8>()) { (result, value) -> Array<UInt8> in return result + value.bigEndian.bytes() } // reset hash value for instance if isLast { accumulatedHash = Array<UInt64>(repeating: 0, count: digestLength) } return Array(result[0..<self.digestLength]) } }
mit
be5f6aca03de20b80e5b2a3a265d4052
34.685121
217
0.512654
3.40813
false
false
false
false
freshOS/Komponents
KomponentsExample/LoginState.swift
1
887
// // LoginState.swift // Komponents // // Created by Sacha Durand Saint Omer on 24/04/2017. // Copyright © 2017 freshOS. All rights reserved. // import Foundation struct LoginState { var email = "HAHA" { didSet { validate() } } var password = "" { didSet { validate() } } var status = LoginStatus.unknown var emailValid = FieldValidationStatus.unknown var passwordValid = FieldValidationStatus.unknown func isFormvalid() -> Bool { return emailValid == . valid && passwordValid == .valid } private mutating func validate() { emailValid = email.contains("@") ? .valid : .invalid passwordValid = password.count >= 6 ? .valid : .invalid status = .unknown } } enum FieldValidationStatus { case unknown case valid case invalid } enum LoginStatus { case unknown case loading case success case error }
mit
d7a0e3e9ca5944372a6afaa52d7007e8
24.314286
90
0.655756
4.179245
false
false
false
false
TarangKhanna/Inspirator
WorkoutMotivation/ProgrammingVC.swift
2
2121
// // ProgrammingVC.swift // WorkoutMotivation // // Created by Tarang khanna on 5/17/15. // Copyright (c) 2015 Tarang khanna. All rights reserved. // import UIKit class ProgrammingVC: UIViewController { //let q1 = ProgrammingQuotes() @IBOutlet var webView: UIWebView! @IBOutlet weak var Qlabel: UILabel! @IBOutlet var activity: UIActivityIndicatorView! @IBOutlet var ImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1) //Qlabel.text = q1.getQuote() //Qlabel.textColor = UIColor.greenColor() //ImageView.image = UIImage(named: "Weights\(arc4random_uniform(10)).png") loadVideo() } func loadVideo() { let choose = arc4random_uniform(6) var requestURL = NSURL(string: "https://www.youtube.com/watch?v=ZpwEHIL_UZ4") switch choose { case 0: requestURL = NSURL(string: "https://www.youtube.com/watch?v=E0qlr22cF14&spfreload=10") case 1: requestURL = NSURL(string: "https://www.youtube.com/watch?v=xDVoIVX1pAc&spfreload=10") case 2: requestURL = NSURL(string: "https://www.youtube.com/watch?v=Gvi05OMB5uA&spfreload=10") case 3: requestURL = NSURL(string: "https://www.youtube.com/watch?v=cWAEUMuxQvw&spfreload=10") case 4: requestURL = NSURL(string: "https://www.youtube.com/watch?v=Sp7253XSm-g&spfreload=10") case 5: requestURL = NSURL(string: "https://www.youtube.com/watch?v=j_yGRhdhVhY") default: requestURL = NSURL(string: "https://www.youtube.com/watch?v=E0qlr22cF14&spfreload=10") } let request = NSURLRequest(URL: requestURL!) webView.loadRequest(request) } func webViewDidStartLoad(_ : UIWebView) { activity.startAnimating() //NSLog("started") } func webViewDidFinishLoad(_ : UIWebView) { activity.stopAnimating() //NSLog("done") } }
apache-2.0
d0e907955851b09d13a9005429e17d8b
33.770492
113
0.620934
3.58277
false
false
false
false
sviatoslav/EndpointProcedure
Sources/MagicalRecord/MagicalRecordObjectsArrayMappingProcedure.swift
1
2072
// // MagicalRecordObjectsArrayMappingProcedure.swift // EndpointProcedure // // Created by Sviatoslav Yakymiv on 2/18/17. // Copyright © 2017 Sviatoslav Yakymiv. All rights reserved. // #if canImport(ProcedureKit) import ProcedureKit #endif #if canImport(MagicalRecord) import MagicalRecord #endif /// Procedure used for objects array mapping. `T` should be `Array` of subclass of `NSManagedObject` class MagicalRecordObjectsArrayMappingProcedure<T>: MagicalRecordMappingProcedure<T> { /// `T.Element.self` if `T == Array` and `T.Element: NSManagedObject`, `nil` otherwise override class var managedObjectType: NSManagedObject.Type? { guard let elementsContainerType = T.self as? ElementsContainer.Type else { return nil } guard NSManagedObject.self != elementsContainerType.elementType else { return nil } return elementsContainerType.elementType as? NSManagedObject.Type } override func performMapping(with completion: (ProcedureResult<T>) -> Void) throws { guard let array = self.input.value as? [[AnyHashable: Any]] else { throw ProcedureKitError.requirementNotSatisfied() } guard let managedObjectType = type(of: self).managedObjectType else { throw MagicalRecordMappingProcedureError.unsupportedType } guard managedObjectType.mr_entityDescription() != nil else { throw MagicalRecordMappingProcedureError.unableMapResponse } var importResult: T? if let moc = self.managedObjectContext { moc.performAndWait { importResult = managedObjectType.mr_import(from: array, in: moc) as? T } } else { MagicalRecord.save(blockAndWait: { moc in importResult = managedObjectType.mr_import(from: array, in: moc) as? T }) } guard let result = importResult else { throw MagicalRecordMappingProcedureError.unableMapResponse } completion(.success(result)) } }
mit
8ddf7ef4ef7c7a084ce7e218b3e0451b
36.654545
100
0.671173
4.942721
false
false
false
false
sviatoslav/EndpointProcedure
Examples/Using DefaultConfigurationProvider and HTTPRequestDataBuidlerProvider.playground/Sources/Support.swift
2
5098
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation import Dispatch internal func _abstractMethod(file: StaticString = #file, line: UInt = #line) { fatalError("Method must be overriden", file: file, line: line) } extension Dictionary { internal init<S: Sequence>(sequence: S, keyMapper: (Value) -> Key?) where S.Iterator.Element == Value { self.init() for item in sequence { if let key = keyMapper(item) { self[key] = item } } } } // MARK: - Thread Safety protocol ReadWriteLock { mutating func read<T>(_ block: () throws -> T) rethrows -> T mutating func write_async(_ block: @escaping () -> Void, completion: (() -> Void)?) mutating func write_sync<T>(_ block: () throws -> T) rethrows -> T } extension ReadWriteLock { mutating func write_async(_ block: @escaping () -> Void) { write_async(block, completion: nil) } } struct Lock: ReadWriteLock { let queue = DispatchQueue.concurrent(label: "run.kit.procedure.ProcedureKit.Lock", qos: .userInitiated) mutating func read<T>(_ block: () throws -> T) rethrows -> T { return try queue.sync(execute: block) } mutating func write_async(_ block: @escaping () -> Void, completion: (() -> Void)?) { queue.async(group: nil, flags: [.barrier]) { block() if let completion = completion { DispatchQueue.main.async(execute: completion) } } } mutating func write_sync<T>(_ block: () throws -> T) rethrows -> T { let result = try queue.sync(flags: [.barrier]) { try block() } return result } } /// A wrapper class for a pthread_mutex final public class PThreadMutex { private var mutex = pthread_mutex_t() public init() { let result = pthread_mutex_init(&mutex, nil) precondition(result == 0, "Failed to create pthread mutex") } deinit { let result = pthread_mutex_destroy(&mutex) assert(result == 0, "Failed to destroy mutex") } fileprivate func lock() { let result = pthread_mutex_lock(&mutex) assert(result == 0, "Failed to lock mutex") } fileprivate func unlock() { let result = pthread_mutex_unlock(&mutex) assert(result == 0, "Failed to unlock mutex") } /// Convenience API to execute block after acquiring the lock /// /// - Parameter block: the block to run /// - Returns: returns the return value of the block public func withCriticalScope<T>(block: () -> T) -> T { lock() defer { unlock() } let value = block() return value } } public class Protector<T> { private var lock = PThreadMutex() private var ward: T public init(_ ward: T) { self.ward = ward } public var access: T { var value: T? lock.lock() value = ward lock.unlock() return value! } public func read<U>(_ block: (T) -> U) -> U { return lock.withCriticalScope { block(self.ward) } } /// Synchronously modify the protected value /// /// - Returns: The value returned by the `block`, if any. (discardable) @discardableResult public func write<U>(_ block: (inout T) -> U) -> U { return lock.withCriticalScope { block(&self.ward) } } /// Synchronously overwrite the protected value public func overwrite(with newValue: T) { write { (ward: inout T) in ward = newValue } } } public extension Protector where T: RangeReplaceableCollection { func append(_ newElement: T.Iterator.Element) { write { (ward: inout T) in ward.append(newElement) } } func append<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == T.Iterator.Element { write { (ward: inout T) in ward.append(contentsOf: newElements) } } func append<C: Collection>(contentsOf newElements: C) where C.Iterator.Element == T.Iterator.Element { write { (ward: inout T) in ward.append(contentsOf: newElements) } } } public extension Protector where T: Strideable { func advance(by stride: T.Stride) { write { (ward: inout T) in ward = ward.advanced(by: stride) } } } public extension NSLock { /// Convenience API to execute block after acquiring the lock /// /// - Parameter block: the block to run /// - Returns: returns the return value of the block func withCriticalScope<T>(block: () -> T) -> T { lock() let value = block() unlock() return value } } public extension NSRecursiveLock { /// Convenience API to execute block after acquiring the lock /// /// - Parameter block: the block to run /// - Returns: returns the return value of the block func withCriticalScope<T>(block: () -> T) -> T { lock() let value = block() unlock() return value } }
mit
b44a1d5fbf241617a2f1f5ea92338664
25.546875
107
0.588189
4.188168
false
false
false
false
material-components/material-components-ios
components/Dialogs/examples/DialogsLongAlertExampleViewController.swift
2
4085
// Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import MaterialComponents.MaterialButtons import MaterialComponents.MaterialButtons_Theming import MaterialComponents.MaterialDialogs import MaterialComponents.MaterialDialogs_Theming import MaterialComponents.MaterialContainerScheme class DialogsLongAlertExampleViewController: UIViewController { let textButton = MDCButton() @objc var containerScheme: MDCContainerScheming = MDCContainerScheme() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = containerScheme.colorScheme.backgroundColor textButton.setTitle("PRESENT ALERT", for: UIControl.State()) textButton.setTitleColor(UIColor(white: 0.1, alpha: 1), for: UIControl.State()) textButton.sizeToFit() textButton.translatesAutoresizingMaskIntoConstraints = false textButton.addTarget(self, action: #selector(tap), for: .touchUpInside) textButton.applyTextTheme(withScheme: containerScheme) self.view.addSubview(textButton) NSLayoutConstraint.activate([ NSLayoutConstraint( item: textButton, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint( item: textButton, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 0.0), ]) } @objc func tap(_ sender: Any) { let messageString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur " + "ultricies diam libero, eget porta arcu feugiat sit amet. Maecenas placerat felis sed risus " + "maximus tempus. Integer feugiat, augue in pellentesque dictum, justo erat ultricies leo, " + "quis eleifend nisi eros dictum mi. In finibus vulputate eros, in luctus diam auctor in. " + "Aliquam fringilla neque at augue dictum iaculis. Etiam ac pellentesque lectus. Aenean " + "vestibulum, tortor nec cursus euismod, lectus tortor rhoncus massa, eu interdum lectus urna " + "ut nulla. Phasellus elementum lorem sit amet sapien dictum, vel cursus est semper. Aenean " + "vel turpis maximus, accumsan dui quis, cursus turpis. Nunc a tincidunt nunc, ut tempus " + "libero. Morbi ut orci laoreet, luctus neque nec, rhoncus enim. Cras dui erat, blandit ac " + "malesuada vitae, fringilla ac ante. Nullam dui diam, condimentum vitae mi et, dictum " + "euismod libero. Aliquam commodo urna vitae massa convallis aliquet." let materialAlertController = MDCAlertController(title: nil, message: messageString) let action = MDCAlertAction(title: "OK") { (_) in print("OK") } materialAlertController.addAction(action) materialAlertController.applyTheme(withScheme: containerScheme) self.present(materialAlertController, animated: true, completion: nil) } } // MARK: Catalog by convention extension DialogsLongAlertExampleViewController { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Dialogs", "Swift Alert Demo"], "primaryDemo": false, "presentable": false, ] } } // MARK: Snapshot Testing by Convention extension DialogsLongAlertExampleViewController { func resetTests() { if presentedViewController != nil { dismiss(animated: false) } } @objc func testPresented() { resetTests() tap(UIButton()) } }
apache-2.0
089daa733d8d77a94f8be2acf4bb5f5f
36.477064
102
0.719706
4.668571
false
false
false
false
Palleas/IantoJones
IantoJones/ControlPanel.swift
1
1847
// // ControlPanel.swift // IantoJones // // Created by Romain Pouclet on 2015-07-16. // Copyright (c) 2015 Perfectly-Cooked. All rights reserved. // import UIKit public protocol Panel { var title: String { get } var viewController: UIViewController { get } } public class ValuesPanel: NSObject, Panel { public let title: String let values: [String] let listViewController = UITableViewController(style: .Grouped) init(title: String, values: [String]) { self.title = title self.values = values super.init() listViewController.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "ValueCell") listViewController.tableView.dataSource = self } public var viewController: UIViewController { return listViewController } } extension ValuesPanel: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ValueCell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = values[indexPath.row] return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return values.count } } public class ControlPanel: NSObject { private var panels = [String: Panel]() private let listViewController = UITableViewController(style: .Grouped) var viewController: UIViewController { return listViewController } override public init() { } public func registerPanel(panel: Panel, forSettingKey key: String) { panels[key] = panel } }
mit
c223e9f6b7db8ebd3a5a61a2678e2472
25.014085
120
0.677315
5.074176
false
false
false
false
sonsongithub/reddift
framework/OAuth/OAuth2Token.swift
1
10915
// // RDTOAuth2Token.swift // reddift // // Created by sonson on 2015/04/11. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** OAuth2 token for access reddit.com API. */ public struct OAuth2Token: Token { public static let baseURL = "https://www.reddit.com/api/v1" public let accessToken: String public let tokenType: String public let expiresIn: Int public let scope: String public let refreshToken: String public let name: String public let expiresDate: TimeInterval /** Initialize vacant OAuth2AppOnlyToken with JSON. */ public init() { self.name = "" self.accessToken = "" self.tokenType = "" self.expiresIn = 0 self.scope = "" self.refreshToken = "" self.expiresDate = Date.timeIntervalSinceReferenceDate + 0 } /** Initialize OAuth2AppOnlyToken with JSON. - parameter json: JSON as JSONDictionary should include "name", "access_token", "token_type", "expires_in", "scope" and "refresh_token". */ public init(_ json: JSONDictionary) { self.name = json["name"] as? String ?? "" self.accessToken = json["access_token"] as? String ?? "" self.tokenType = json["token_type"] as? String ?? "" let expiresIn = json["expires_in"] as? Int ?? 0 self.expiresIn = expiresIn self.expiresDate = json["expires_date"] as? TimeInterval ?? Date.timeIntervalSinceReferenceDate + Double(expiresIn) self.scope = json["scope"] as? String ?? "" self.refreshToken = json["refresh_token"] as? String ?? "" } /** Create OAuth2Token object from JSON. - parameter json: JSON object as JSONDictionary must include "name", "access_token", "token_type", "expires_in", "scope" and "refresh_token". If it does not, returns Result<NSError>. - returns: OAuth2Token object includes a new access token. */ static func tokenWithJSON(_ json: JSONAny) -> Result<OAuth2Token> { if let json = json as? JSONDictionary { if let _ = json["access_token"] as? String, let _ = json["token_type"] as? String, let _ = json["expires_in"] as? Int, let _ = json["scope"] as? String, let _ = json["refresh_token"] as? String { return Result(value: OAuth2Token(json)) } } return Result(error: ReddiftError.tokenJsonObjectIsNotDictionary as NSError) } /** Create URLRequest object to request getting an access token. - parameter code: The code which is obtained from OAuth2 redict URL at reddit.com. - returns: URLRequest object to request your access token. */ static func requestForOAuth(_ code: String) -> URLRequest? { guard let URL = URL(string: OAuth2Token.baseURL + "/access_token") else { return nil } var request = URLRequest(url: URL) do { try request.setRedditBasicAuthentication() let param = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + Config.sharedInstance.redirectURI let data = param.data(using: .utf8) request.httpBody = data request.httpMethod = "POST" return request } catch { print(error) return nil } } /** Create request object for refreshing access token. - returns: URLRequest object to request refreshing your access token. */ public func requestForRefreshing() -> URLRequest? { guard let URL = URL(string: OAuth2Token.baseURL + "/access_token") else { return nil } var request = URLRequest(url: URL) do { try request.setRedditBasicAuthentication() let param = "grant_type=refresh_token&refresh_token=" + refreshToken let data = param.data(using: .utf8) request.httpBody = data request.httpMethod = "POST" return request } catch { print(error) return nil } } /** Create request object for revoking access token. - returns: URLRequest object to request revoking your access token. */ func requestForRevoking() -> URLRequest? { guard let URL = URL(string: OAuth2Token.baseURL + "/revoke_token") else { return nil } var request = URLRequest(url: URL) do { try request.setRedditBasicAuthentication() let param = "token=" + accessToken + "&token_type_hint=access_token" let data = param.data(using: .utf8) request.httpBody = data request.httpMethod = "POST" return request } catch { print(error) return nil } } /** Request to refresh access token. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult public func refresh(_ completion: @escaping (Result<OAuth2Token>) -> Void) throws -> URLSessionDataTask { let session = URLSession(configuration: URLSessionConfiguration.default) guard let request = requestForRefreshing() else { throw ReddiftError.canNotCreateURLRequest as NSError } let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in let result = Result(from: Response(data: data, urlResponse: response), optional: error as NSError?) .flatMap(response2Data) .flatMap(data2Json) .flatMap({(json: JSONAny) -> Result<JSONDictionary> in if let json = json as? JSONDictionary { return Result(value: json) } return Result(error: ReddiftError.tokenJsonObjectIsNotDictionary as NSError) }) switch result { case .success(let json): var newJSON = json newJSON["name"] = self.name as AnyObject newJSON["refresh_token"] = self.refreshToken as AnyObject completion(OAuth2Token.tokenWithJSON(newJSON)) case .failure(let error): completion(Result(error: error)) } }) task.resume() return task } /** Request to revoke access token. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult public func revoke(_ completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let session = URLSession(configuration: URLSessionConfiguration.default) guard let request = requestForRevoking() else { throw ReddiftError.canNotCreateURLRequest as NSError } let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in let result = Result(from: Response(data: data, urlResponse: response), optional: error as NSError?) .flatMap(response2Data) .flatMap(data2Json) completion(result) }) task.resume() return task } /** Request to get a new access token. - parameter code: Code to be confirmed your identity by reddit. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult public static func getOAuth2Token(_ code: String, completion: @escaping (Result<OAuth2Token>) -> Void) throws -> URLSessionDataTask { let session = URLSession(configuration: URLSessionConfiguration.default) guard let request = requestForOAuth(code) else { throw ReddiftError.canNotCreateURLRequest as NSError } let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in let result = Result(from: Response(data: data, urlResponse: response), optional: error as NSError?) .flatMap(response2Data) .flatMap(data2Json) .flatMap(OAuth2Token.tokenWithJSON) switch result { case .success(let token): do { try token.getProfile({ (result) -> Void in completion(result) }) } catch { completion(Result(error: error as NSError)) } case .failure: completion(result) } }) task.resume() return task } /** Request to get user's own profile. Don't use this method after getting access token correctly. Use Session.getProfile instead of this. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult func getProfile(_ completion: @escaping (Result<OAuth2Token>) -> Void) throws -> URLSessionDataTask { guard let request = URLRequest.requestForOAuth(with: Session.OAuthEndpointURL, path: "/api/v1/me", method: "GET", token: self) else { throw ReddiftError.canNotCreateURLRequest as NSError } let session = URLSession(configuration: URLSessionConfiguration.default) let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in let result = Result(from: Response(data: data, urlResponse: response), optional: error as NSError?) .flatMap(response2Data) .flatMap(data2Json) .flatMap({ (json: JSONAny) -> Result<Account> in if let object = json as? JSONDictionary { return Result(fromOptional: Account(json: object), error: ReddiftError.accountJsonObjectIsMalformed as NSError) } return Result(error: ReddiftError.accountJsonObjectIsNotDictionary as NSError) }) switch result { case .success(let profile): let json = ["name": profile.name, "access_token": self.accessToken, "token_type": self.tokenType, "expires_in": self.expiresIn, "expires_date": self.expiresDate, "scope": self.scope, "refresh_token": self.refreshToken] as [String: Any] completion(OAuth2Token.tokenWithJSON(json)) case .failure(let error): completion(Result(error: error)) } }) task.resume() return task } }
mit
a0a722bba3ed89a2189f8516bec0772d
41.463035
251
0.607899
4.809608
false
false
false
false
davidiola/BitExplorer
loginViewController.swift
1
3598
// // loginViewController.swift // BitExplorer // // Created by David Iola on 2/25/17. // Copyright © 2017 David Iola. All rights reserved. // import UIKit import Firebase import FirebaseAuth import FirebaseDatabase class loginViewController: UIViewController { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var emailIcon: UILabel! @IBOutlet weak var passwordIcon: UILabel! override func viewDidLoad() { super.viewDidLoad() emailIcon.font = UIFont.fontAwesome(ofSize: 18) emailIcon.text = String.fontAwesomeIcon(name: .envelope) passwordIcon.font = UIFont.fontAwesome(ofSize: 20) passwordIcon.text = String.fontAwesomeIcon(name: .unlockAlt) self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(loginViewController.dismissKeyboard))) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func cancelTapped(_ sender: Any) { self.dismiss(animated: true, completion: nil) } func dismissKeyboard() { emailField.resignFirstResponder() passwordField.resignFirstResponder() } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { let email = emailField.text; let password = passwordField.text; //check firebase to login //successful login, "name" FIRAuth.auth()?.signIn(withEmail: email!, password: password!) { (user, error) in if error == nil { //edit this let myAlert = UIAlertController(title: "Alert", message: "Successful Login", preferredStyle: UIAlertControllerStyle.alert); let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) { action in self.performSegue(withIdentifier: "mainSegue", sender: self) } myAlert.addAction(okAction); self.present(myAlert, animated: true, completion: nil); } else { let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) //self.displayMyAlertMessage("Login failed") } } return false } }
mit
062b0ec1d00fc7d71ad1ad463ccf72d4
28.975
139
0.562691
5.965174
false
false
false
false
zendobk/SwiftUtils
Sources/Extensions/Double.swift
1
1521
// // Double.swift // SwiftUtils // // Created by DaoNV on 10/7/15. // Copyright © 2016 Asian Tech Co., Ltd. All rights reserved. // import Foundation extension Double { public var abs: Double { return Foundation.fabs(self) } public var sqrt: Double { return Foundation.sqrt(self) } public var floor: Double { return Foundation.floor(self) } public var ceil: Double { return Foundation.ceil(self) } public var round: Double { return Foundation.round(self) } public func clamp(_ min: Double, _ max: Double) -> Double { return Swift.max(min, Swift.min(max, self)) } public static func random(min: Double = 0, max: Double) -> Double { let diff = max - min let rand = Double(arc4random() % (UInt32(RAND_MAX) + 1)) return ((rand / Double(RAND_MAX)) * diff) + min } public func distance(_ precision: Int = -1, meter: String = "m", kilometer: String = "km") -> String { // precision < 0: Auto var num = self var unit = meter if num > 1000.0 { unit = kilometer num /= 1000.0 } if precision == -1 { if num == trunc(num) { return String(format: "%.0f%@", num, unit) } else { return String(format: "%.1f%@", num, unit) } } else { let format = "%.\(precision)f%@" return String(format: format, num, unit) } } }
apache-2.0
9be68c1f811bb8136281daa18bb3de6d
24.333333
129
0.528289
3.887468
false
false
false
false
subangstrom/Ronchi
MathFramework/MathFunctions.swift
1
2308
// // Functions.swift // Ronchigram // // Created by James LeBeau on 5/25/17. // Copyright © 2017 The Handsome Microscopist. All rights reserved. // import Foundation // Polynomial expansion of I0 from abramowitz_and_stegun, page 378 func besselI0(_ x:Float) -> Float { var i0:Float = 0.0 let t:Float = abs(x)/3.75 if (-3.75...3.75).contains(x){ let t2 = t * t let i0lowCoeffs:[Float] = [1.0, 3.5156229, 3.0899424, 1.2067492, 0.2659732, 0.0360768, 0.0045813] i0 = polynomialSum(i0lowCoeffs){t2*$0} }else{ // first value in coeffects for t^0 let ti:Float = 1.0/(t) let i0highCoeffs:[Float] = [0.39894228, 0.01328592, 0.00225319, -0.00157565, 0.00916281, -0.02057706, 0.02635537, -0.01647633, 0.00392377] i0 = polynomialSum(i0highCoeffs){ti*$0} i0 = i0/x.squareRoot()*expf(x) } return i0 } // Polynomial expansion of K0 from abramowitz_and_stegun, page 379 func besselK0(_ x:Float) -> Float { var k0:Float let ax = abs(x) if (ax > 0 && ax <= 2){ let x2 = (x * x)/4.0 let k0lowCoeffs:[Float] = [-0.57721566, 0.42278420, 0.23069756, 0.03488590, 0.00262698, 0.00010750, 0.00000740] k0 = -logf(x/2.0)*besselI0(x) k0 = k0+polynomialSum(k0lowCoeffs){x2*$0} }else if ax > 2{ // first value in coeffects for t^0 let xi:Float = 2.0/(x) let k0highCoeffs:[Float] = [1.25331414, -0.07832358, 0.02189568, -0.01062446, 0.00587872, -0.00251540, 0.00053208] k0 = polynomialSum(k0highCoeffs){xi*$0} k0 = k0/x.squareRoot()*expf(-x) }else{ k0 = 1e20 } return k0 } // Closure based polynomial expansion. Makes it easy to avoid loops for exansions func polynomialSum(_ coeffs:[Float], f: (Float) -> (Float)) -> Float { var sum = Float(0) var tp = Float(1) for coeff in coeffs { sum = coeff*tp + sum tp = f(tp) } return sum }
gpl-3.0
88f58130517fc080ac2181d4d2708a73
21.617647
97
0.505418
3.055629
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/Observers.swift
1
3564
// // Observers.swift // RealmModelGenerator // // Created by Brandon Erbschloe on 3/23/16. // Copyright © 2016 QuarkWorks. All rights reserved. // // This class is not thread safe and should only be used on the main thread / dispatch queue // import Foundation public protocol Observer: AnyObject { func onChange(observable:Observable) } public typealias ObserveBlock = (Observable) -> () public class ObserverToken: Observer { let observable:Observable let observeBlock:ObserveBlock internal init(observable:Observable, observeBlock:@escaping ObserveBlock) { self.observable = observable self.observeBlock = observeBlock self.observable.addObserver(observer: self) } public func stopListening() { observable.removeObserver(observer: self) } public func onChange(observable: Observable) { observeBlock(observable) } deinit { stopListening() } } public protocol Observable: AnyObject { func addObserver(observer: Observer) func removeObserver(observer: Observer) func removeAllObservers() func notifyObservers() } public extension Observable { public func addObserveBlockBlock(observeBlock:@escaping ObserveBlock) -> ObserverToken { return ObserverToken(observable: self, observeBlock: observeBlock) } } public class DeferredObservable: Observable, Observer { private let observable:Observable private var weakHashTable = NSHashTable<AnyObject>.weakObjects() public init(observable: Observable) { self.observable = observable self.observable.addObserver(observer: self) } public func addObserver(observer: Observer) -> Void { if !weakHashTable.contains(observer) { weakHashTable.add(observer) } } public func removeObserver(observer: Observer) -> Void { while weakHashTable.contains(observer) { weakHashTable.remove(observer) } } public func removeAllObservers() -> Void { self.weakHashTable.removeAllObjects() } public func removeFromParent() { self.observable.removeObserver(observer: self) } public func notifyObservers() -> Void { self.observable.notifyObservers() } public func onChange(observable: Observable) { self.weakHashTable.allObjects.forEach({ ($0 as! Observer).onChange(observable: self) }) } deinit { self.removeFromParent() } } public class BaseObservable: Observable { private var weakHashTable = NSHashTable<AnyObject>.weakObjects() private var willNotify = false public func addObserver(observer: Observer) { if !weakHashTable.contains(observer) { weakHashTable.add(observer) } } public func removeObserver(observer: Observer) { while weakHashTable.contains(observer) { weakHashTable.remove(observer) } } public func removeAllObservers() { weakHashTable.removeAllObjects() } public func notifyObservers() { if willNotify == true {return} willNotify = true OperationQueue.main.addOperation({[weak self] in guard let sSelf = self else {return} sSelf.weakHashTable.allObjects.forEach({ let observer = $0 as! Observer observer.onChange(observable: sSelf) }) sSelf.willNotify = false; }) } }
mit
c9e34b49587eb47a4c47b7b3c7460f99
25.589552
93
0.646646
4.976257
false
false
false
false
zwaldowski/ParksAndRecreation
Swift-2/Geometry.playground/Sources/CGPoint.swift
1
1578
import UIKit // MARK: Printable extension CGPoint: CustomStringConvertible { public var description: String { #if os(OSX) return NSStringFromPoint(self) #else return NSStringFromCGPoint(self) #endif } } // MARK: Vector arithmetic public prefix func -(p: CGPoint) -> CGPoint { return CGPoint(x: -p.x, y: -p.y) } public func +(lhs:CGPoint, rhs:CGPoint) -> CGPoint { return CGPoint(x:lhs.x + rhs.x, y:lhs.y + rhs.y) } public func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint { return lhs + -rhs } public func +=(inout lhs: CGPoint, rhs: CGPoint) { lhs = lhs + rhs } public func -=(inout lhs: CGPoint, rhs: CGPoint) { lhs = lhs - rhs } public func *(lhs: CGPoint, rhs: CGPoint) -> CGFloat { return (lhs.x * rhs.x) + (lhs.y * rhs.y) } public func /(lhs: CGPoint, rhs: CGPoint) -> CGFloat { return (lhs.x * rhs.x) - (lhs.y * rhs.y) } // MARK: Scalar arithmetic public func *(lhs: CGPoint, rhs: CGFloat) -> CGPoint { return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs) } public func /(lhs: CGPoint, rhs: CGFloat) -> CGPoint { return CGPoint(x: lhs.x / rhs, y: lhs.y / rhs) } public func *= (inout lhs:CGPoint, rhs:CGFloat) { lhs = lhs * rhs } public func /= (inout lhs:CGPoint, rhs:CGFloat) { lhs = lhs / rhs } // MARK: Trigonometry public func ...(a: CGPoint, b: CGPoint) -> CGFloat { let distance = a - b return sqrt(distance * distance) } public extension CGPoint { public func midpoint(other: CGPoint) -> CGPoint { return CGPoint(x: (x + other.x) / 2, y: (y + other.y) / 2) } }
mit
20cd18cd23bf9961b670a47b1b82d3ca
22.205882
68
0.61597
3.162325
false
false
false
false
xmartlabs/Bender
Sources/Core/PALFunctionConstant.swift
1
1795
// // FunctionConstant.swift // Bender // // Created by Mathias Claassen on 5/10/17. // // import Metal /// Base class for FunctionConstant. Should never be instantiated. Just a helper for us to store arrays of FunctionConstants of different types public class FunctionConstantBase: Equatable { /// Index of the function constant in the Metal shaders public var index: Int /// Type of the function constant in the Metal shaders public var type: MTLDataType public init(index: Int, type: MTLDataType) { self.index = index self.type = type } /// Returns the value of the FunctionConstant public func getValue() -> Any { fatalError("Not implemented") } /// Returns if two FunctionConstant's are equal. Helper to allow generic inheritance in Equatable. public func isEqual(to other: FunctionConstantBase) -> Bool { return type == other.type && index == other.index } public static func == (left: FunctionConstantBase, right: FunctionConstantBase) -> Bool { return left.isEqual(to: right) } } /// Generic class that holds information for Metals function constants. public class FunctionConstant<T: Any>: FunctionConstantBase where T: Equatable { /// Value to be passed to the compute kernels function constant public var value: T public init(index: Int, type: MTLDataType, value: T) { self.value = value super.init(index: index, type: type) } public override func getValue() -> Any { return value } public override func isEqual(to other: FunctionConstantBase) -> Bool { guard let otherValue = other.getValue() as? T else { return false } return type == other.type && index == other.index && value == otherValue } }
mit
a4a9c0bce4ebd9220a828adc868f06f1
28.916667
143
0.673538
4.432099
false
false
false
false
sxyx2008/FoodPin
FoodPin/RestaurantTableViewController.swift
2
10443
// // RestaurantTableViewController.swift // FoodPin // // Created by scott on 14-10-31. // Copyright (c) 2014年 scott. All rights reserved. // import UIKit import CoreData class RestaurantTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchResultsUpdating { var restaurants:[Restaurant] = [] var searchResults:[Restaurant] = [] var fetchResultsController:NSFetchedResultsController! var searchController:UISearchController! override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 80.0 self.tableView.rowHeight = UITableViewAutomaticDimension self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) /********************************UISearchBar**********************************************/ searchController = UISearchController(searchResultsController: nil) searchController.searchBar.sizeToFit() searchController.searchBar.tintColor = UIColor.whiteColor() // searchController.searchBar.barTintColor = UIColor(red: 231.0/255.0, green: 95.0/255.0, blue: 53.0/255.0, alpha: 0.3) // searchController.searchBar.prompt = "Quick Search" searchController.searchBar.placeholder = NSLocalizedString("Search your restaurant", comment: "Search your restaurant") tableView.tableHeaderView = searchController.searchBar definesPresentationContext = true self.searchController.searchResultsUpdater = self self.searchController.dimsBackgroundDuringPresentation = false /********************************从CoreData中获取数据**********************************************/ var fetchRequest = NSFetchRequest(entityName: "Restaurant") let sortDescription = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescription] if let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext { fetchResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchResultsController.delegate = self var e:NSError? var result = fetchResultsController.performFetch(&e) restaurants = fetchResultsController.fetchedObjects as [Restaurant] if result != true { println(e?.localizedDescription) } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.hidesBarsOnSwipe = true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) /********************************UIPageViewController**********************************************/ let defaults = NSUserDefaults.standardUserDefaults() var hasViewedWalkthrough = defaults.boolForKey("hasViewedWalkthrough") if hasViewedWalkthrough == false { if let pageViewController = storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as? PageViewController { self.presentViewController(pageViewController, animated: false, completion: nil) } } } // 检索过滤 func filterContentSearchText(searchText:String){ searchResults = restaurants.filter({ ( restaurant: Restaurant) -> Bool in let nameMatch = restaurant.name.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch) let locationMatch = restaurant.location.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch) return nameMatch != nil || locationMatch != nil }) } func updateSearchResultsForSearchController(searchController: UISearchController){ let searchText = searchController.searchBar.text filterContentSearchText(searchText) tableView.reloadData() } // MARK: - NSFetchedResultsControllerDelegate func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) default: tableView.reloadData() } restaurants = controller.fetchedObjects as [Restaurant] } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } // MARK: - tableView override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.active { return searchResults.count }else { return restaurants.count } } // 此大法是为了滑动单元格时显示UITableViewRowAction override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if searchController.active { return false }else { return true } } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: NSLocalizedString("Share", comment: "Share Action"), handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in let shareMenu = UIAlertController(title: nil, message: NSLocalizedString("Share using", comment: "For social sharing"), preferredStyle: .ActionSheet) let twitterAction = UIAlertAction(title: NSLocalizedString("Twitter", comment: "For sharing on Twitter"), style: UIAlertActionStyle.Default, handler: {(action:UIAlertAction!) -> Void in }) let facebookAction = UIAlertAction(title: NSLocalizedString("Facebook", comment: "For sharing on Facebook"), style: UIAlertActionStyle.Default, handler: {(action:UIAlertAction!) -> Void in }) let emailAction = UIAlertAction(title: NSLocalizedString("Email", comment: "For sharing on Email"), style: UIAlertActionStyle.Default, handler: {(action:UIAlertAction!) -> Void in }) let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel"), style: UIAlertActionStyle.Cancel, handler: {(action:UIAlertAction!) -> Void in }) shareMenu.addAction(twitterAction) shareMenu.addAction(facebookAction) shareMenu.addAction(emailAction) shareMenu.addAction(cancelAction) self.presentViewController(shareMenu, animated: true, completion: nil) } ) var deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete",handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in // Delete the row from the data source if let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext { let restaurantToDelete = self.fetchResultsController.objectAtIndexPath(indexPath) as Restaurant managedObjectContext.deleteObject(restaurantToDelete) var error:NSError? if managedObjectContext.save(&error) != true { println("Delete error: " + error!.localizedDescription) } } } ) deleteAction.backgroundColor = UIColor(red: 237.0/255.0, green: 75.0/255.0, blue: 27.0/255.0, alpha: 1.0) shareAction.backgroundColor = UIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) return [deleteAction,shareAction] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomTableViewCell let restaurant = (searchController.active) ? searchResults[indexPath.row] : restaurants[indexPath.row] cell.nameLabel.text = restaurant.name cell.typeLabel.text = restaurant.type cell.locationLabel.text = restaurant.location cell.favorIconImageView.hidden = !restaurant.isVisited.boolValue cell.thumbnailImageView.image = UIImage(data: restaurant.image) cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.width / 2 cell.thumbnailImageView.clipsToBounds = true return cell } // MARK: - nav override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showRestaurantDetail" { let destinationController = segue.destinationViewController as DetailViewController //destinationController.hidesBottomBarWhenPushed = true let indexPath = tableView.indexPathForSelectedRow()! let restaurant = (searchController.active) ? searchResults[indexPath.row] : restaurants[indexPath.row] destinationController.restaurant = restaurant } } // unwind segue @IBAction func unwindToHomeScreen(segue:UIStoryboardSegue) { } }
mit
087e5a02d0cb271ed2e257073cd12dbf
45.815315
211
0.653228
6.201074
false
false
false
false
basheersubei/swift-t
stc/tests/683-app-implicit-input.swift
4
887
import sys; /* * Regression test for bug where implicit dependency between apps is * not respected */ @suppress=unused_output app (file implicit) produce(string dir) { "./683-produce.sh" dir } app (void o) consume(string dir, file implicit) { "./683-consume.sh" dir } // Shouldn't execute until after signal set app (void o) consume2(string dir, void signal) { "./683-consume.sh" dir } main { string dir = "tmp-683"; file f<dir/"tmp.txt">; foreach i in [1:10] { // Consume should execute after produce is done consume(dir, f) => trace("DONE", i); } // Try to force produce to execute after consume wait(sleep(0.1)) { f = produce(dir); } string dir2 = "tmp-683-void"; void signal2; wait (sleep(0.1)) { wait (produce(dir2)) { // Set once file set signal2 = make_void(); } } consume2(dir2, signal2); }
apache-2.0
4b6bed50820a1e0b9b530ff10ed1f321
16.74
68
0.617813
3.167857
false
false
false
false
zhangxigithub/elevator
Elevator/Elevator.swift
1
9871
// // Elevator.swift // Elevator // // Created by zhangxi on 12/17/15. // Copyright © 2015 zhangxi.me. All rights reserved. // import UIKit enum ElevatorDirection { case UP case DOWN case AnyDirection } class Elevator: UIView,ElevatorControlPanelDelegate,ElevatorCarDelegate { var car:ElevatorCar! var floorCount:Int! var controlPanels = [ElevatorControlPanel]() //MARK: - 电梯控制器 func scan() { print("scan.........") //当电梯停止的时候 或者 门没关的时候不移动电梯 if car.state != ElevatorCarState.Stop { return } if car.gateState != .Close { return } //当待机状态时,选择最近的目的地 if car.direction == .AnyDirection { if let p = anyDirectionRequest(car.floor) { look(p) return } return } //1.先扫描同方向上的请求 if let p = sameDirectionRequest(car.floor, direction: car.direction) { look(p) return } //2.同方向上没有请求,改变方向 changeDirection() //3.扫描反方向的请求 if let p = opsiteDirectionRequest(car.floor, direction: car.direction) { look(p) return } print("待机..运行方向改为任意方向") car.direction = .AnyDirection } func look(panel:ElevatorControlPanel) { if panel.destination == true {//电梯内有人按楼层,优先到达该楼层 moveTo(panel.floor, direction:car.direction) }else {//电梯外有人请求电梯,次优先 moveTo(panel.floor, direction:car.direction) } } //MARK: - 查找某个方向上的请求 //同方向最近的的请求 func sameDirectionRequest(floor:Int,direction:ElevatorDirection) -> ElevatorControlPanel? { if direction == .UP { for i in floor...floorCount { let p = panel(floor: i) if p.needUp == true || p.destination == true { return p } } }else { for var i = floor ;i>=1 ; i-=1 { let p = panel(floor: i) if p.needDown == true || p.destination == true { return p } } } return nil } //相反方向最近的的请求 func opsiteDirectionRequest(floor:Int,direction:ElevatorDirection) -> ElevatorControlPanel? { if direction == .UP { for i in 1...floorCount { let p = panel(floor: i) if p.needUp == true || p.destination == true { return p } } }else { for var i = floorCount! ;i>=1 ; i-=1 { let p = panel(floor: i) if p.needDown == true || p.destination == true { return p } } } return nil } //任意方向最近的的请求 func anyDirectionRequest(floor:Int) -> ElevatorControlPanel? { var finish = false var downIndex = floor var upIndex = floor+1 while !finish { finish = true if upIndex <= floorCount { finish = false let panel = self.panel(floor: upIndex) if panel.destination == true || panel.needUp == true || panel.needDown == true { self.car.direction = .UP return panel } } upIndex++ if downIndex >= 1 { finish = false let panel = self.panel(floor: downIndex) if panel.destination == true || panel.needUp == true || panel.needDown == true { self.car.direction = .DOWN return panel } } downIndex-- } return nil } func moveTo(floor:Int,direction:ElevatorDirection) { print("moveTo \(floor)") let newFrame = carFrame(floor) let duration = NSTimeInterval(abs(floor - car.floor)) print("duration \(duration)") self.car.state = .MovingUp self.car.direction = direction UIView.animateWithDuration(duration, animations: { () -> Void in self.car.frame = newFrame }) { (finish:Bool) -> Void in self.car.arrive(floor) let panel = self.panel(floor: floor) //panel.needUp = false //panel.needDown = false if direction == .UP { panel.needUp = false } if direction == .DOWN { panel.needDown = false } if direction == .AnyDirection { panel.needUp = false panel.needDown = false } } } func changeDirection() { if car.direction == .UP { car.direction = .DOWN } else if car.direction == .DOWN { car.direction = .UP } } //MARK: - ElevatorControlPanelDelegate func up(panel: ElevatorControlPanel) { print("\(panel.floor)楼 need up") if car.direction == .AnyDirection { car.direction = .UP } scan() } func down(panel: ElevatorControlPanel) { print("\(panel.floor)楼 need down") if car.direction == .AnyDirection { car.direction = .DOWN } scan() } //MARK: - ElevatorCarDelegate func didSelectFloor(car: ElevatorCar, floor: Int) { print("need fo to \(floor)") panel(floor: floor).destination = true } func arrive(car: ElevatorCar, floor: Int) { let panel = self.panel(floor: floor) panel.destination = false if car.direction == .UP { panel.upButton.selected = false }else { panel.downButton.selected = false } } func willOpen(car:ElevatorCar) { print("willOpen") } func didOpen(car:ElevatorCar) { print("didOpen") } func willClose(car:ElevatorCar) { print("willClose") } func didClose(car:ElevatorCar) { print("didClose 当前楼层\(car.floor)") scan() } //MARK: - === convenience init(numberOfFloor:Int,frame: CGRect) { self.init(frame:frame) floorCount = numberOfFloor for i in 1 ... numberOfFloor { let floorFrame = self.floorFrame(i) let floorLabel = UILabel(frame: CGRectMake(floorFrame.origin.x,floorFrame.origin.y,80,22)) floorLabel.userInteractionEnabled = false floorLabel.text = String(i) floorLabel.textColor = UIColor.redColor() floorLabel.font = UIFont.systemFontOfSize(20) self.addSubview(floorLabel) let line = UIView(frame: CGRectMake(floorFrame.origin.x,floorFrame.origin.y+floorFrame.size.height-0.5,floorFrame.size.width,0.5)) line.backgroundColor = UIColor(white: 0.8, alpha: 1) self.addSubview(line) let panel = ElevatorControlPanel(floor: i, frame: controlPanelFrame(i)) panel.delegate = self if i == 1 { panel.isBottomFloor() } if i == numberOfFloor { panel.isTopFloor() } self.controlPanels.append(panel) self.addSubview(panel) } car = ElevatorCar(floor: 1,totalFloorCount:numberOfFloor, frame: carFrame(1)) car.delegate = self car.direction = .AnyDirection self.addSubview(car) } func panel(floor floor:Int)->ElevatorControlPanel { return controlPanels[floor-1] } let controlPanelWidth :CGFloat = 64 let controlPanelHeight:CGFloat = 120 func controlPanelFrame(floor:Int) -> CGRect { let floorHeight = (self.frame.size.height / CGFloat(floorCount)) let y = self.frame.size.height - CGFloat(floor)*floorHeight return CGRectMake(self.frame.size.width-controlPanelWidth, y,controlPanelWidth, floorHeight) } func floorFrame(floor:Int) -> CGRect { let floorHeight = (self.frame.size.height / CGFloat(floorCount)) let y = self.frame.size.height - CGFloat(floor)*floorHeight return CGRectMake(0, y,self.frame.size.width, floorHeight) } func carFrame(floor:Int) -> CGRect { let floorHeight = (self.frame.size.height / CGFloat(floorCount)) let y = self.frame.size.height - CGFloat(floor)*floorHeight return CGRectMake(20, y,self.frame.size.width-controlPanelWidth-20, floorHeight-0.5) } }
apache-2.0
c548cd5c466fa5b114efdba99d2acb0a
23.187342
142
0.478229
4.443721
false
false
false
false
mshhmzh/firefox-ios
Sync/EnvelopeJSON.swift
4
1797
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared public class EnvelopeJSON { private let json: JSON public init(_ jsonString: String) { self.json = JSON.parse(jsonString) } public init(_ json: JSON) { self.json = json } public func isValid() -> Bool { return !self.json.isError && self.json["id"].isString && //self["collection"].isString && self.json["payload"].isString } public var id: String { return self.json["id"].asString! } public var collection: String { return self.json["collection"].asString ?? "" } public var payload: String { return self.json["payload"].asString! } public var sortindex: Int { let s = self.json["sortindex"] return s.asInt ?? 0 } public var modified: Timestamp { if (self.json["modified"].isInt) { return Timestamp(self.json["modified"].asInt!) * 1000 } if (self.json["modified"].isDouble) { return Timestamp(1000 * (self.json["modified"].asDouble ?? 0.0)) } return 0 } public func toString() -> String { return self.json.toString() } public func withModified(now: Timestamp) -> EnvelopeJSON { if var d = self.json.asDictionary { d["modified"] = JSON(Double(now) / 1000) return EnvelopeJSON(JSON(d)) } return EnvelopeJSON(JSON.parse("!")) // Intentionally bad JSON. } } extension EnvelopeJSON { func asJSON() -> JSON { return self.json } }
mpl-2.0
adb486ac65fc2fb0bd6201df30b24e5c
23.616438
76
0.576516
4.21831
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/LiveBroadcast/Client/LiveBroadcast/Classes/Room/GiftContainerView.swift
1
3013
// // GiftContainerView.swift // LiveBroadcast // // Created by 朱双泉 on 2018/12/14. // Copyright © 2018 Castie!. All rights reserved. // import UIKit private let kChannelCount = 2 private let kChannelViewH : CGFloat = 40 private let kChannelMargin : CGFloat = 10 class GiftContainerView: UIView { fileprivate lazy var channelViews = [GiftChannelView]() fileprivate lazy var cacheGiftChannelModels = [GiftChannelModel]() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension GiftContainerView { fileprivate func setupUI() { let w : CGFloat = frame.width let h : CGFloat = kChannelViewH let x : CGFloat = 0 for i in 0..<kChannelCount { let y : CGFloat = (h + kChannelMargin) * CGFloat(i) let channelView = GiftChannelView.loadFromNib() channelView.frame = CGRect(x: x, y: y, width: w, height: h) channelView.alpha = 0.0 addSubview(channelView) channelViews.append(channelView) channelView.completionCallback = { channelView in guard self.cacheGiftChannelModels.count != 0 else { return } let firstGiftChannelModel = self.cacheGiftChannelModels.first! self.cacheGiftChannelModels.removeFirst() channelView.giftChannelModel = firstGiftChannelModel for i in (0..<self.cacheGiftChannelModels.count).reversed() { let giftChannelModel = self.cacheGiftChannelModels[i] if giftChannelModel.isEqual(firstGiftChannelModel) { channelView.addOnceToCache() self.cacheGiftChannelModels.remove(at: i) } } } } } } extension GiftContainerView { func showGiftChannelView(_ giftChannelModel: GiftChannelModel) { if let channelView = checkUsingChannelView(giftChannelModel) { channelView.addOnceToCache() return } if let channelView = checkIdleChanelView() { channelView.giftChannelModel = giftChannelModel return } cacheGiftChannelModels.append(giftChannelModel) } private func checkUsingChannelView(_ giftChannelModel: GiftChannelModel) -> GiftChannelView? { for channelView in channelViews { if giftChannelModel.isEqual(channelView.giftChannelModel) && channelView.state != .endAnimating { return channelView } } return nil } private func checkIdleChanelView() -> GiftChannelView? { for channelView in channelViews { if channelView.state == .idle { return channelView } } return nil } }
mit
21dd0e8b4f97b8a057c128da3895b13d
30.978723
109
0.5998
4.952224
false
false
false
false
ioscreator/ioscreator
SwiftUIEnvironmentObjectTutorial/SwiftUIEnvironmentObjectTutorial/SceneDelegate.swift
1
2858
// // SceneDelegate.swift // SwiftUIEnvironmentObjectTutorial // // Created by Arthur Knopper on 11/09/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? var settings = GameSettings() func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView.environmentObject(settings)) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
9c40775eb58cd21dab76a426e36f7477
42.287879
147
0.707035
5.390566
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/SwiftyDemo/CIImage+Extension.swift
1
2057
// // CIImage+Extension.swift // SwiftyDemo // // Created by newunion on 2020/3/2. // Copyright © 2020 firestonetmt. All rights reserved. // import UIKit extension CIImage { func createNonInterpolated(withSize size: CGFloat) -> UIImage? { let extent = self.extent let scale = min(size / extent.width, size / extent.height) // 1.创建bitmap; let width = size_t(extent.width * scale) let height = size_t(extent.height * scale) let cs = CGColorSpaceCreateDeviceGray() let context1 = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue).rawValue) let ciContext = CIContext() guard let context = context1 else { return nil } guard let bitmapImage = ciContext.createCGImage(self, from: extent) else { return nil } context.interpolationQuality = CGInterpolationQuality.none context.scaleBy(x: scale, y: scale) context.draw(bitmapImage, in: extent) // 2.保存bitmap到图片 guard let scaledImage = context.makeImage() else { return nil } // free(context) // free(bitmapImage) return UIImage(cgImage: scaledImage) } } class MGCreatTiool { func creatQRCode() -> UIImage?{ // 1.创建滤镜对象 let filter = CIFilter(name: "CIQRCodeGenerator") // 2.恢复默认设置 filter?.setDefaults() //3.链接字符串 let str = "https://www.jianshu.com/u/4c669da2ffa3" // 4.将链接字符串转data格式 let strData = str.data(using: .utf8) filter?.setValue(strData, forKeyPath: "inputMessage") // 5.生成二维码 let outputImage = filter?.outputImage return outputImage?.createNonInterpolated(withSize: 80); } }
mit
a4183a39f128a0fb5b320429fcd55a12
25.052632
198
0.585859
4.4098
false
false
false
false
xingerdayu/dayu
dayu/FileUtil.swift
1
1261
// // FileUtil.swift // Community // // Created by Xinger on 15/3/28. // Copyright (c) 2015年 Xinger. All rights reserved. // import Foundation class FileUtil { class func getDefaultPath() -> String { var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) return paths[0] as String } class func save(data:NSData, fileName:String) { let path = getDefaultPath() let savePath = NSURL(string: path)?.URLByAppendingPathComponent(fileName)//.stringByAppendingPathComponent(fileName) print("savePath = \(savePath)") data.writeToURL(savePath!, atomically: true) //data.writeToFile(savePath, atomically: true) } class func getUserImageFromLocal(user:User) -> UIImage? { //let path = getDefaultPath().stringByAppendingPathComponent(user.getLocalImageName()) let path = NSURL(string: getDefaultPath())?.URLByAppendingPathComponent(user.getLocalImageName()).absoluteString let fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(path!) { return nil } return UIImage(contentsOfFile: path!) } }
bsd-3-clause
cfc6e7e760cb92cead0bfb7ed901e5a2
33.054054
141
0.680699
5.117886
false
false
false
false
MobileTribe/BBL-RX
Swift/RxDemo/Classes/DemoViewController.swift
1
3038
// // DemoViewController.swift // RxDemo // // Created by Aurélien DELRUE on 22/12/2016. // Copyright © 2016 Aurélien DELRUE. All rights reserved. // import UIKit import RxSwift class DemoViewController: UIViewController { /// UI @IBOutlet var resultTextView: UITextView! // MARK: User actions @IBAction func firstDemoAction() { // UI resultTextView.text = "Affichage simple des valeurs de l'observable :\n\n" // Rx _ = Observable.of("one", "two", "three", "four", "five") .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .observeOn(MainScheduler.instance) .subscribe( onNext: { (value) in self.printUI(content: "onNext : \(value)") }, onError: { (error) in self.printUI(content: "onError") }, onCompleted: { self.printUI(content: "onComplete") }) } @IBAction func secondDemoAction() { // UI resultTextView.text = "Edition et affichage des valeurs de l'observable :\n\n" // Rx _ = Observable.of("one", "two", "three", "four", "five") .map { "\($0) bananas" } .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .observeOn(MainScheduler.instance) .subscribe( onNext: { (value) in self.printUI(content: "onNext : \(value)") }, onError: { (error) in self.printUI(content: "onError") }, onCompleted: { self.printUI(content: "onComplete") }) } @IBAction func thirdDemoAction() { // UI resultTextView.text = "Filtre les valeurs de 3+ caractères puis édition des valeurs avec un interval d'une seconde :\n\n" // Rx let defaultObservable = Observable.of("one", "two", "three", "four", "five") let intervals = Observable<NSInteger>.interval(1.0, scheduler: MainScheduler.instance) _ = Observable .zip(defaultObservable, intervals) { return $0.0 } .filter { $0.characters.count > 3 } .map { "\($0) bananas" } .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .observeOn(MainScheduler.instance) .subscribe( onNext: { (value) in self.printUI(content: value) }, onError: { (error) in self.printUI(content: "onError") }, onCompleted: { self.printUI(content: "End") }) } // MARK: UI func printUI(content: String) { resultTextView.text = resultTextView.text + "[\(Date().description)] \(content)\n" } }
mit
5d117de00a136cd89a466561272272be
28.163462
129
0.503132
4.574661
false
false
false
false
plivesey/SwiftGen
SwiftGen.playground/Pages/Storyboards-Demo.xcplaygroundpage/Contents.swift
1
4550
//: #### Other pages //: //: * [Demo for `swiftgen strings`](Strings-Demo) //: * [Demo for `swiftgen images`](Images-Demo) //: * Demo for `swiftgen storyboards` //: * [Demo for `swiftgen colors`](Colors-Demo) //: * [Demo for `swiftgen fonts`](Fonts-Demo) class CreateAccViewController: UIViewController {} //: #### Example of code generated by swiftgen-storyboard // Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen import Foundation import UIKit protocol StoryboardSceneType { static var storyboardName: String { get } } extension StoryboardSceneType { static func storyboard() -> UIStoryboard { return UIStoryboard(name: self.storyboardName, bundle: nil) } static func initialViewController() -> UIViewController { guard let vc = storyboard().instantiateInitialViewController() else { fatalError("Failed to instantiate initialViewController for \(self.storyboardName)") } return vc } } extension StoryboardSceneType where Self: RawRepresentable, Self.RawValue == String { func viewController() -> UIViewController { return Self.storyboard().instantiateViewController(withIdentifier: self.rawValue) } static func viewController(identifier: Self) -> UIViewController { return identifier.viewController() } } protocol StoryboardSegueType: RawRepresentable { } extension UIViewController { func perform<S: StoryboardSegueType>(segue: S, sender: Any? = nil) where S.RawValue == String { performSegue(withIdentifier: segue.rawValue, sender: sender) } } struct StoryboardScene { enum Wizard: String, StoryboardSceneType { static let storyboardName = "Wizard" static func initialViewController() -> CreateAccViewController { guard let vc = storyboard().instantiateInitialViewController() as? CreateAccViewController else { fatalError("Failed to instantiate initialViewController for \(self.storyboardName)") } return vc } case acceptCGUScene = "Accept-CGU" static func instantiateAcceptCGU() -> UIViewController { return StoryboardScene.Wizard.acceptCGUScene.viewController() } case createAccountScene = "CreateAccount" static func instantiateCreateAccount() -> CreateAccViewController { guard let vc = StoryboardScene.Wizard.createAccountScene.viewController() as? CreateAccViewController else { fatalError("ViewController 'CreateAccount' is not of the expected class CreateAccViewController.") } return vc } case preferencesScene = "Preferences" static func instantiatePreferences() -> UITableViewController { guard let vc = StoryboardScene.Wizard.preferencesScene.viewController() as? UITableViewController else { fatalError("ViewController 'Preferences' is not of the expected class UITableViewController.") } return vc } case validatePasswordScene = "Validate_Password" static func instantiateValidatePassword() -> UIViewController { return StoryboardScene.Wizard.validatePasswordScene.viewController() } } } struct StoryboardSegue { enum Wizard: String, StoryboardSegueType { case showPassword = "ShowPassword" } } //: #### Usage Example let createAccountVC = StoryboardScene.Wizard.createAccountScene.viewController() createAccountVC.title let validateVC = StoryboardScene.Wizard.validatePasswordScene.viewController() validateVC.title let segue = StoryboardSegue.Wizard.showPassword createAccountVC.perform(segue: segue) switch segue { case .showPassword: print("Working! 🎉") default: print("Not working! 😱") } /******************************************************************************* This is a «real world» example of how you can benefit from the generated enum; you can easily switch or directly compare the passed in `segue` with the corresponding segues for a specific storyboard. *******************************************************************************/ //override func prepareForSegue(_ segue: UIStoryboardSegue, sender sender: AnyObject?) { // switch UIStoryboard.Segue.Message(rawValue: segue.identifier)! { // case .Custom: // // Prepare for your custom segue transition // case .NonCustom: // // Pass in information to the destination View Controller // } //}
mit
890d2c2d2d6cead90249130948657062
34.193798
118
0.671145
5.322392
false
false
false
false
huangboju/Moots
Examples/URLSession/URLSession/SandBox.swift
1
13114
// // SandBox.swift // URLSession // // Created by 伯驹 黄 on 2016/12/29. // Copyright © 2016年 伯驹 黄. All rights reserved. // import UIKit // QunarFlight团队博客~iOS 中数据持久化的几种方式 // http://blog.flight.dev.qunar.com/2016/11/10/ios-data-persistence-learn/#more // JSONSerialization // http://www.hangge.com/blog/cache/detail_647.html // http://swiftcafe.io/2015/07/18/swift-json class SandBox: UITableViewController { enum Path: String { case home = "Home Directory" case documents = "Documents" case library = "Library" case caches = "Caches" case tmp = "Tmp" } let titles: [[String]] = [ [ "Home Directory", "Documents", "Library", "Caches", "Tmp" ], [ "createDirectory", "createFile", "writeFile", "readFileContent", "isExist", "fileSize", "deleteFile", "moveFile", "renameFile", "copyFile", "findFile" ], [ "addContents", "findContents" ], [ "writeToJSON" ] ] override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } func excute(_ rawValue: String) { var path: String! switch Path(rawValue: rawValue)! { case .home: path = NSHomeDirectory() case .documents: path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first case .library: path = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first case .caches: path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first case .tmp: path = NSTemporaryDirectory() } print("📂\(String(describing: path))\n\n") } // 创建文件夹 func createDirectory() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let fileManager = FileManager.default let iOSDirectory = documentsPath + "/iOS" print("📂\(iOSDirectory)\n\n") do { try fileManager.createDirectory(at: URL(fileURLWithPath: iOSDirectory), withIntermediateDirectories: true, attributes: nil) } catch let error { print("❌\(error)") } } func createFile() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let fileManager = FileManager.default let iOSDirectory = documentsPath + "/iOS.txt" print("📃\(iOSDirectory)\n\n") let contents = "新建文件".data(using: .utf8) let isSuccess = fileManager.createFile(atPath: iOSDirectory, contents: contents, attributes: nil) print(isSuccess ? "✅" : "❌") } func writeFile() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let iOSPath = documentsPath + "/iOS.json" guard let dataFilePath = Bundle.main.path(forResource: "test", ofType: "json") else { return } let data = try? Data(contentsOf: URL(fileURLWithPath: dataFilePath)) do { try data?.write(to: URL(fileURLWithPath: iOSPath)) // try content.write(toFile: iOSPath, atomically: true, encoding: .utf8) } catch let error { print("❌\(error)") } } func readFileContent() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let iOSPath = documentsPath + "/iOS.txt" do { let contents = try String(contentsOf: URL(fileURLWithPath: iOSPath), encoding: .utf8) print(contents) } catch let error { print("❌\(error)") } } func isExist() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let iOSPath = documentsPath + "/iOS.txt" let fileManager = FileManager.default if fileManager.fileExists(atPath: iOSPath) { print("📃存在") } else { print("📃不存在") } } func fileSize() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let iOSPath = documentsPath + "/iOS.txt" let fileManager = FileManager.default if fileManager.fileExists(atPath: iOSPath) { do { let att = try fileManager.attributesOfItem(atPath: iOSPath) let size = att[.size] let creationDate = att[.creationDate] let ownerAccountName = att[.ownerAccountName] let modificationDate = att[.modificationDate] print("size=\(String(describing: size))", "creationDate=\(String(describing: creationDate))", "ownerAccountName=\(String(describing: ownerAccountName))", "modificationDate=\(String(describing: modificationDate))") } catch let error { print("❌\(error)") } } else { print("📃不存在") } } // func folderSize() { // let fileManager = FileManager.default // let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! // // let isExist = fileManager.fileExists(atPath: documentsPath) // // if isExist { // // let childFileEnumerator = fileManager.subpaths(atPath: documentsPath) // let folderSize = 0 // let fileName = @"" // while ((fileName = [childFileEnumerator nextObject]) != nil){ // NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName]; // folderSize += [self fileSizeAtPath:fileAbsolutePath]; // } // return folderSize / (1024.0 * 1024.0) // } else { // NSLog(@"file is not exist"); // return 0; // } // } func deleteFile() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let fileManager = FileManager.default let iOSPath = documentsPath + "/iOS.txt" do { try fileManager.removeItem(atPath: iOSPath) print("✅删除") } catch let error { print("📃删除错误\(error)") } } func moveFile() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let fileManager = FileManager.default let filePath = documentsPath + "/iOS.txt" let moveToPath = documentsPath + "/iOS/iOS1.txt" do { try fileManager.moveItem(atPath: filePath, toPath: moveToPath) print("✅移动") } catch let error { print("❌\(error)") } } func renameFile() { // 通过移动该文件对文件重命名 let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let fileManager = FileManager.default let filePath = documentsPath + "/iOS.txt" let moveToPath = documentsPath + "/rename.txt" do { try fileManager.moveItem(atPath: filePath, toPath: moveToPath) print("✅重命名") } catch let error { print("❌\(error)") } } func copyFile() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let fileManager = FileManager.default let filePath = documentsPath + "/iOS.txt" let moveToPath = documentsPath + "/copy.txt" do { try fileManager.copyItem(atPath: filePath, toPath: moveToPath) print("✅") } catch let error { print("❌", error) } } func findFile() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let fileManager = FileManager.default // 当前文件夹下的所有文件 if let paths = fileManager.subpaths(atPath: documentsPath) { for path in paths where path.first != "." { // 剔除隐藏文件 print("\(documentsPath)/\(path)\n") } } // 查找当前文件夹 do { let paths = try fileManager.contentsOfDirectory(atPath: documentsPath) paths.forEach { print($0) } } catch let error { print(error) } } // 向文件追加数据 func addContents() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let sourcePath = documentsPath + "/iOS.json" do { let fileHandle = try FileHandle(forUpdating: URL(fileURLWithPath: sourcePath)) fileHandle.seekToEndOfFile() // 将节点跳到文件的末尾 let data = "追加的数据".data(using: .utf8) fileHandle.write(data!) // 追加写入数据 fileHandle.closeFile() print("✅") } catch let error { print("❌\(error)") } } func findContents() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let sourcePath = documentsPath + "/copy.txt" do { let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: sourcePath)) let length = fileHandle.availableData.count fileHandle.seek(toFileOffset: UInt64(length / 2)) // 偏移量文件的一半 let data = fileHandle.readDataToEndOfFile() let contents = String(data: data, encoding: String.Encoding.utf8) fileHandle.closeFile() print("✅\(String(describing: contents))") } catch let error { print("❌\(error)") } } func writeToJSON() { //Swift对象 let user:[String: Any] = [ "uname": "张三", "tel": ["mobile": "138", "home": "010"] ] //首先判断能不能转换 if !JSONSerialization.isValidJSONObject(user) { print("is not a valid json object") return } //利用自带的json库转换成Data //如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读 do { let data = try JSONSerialization.data(withJSONObject: user, options: .prettyPrinted) let documentsPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! let iOSPath = documentsPath + "/iOS.json" try data.write(to: URL(fileURLWithPath: iOSPath)) print("✅✅✅", iOSPath) } catch let error { print("❌\(error)") } // //把Data对象转换回JSON对象 // let json = try? JSONSerialization.jsonObject(with: data!, // options:.allowFragments) as! [String: Any] // print("Json Object:", json) // //验证JSON对象可用性 // let uname = json?["uname"] // let mobile = (json?["tel"] as! [String: Any])["mobile"] // print("get Json Object:","uname: \(uname), mobile: \(mobile)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in tableView: UITableView) -> Int { return titles.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titles[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.textLabel?.text = titles[indexPath.section][indexPath.row] } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if indexPath.section == 0 { excute(titles[indexPath.section][indexPath.row]) } else { perform(Selector(titles[indexPath.section][indexPath.row])) } } }
mit
d17427c9aa00a7c24aa7bd200c6d0be8
32.509235
229
0.584252
4.937792
false
false
false
false
jxxcarlson/exploring_swift
oneCircleB.playground/Sources/Point.swift
4
403
import Foundation public class Point { public var x = 0.0 public var y = 0.0 public init() { } public init(x: Double, y:Double) { self.x = x; self.y = y } public func distance_to(p: Point) -> Double { let dx = self.x - p.x let dy = self.y - p.y let d_squared = dx*dx + dy*dy return sqrt(d_squared) } }
mit
02d2d6ce028b0001a693002678ccf8c9
17.363636
63
0.483871
3.415254
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/Omar-Villegas/Ejercicios-Libro/Ejercicio76-5.swift
1
927
/* Created by Omar Villegas on 09/02/17. Copyright © 2017 Omar Villegas. All rights reserved. Materia: Patrones de Diseño Alumno: Villegas Castillo Omar No. de control: 13211106 Ejercicios del PDF "Problemas para Resolver por Computadora 1993" PROBLEMA 76 CAPÍTULO 5 Un experimento consiste en lanzar una moneda hasta que salga águila. Hacer un programa para efectuar 2000 veces el experimento y contar el número de lanzamientos requeridos en cada caso . Imprimir la distribución. */ import Foundation var moneda = 0 var veces = 0 //CICLO FOR PARA EFECTUAR 2000 VECES EL EXPERIMENTO for i in 1...2000 { //REPETIR HASTA QUE SALGA AGUILA (1) repeat { moneda = Int(arc4random() % 2 + 1) veces = veces+1 //CONTADOR DE LANZAMIENTOS } while moneda == 1 } //IMPRIMIR LAS VECES print("\(veces) lanzamientos requeridos en obtener águila 2000 veces")
gpl-3.0
e08cb371c1f0317aed388e091a1905a5
22.589744
213
0.705435
2.996743
false
false
false
false
aiaio/DesignStudioExpress
DesignStudioExpress/Views/SettingsViewController.swift
1
4172
// // SettingsViewController.swift // DesignStudioExpress // // Created by Tim Broder on 12/10/15. // Copyright © 2015 Alexander Interactive. All rights reserved. // import Foundation import MGSwipeTableCell class SettingsViewController: UIViewControllerBase, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate { @IBOutlet weak var tableView: UITableView! let vm = SettingsViewModel() override func viewDidLoad() { super.viewDidLoad() self.customizeStyle() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return vm.getTotalRows() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = self.createCell("settingsHeader", indexPath: indexPath, UITableViewCell.self) return cell } let cell = self.createCell("setttingCell", indexPath: indexPath, UITableViewCellSettings.self) return cell } // customize row height func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // default row height for DS cells var rowHeight = 60 // row height for photo // dynamically adjust based on the device height // should refactor to use autoconstraints if indexPath.row == 0 { let screenSize = UIScreen.mainScreen().bounds.height if screenSize <= 480 { // 4s rowHeight = 245 } else if screenSize <= 568 { // 5 rowHeight = 260 } else if screenSize <= 667 { // 6 rowHeight = 360 } else { // 6++ rowHeight = 360 } } return CGFloat(rowHeight) } @objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let action = vm.getAction(indexPath) { action(self) } } // MARK: StyledNavigationBar override func customizeNavBarStyle() { super.customizeNavBarStyle() DesignStudioElementStyles.transparentNavigationBar(self.navigationController!.navigationBar) } // MARK: - Custom // creates table view cell of a specified type private func createCell<T: UITableViewCell>(reuseIdentifier: String, indexPath: NSIndexPath, _: T.Type) -> T { var cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! T! if cell == nil { cell = T(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier) } // first cell contains static content // skip setting the data if indexPath.row == 0 { return cell } guard let settingCell = cell as? UITableViewCellSettings else { return cell } settingCell.title?.text = vm.getTitle(indexPath) guard let imagePath = vm.getImageName(indexPath) else { return cell } settingCell.icon.image = UIImage(named: imagePath) return cell } private func customizeStyle() { // this in comb. with UIEdgeInsetsZero on layoutMargins for a cell // will make the cell separator show from edge to edge self.tableView.layoutMargins = UIEdgeInsetsZero } // MARK: - MFMailComposeViewControllerDelegate func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { self.dismissViewControllerAnimated(true, completion: {}) } }
mit
ca1bbe691dc3bb89ca7613edb58a4446
30.360902
139
0.619755
5.690314
false
false
false
false
alexandreblin/ios-car-dashboard
CarDash/RadioViewController.swift
1
4619
// // RadioViewController.swift // CarDash // // Created by Alexandre Blin on 12/06/2016. // Copyright © 2016 Alexandre Blin. All rights reserved. // import UIKit import MarqueeLabel /// View controller displaying the current radio station. class RadioViewController: CarObservingViewController { @IBOutlet private weak var radioDescriptionVerticalSpaceConstraint: NSLayoutConstraint! @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var descriptionLabel: MarqueeLabel! @IBOutlet private weak var frequencyLabel: UILabel! @IBOutlet private weak var radioArtView: UIImageView! private var radioArtFound = false private let radioAliases = [ "virgin": "europe2", "mfmradio": "mfm", "cannesr": "razur", "rcfnice": "rcf" ] override func viewDidLoad() { super.viewDidLoad() // Add perspective to radioArtView var rotationAndPerspectiveTransform = CATransform3DIdentity rotationAndPerspectiveTransform.m34 = 1.0 / -500 rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 25.0 * CGFloat(M_PI) / 180.0, 0.0, 1.0, 0.0) radioArtView.layer.transform = rotationAndPerspectiveTransform radioArtView.layer.allowsEdgeAntialiasing = true radioArtView.layer.minificationFilter = kCAFilterTrilinear } override func carInfoPropertyChanged(_ carInfo: CarInfo, property: CarInfo.Property) { if property == .radioName || property == .radioFrequency || property == .radioBandName { if property == .radioFrequency { // When changing stations, remove current radio logo radioArtFound = false UIView.transition(with: radioArtView, duration: 0.2, options: .transitionCrossDissolve, animations: { self.radioArtView.image = UIImage(named: "radioart_placeholder") }, completion: nil) } updateRadioLabels() } else if property == .radioDescription { setRadioDescription(carInfo.radioDescription) } } /// Sets and animate the radio description label. /// /// - Parameter description: The description string to set private func setRadioDescription(_ description: String?) { if let description = description { descriptionLabel.text = description UIView.animate(withDuration: 0.5, animations: { self.descriptionLabel.alpha = 1 self.radioDescriptionVerticalSpaceConstraint.constant = 32 self.view.layoutIfNeeded() }) } else { UIView.animate(withDuration: 0.5, animations: { self.descriptionLabel.alpha = 0 self.radioDescriptionVerticalSpaceConstraint.constant = -78 self.view.layoutIfNeeded() }) } } private func updateRadioLabels() { if let radioName = carInfo.radioName, let frequency = carInfo.radioFrequency, let bandName = carInfo.radioBandName { nameLabel.text = radioName frequencyLabel.text = "\(frequency) MHz – FM \(bandName)" let charactersToRemove = CharacterSet.alphanumerics.inverted let strippedRadioName = carInfo.radioName?.lowercased().components(separatedBy: charactersToRemove).joined(separator: "") if !radioArtFound { // Try to find the station logo if var strippedRadioName = strippedRadioName { if let mapping = radioAliases[strippedRadioName] { strippedRadioName = mapping } if let radioArt = UIImage(named: "radioart_\(strippedRadioName)") { radioArtFound = true UIView.transition(with: radioArtView, duration: 0.2, options: .transitionCrossDissolve, animations: { self.radioArtView.image = radioArt }, completion: nil) } } } } else { // No station name found, display the frequency instead of the name nameLabel.text = (carInfo.radioFrequency ?? "0.0") + " MHz" frequencyLabel.text = "FM " + (carInfo.radioBandName ?? "") // Force layout now because when changing frequency, we animate the hiding of the radio description // but we don't want to animate the frequency label (it looks ugly) view.layoutIfNeeded() } } }
mit
da1be02571728f424aa566783adc659c
39.849558
139
0.623267
5.072527
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Test/UserProfileManagerTests.swift
3
4635
// // UserProfileManagerTests.swift // edX // // Created by Akiva Leffert on 10/29/15. // Copyright © 2015 edX. All rights reserved. // @testable import edX import Foundation class UserProfileManagerTests : XCTestCase { func loggedInContext() -> (OEXMockCredentialStorage, OEXSession, UserProfileManager, MockNetworkManager) { let credentialStorage = OEXMockCredentialStorage.freshStorage() let session = OEXSession(credentialStore: credentialStorage) session.loadTokenFromStore() let networkManager = MockNetworkManager(authorizationHeaderProvider: nil, baseURL: NSURL(string:"http://example.com")!) networkManager.interceptWhenMatching({ $0.method == .GET}, successResponse: { return (nil, UserProfile(username: credentialStorage.storedUserDetails!.username!)) }) let profileManager = UserProfileManager(networkManager: networkManager, session: session) return (credentialStorage, session, profileManager, networkManager) } func testCurrentUserSwapsFeed() { let (credentialStorage, session, profileManager, _) = loggedInContext() let feed = profileManager.feedForCurrentUser() var expectation = expectationWithDescription("Profile populated") feed.refresh() // Initial log in should include user var removable = feed.output.listen(self) { if let value = $0.value { XCTAssertEqual(value.username!, credentialStorage.storedUserDetails!.username!) expectation.fulfill() } } waitForExpectations() removable.remove() session.closeAndClearSession() credentialStorage.storedAccessToken = OEXAccessToken.fakeToken() credentialStorage.storedUserDetails = OEXUserDetails.freshUser() // Log out should remove user expectation = expectationWithDescription("Profile removed") feed.output.listenOnce(self) { XCTAssertNil($0.value) expectation.fulfill() } session.loadTokenFromStore() // Log in back in should update user expectation = expectationWithDescription("Profile populated again") feed.refresh() removable = feed.output.listen(self) { if let value = $0.value { XCTAssertEqual(value.username!, credentialStorage.storedUserDetails!.username!) expectation.fulfill() } } waitForExpectations() removable.remove() } func testUpdate() { let (_, _, profileManager, networkManager) = loggedInContext() let profileFeed = profileManager.feedForCurrentUser() var profile : UserProfile! var expectation = expectationWithDescription("Profile populated") profileFeed.refresh() profileFeed.output.listenOnce(self) { profile = $0.value expectation.fulfill() } waitForExpectations() let newBio = "Test Passed" profile.updateDictionary = ["bio" : newBio] networkManager.interceptWhenMatching({ $0.method == .PATCH}) { () -> (NSData?, UserProfile) in let newProfile = profile newProfile.bio = newBio return (nil, newProfile) } expectation = expectationWithDescription("Profile updated") profileManager.updateCurrentUserProfile(profile) { result -> Void in XCTAssertEqual(result.value!.bio, newBio) expectation.fulfill() } waitForExpectations() // We updated the profile so the current user feed should also fire expectation = expectationWithDescription("Profile feed update") profileFeed.output.listenOnce(self) { XCTAssertEqual($0.value!.bio!, newBio) expectation.fulfill() } waitForExpectations() } func testClearsOnLogOut() { let (_, session, profileManager, _) = loggedInContext() var feed = profileManager.feedForUser("some_test_person") feed.refresh() let expectation = expectationWithDescription("Profile loaded") feed.output.listenOnce(self) {_ in expectation.fulfill() } waitForExpectations() XCTAssertNotNil(feed.output.value!.username) session.closeAndClearSession() feed = profileManager.feedForUser("some_test_person") XCTAssertNil(feed.output.value) } }
apache-2.0
074dc199bd1204ae2ca856ac1eb913e2
35.496063
127
0.627104
5.665037
false
true
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/BottomCenterTop.Individual.swift
1
1252
// // BottomCenterTop.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct BottomCenterTop { let bottomCenter: LayoutElement.Point let top: LayoutElement.Vertical } } // MARK: - Make Frame extension IndividualProperty.BottomCenterTop { private func makeFrame(bottomCenter: Point, top: Float, width: Float) -> Rect { let x = bottomCenter.x - width.half let y = top let height = bottomCenter.y - top let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Width extension IndividualProperty.BottomCenterTop: LayoutPropertyCanStoreWidthToEvaluateFrameType { public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let bottomCenter = self.bottomCenter.evaluated(from: parameters) let top = self.top.evaluated(from: parameters) let height = bottomCenter.y - top let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height)) return self.makeFrame(bottomCenter: bottomCenter, top: top, width: width) } }
apache-2.0
835c1a8ead062ac95a9896d62cf6fc8c
21.907407
115
0.724333
3.782875
false
false
false
false
catloafsoft/AudioKit
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Variable Delay.xcplaygroundpage/Contents.swift
1
1233
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Variable Delay //: ### When you smooth vary effect parameters, you get completely new kinds of effects. import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("drumloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true var delay = AKVariableDelay(player) //: Set the parameters of the delay here delay.time = 0.1 // seconds AudioKit.output = delay AudioKit.start() player.play() var t = 0.0 let timeStep = 0.02 AKPlaygroundLoop(every: timeStep) { //: Vary the delay time between 0.0 and 0. 4 in a sinusoid at 0.5 hz let delayModulationHz = 0.5 let delayModulation = (1.0 - cos(2 * 3.14 * delayModulationHz * t)) * 0.02 delay.time = delayModulation //: Vary the feedback between zero and 1 in a sinusoid at 0.5Hz let feedbackModulationHz = 0.5 let feedbackModulation = (1.0 - sin(2 * 3.14 * feedbackModulationHz * t)) * 0.5 delay.feedback = feedbackModulation t = t + timeStep } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
a2a7f24c2df19d1f13b7cd9334e97a8c
28.357143
90
0.687753
3.512821
false
false
false
false
PureSwift/Silica
Sources/Silica/CGAffineTransform.swift
1
2759
// // AffineTransform.swift // Silica // // Created by Alsey Coleman Miller on 5/8/16. // Copyright © 2016 PureSwift. All rights reserved. // import Cairo import CCairo import Foundation #if os(macOS) import struct CoreGraphics.CGAffineTransform public typealias CGAffineTransform = CoreGraphics.CGAffineTransform #else /// Affine Transform public struct CGAffineTransform { // MARK: - Properties public var a, b, c, d, tx, ty: CGFloat // MARK: - Initialization public init(a: CGFloat, b: CGFloat, c: CGFloat, d: CGFloat, tx: CGFloat, ty: CGFloat) { self.a = a self.b = b self.c = c self.d = d self.tx = tx self.ty = ty } public static let identity = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) } #endif // MARK: - Geometry Math // Immutable math public protocol CGAffineTransformMath { func applying(_ transform: CGAffineTransform) -> Self } // Mutable versions public extension CGAffineTransformMath { @inline(__always) mutating func apply(_ transform: CGAffineTransform) { self = self.applying(transform) } } // Implementations extension CGPoint: CGAffineTransformMath { @inline(__always) public func applying(_ t: CGAffineTransform) -> CGPoint { return CGPoint(x: t.a * x + t.c * y + t.tx, y: t.b * x + t.d * y + t.ty) } } extension CGSize: CGAffineTransformMath { @inline(__always) public func applying( _ transform: CGAffineTransform) -> CGSize { var newSize = CGSize(width: transform.a * width + transform.c * height, height: transform.b * width + transform.d * height) if newSize.width < 0 { newSize.width = -newSize.width } if newSize.height < 0 { newSize.height = -newSize.height } return newSize } } // MARK: - Cairo Conversion extension CGAffineTransform: CairoConvertible { public typealias CairoType = Cairo.Matrix @inline(__always) public init(cairo matrix: CairoType) { self.init(a: CGFloat(matrix.xx), b: CGFloat(matrix.xy), c: CGFloat(matrix.yx), d: CGFloat(matrix.yy), tx: CGFloat(matrix.x0), ty: CGFloat(matrix.y0)) } @inline(__always) public func toCairo() -> CairoType { var matrix = Matrix() matrix.xx = Double(a) matrix.xy = Double(b) matrix.yx = Double(c) matrix.yy = Double(d) matrix.x0 = Double(tx) matrix.y0 = Double(ty) return matrix } }
mit
56f6f359571b948919c97cf6c1acd176
21.422764
91
0.569253
4.134933
false
false
false
false
iAladdin/SwiftyFORM
Example/TextView/TextViewValidationViewController.swift
1
2441
// // TextViewValidationViewController.swift // SwiftyFORM // // Created by Simon Strandgaard on 15/12/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit import SwiftyFORM class TextViewValidationViewController: FormViewController { override func populate(builder: FormBuilder) { builder.navigationTitle = "Validation" builder += longSummary builder += notes builder += commentArea builder += userDescription builder += SectionHeaderTitleFormItem().title("Buttons") builder += randomizeButton builder += clearButton } lazy var longSummary: TextViewFormItem = { let instance = TextViewFormItem() instance.title("Long summary").placeholder("placeholder") instance.value = "Lorem ipsum" return instance }() lazy var notes: TextViewFormItem = { let instance = TextViewFormItem() instance.title("Notes").placeholder("I'm a placeholder") return instance }() lazy var commentArea: TextViewFormItem = { let instance = TextViewFormItem() instance.title("Comments").placeholder("I'm also a placeholder") return instance }() lazy var userDescription: TextViewFormItem = { let instance = TextViewFormItem() instance.title("Description").placeholder("Yet another placeholder") return instance }() lazy var randomizeButton: ButtonFormItem = { let instance = ButtonFormItem() instance.title("Randomize") instance.action = { [weak self] in self?.randomize() } return instance }() lazy var clearButton: ButtonFormItem = { let instance = ButtonFormItem() instance.title("Clear") instance.action = { [weak self] in self?.clear() } return instance }() func pickRandom(strings: [String]) -> String { if strings.count == 0 { return "" } let i = randomInt(0, strings.count - 1) return strings[i] } func appendRandom(textView: TextViewFormItem, strings: [String]) { let notEmpty = textView.value.characters.count != 0 var s = "" if notEmpty { s = " " } textView.value += s + pickRandom(strings) } func randomize() { appendRandom(longSummary, strings: ["Hello", "World", "Cat", "Water", "Fish", "Hund"]) appendRandom(notes, strings: ["Hat", "Ham", "Has"]) commentArea.value += pickRandom(["a", "b", "c"]) userDescription.value += pickRandom(["x", "y", "z", "w"]) } func clear() { longSummary.value = "" notes.value = "" commentArea.value = "" userDescription.value = "" } }
mit
a1d4489fc6ff0a6ba16ebf073f3d2da9
23.908163
88
0.686604
3.732416
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/BezierCurveQuadratic.swift
1
3319
// // BezierCurveQuadratic.swift // BezierCurve // // Created by James Bean on 10/26/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit // Port of degrafa public class BezierCurveQuadratic: BezierCurve { // First point public var p1: CGPoint // Control point public var cp: CGPoint // Last point public var p2: CGPoint public var uiBezierPath: UIBezierPath { get { return getUIBezierPath() } } public var cgPath: CGPath { get { return uiBezierPath.CGPath } } /* // rearrange so that these are used private var c0: CGPoint? private var c1: CGPoint? private var c2: CGPoint? */ // Coefficients: set within setCoefficients() private var c0x: CGFloat = 0 private var c0y: CGFloat = 0 private var c1x: CGFloat = 0 private var c1y: CGFloat = 0 private var c2x: CGFloat = 0 private var c2y: CGFloat = 0 public init(point1: CGPoint, controlPoint: CGPoint, point2: CGPoint) { self.p1 = point1 self.cp = controlPoint self.p2 = point2 setCoefficients() } public func getXAtT(t: CGFloat) -> CGFloat? { let x = ((1 - t) * (1 - t) * p1.x) + (2 * (1-t) * t * cp.x) + (t * t * p2.x) return x } public func getYAtT(t: CGFloat) -> CGFloat? { let y = ((1 - t) * (1 - t) * p1.y) + (2 * (1-t) * t * cp.y) + (t * t * p2.y) return y } public func getYValuesAtX(x: CGFloat) -> [CGFloat] { if !isWithinBounds(x: x) { return [] } let c = c0x - x let b = c1x var a = c2x var d = (b * b) - (4 * a * c) if d < 0 { return [] } d = sqrt(d) a = 1 / (a + a) // two potential values for t let t0 = (d - b) * a let t1 = (-b - d) * a var yValues: [CGFloat] = [] if let y = getYAtT(t0) where t0 <= 1 { yValues.append(y) } if let y = getYAtT(t1) where t1 >= 0 && t1 <= 1 { yValues.append(y) } return yValues } public func getXAtY(y: CGFloat) -> [CGFloat] { // TODO return [] } public func getTAtMaxX() -> CGFloat { return 0 } public func getTAtMinX() -> CGFloat { return 0 } public func getTAtMinY() -> CGFloat { // TODO return 0 } public func getTAtMaxY() -> CGFloat { // TODO return 0 } private func setCoefficients() { c0x = p1.x c0y = p1.y c1x = 2.0 * (cp.x - p1.x) c1y = 2.0 * (cp.y - p1.y) c2x = p1.x - (2.0 * cp.x) + p2.x c2y = p1.y - (2.0 * cp.y) + p2.y } public func isWithinBounds(y y: CGFloat) -> Bool { let maxY = [p1.y, p2.y].maxElement()! let minY = [p1.y, p2.y].minElement()! return y >= minY && y <= maxY } public func isWithinBounds(x x: CGFloat) -> Bool { let maxX = [p1.x, p2.x].maxElement()! let minX = [p1.x, p2.x].minElement()! return x >= minX && x <= maxX } private func getUIBezierPath() -> UIBezierPath { let path = UIBezierPath() path.moveToPoint(p1) path.addQuadCurveToPoint(p2, controlPoint: cp) return path } }
gpl-2.0
46ac54e7db2a60dde11035fe59ba23b6
24.523077
84
0.509946
3.378819
false
false
false
false
460467069/smzdm
什么值得买7.1.1版本/什么值得买(5月12日)/Classes/Home(首页)/View/ZZHomePromotionCellEight.swift
1
5530
// // ZZHomePromotionCellEight.swift // 什么值得买 // // Created by Wang_ruzhou on 2017/3/9. // Copyright © 2017年 Wang_ruzhou. All rights reserved. // import UIKit class ZZHomePromotionItemEight: UIView { lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.backgroundColor = UIColor.zz_random() return imageView }() lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.textColor = kGlobalGrayColor titleLabel.font = UIFont.systemFont(ofSize: 14) titleLabel.textAlignment = .center return titleLabel }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(imageView) self.addSubview(titleLabel) imageView.snp.makeConstraints { (make) in make.top.left.right.equalTo(self) make.bottom.equalTo(titleLabel.snp.top) } titleLabel.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ZZHomePromotionCollectionCellEight: UICollectionViewCell { var littleBanener: ZZLittleBanner? { didSet { if let littleBanener = littleBanener { homePromotionItemEight.imageView.zdm_setImage(urlStr: littleBanener.pic, placeHolder: nil) homePromotionItemEight.titleLabel.text = littleBanener.title } } } lazy var homePromotionItemEight: ZZHomePromotionItemEight = { let homePromotionItemEight = ZZHomePromotionItemEight() return homePromotionItemEight }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(homePromotionItemEight) homePromotionItemEight.snp.makeConstraints { (make) in make.edges.equalTo(UIEdgeInsets.zero) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } @objcMembers class ZZHomePromotionCellEight: UITableViewCell { lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.textColor = kGlobalGrayColor titleLabel.font = UIFont.systemFont(ofSize: 14) return titleLabel }() lazy var lineLabel: UILabel = { let lineLabel = UILabel() lineLabel.backgroundColor = kGlobalLightGrayColor return lineLabel }() lazy var collectionView: UICollectionView = { let collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: ZZGoodsHeaderLayout()) collectionView.backgroundColor = UIColor.white collectionView.delegate = self collectionView.dataSource = self // collectionView.contentInset = UIEdgeInsets.init(top: collectionViewTop, left: collectionViewLeft, bottom: collectionViewBottom, right: collectionViewRight) collectionView.registerReuseCellClass(ZZHomePromotionCollectionCellEight.self) return collectionView }() var dataSource: [ZZLittleBanner] = [] override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } var article: ZZWorthyArticle? { didSet { if let article = article { titleLabel.text = article.title if let rows = article.rows { dataSource = rows collectionView.reloadData() } } } } func initUI() { contentView.addSubview(titleLabel) contentView.addSubview(lineLabel) contentView.addSubview(collectionView) titleLabel.snp.makeConstraints { (make) in make.top.left.equalTo(self.contentView).offset(15) } lineLabel.snp.makeConstraints { (make) in make.width.equalTo(self.contentView) make.height.equalTo(0.5) make.top.equalTo(titleLabel.snp.bottom).offset(15) } collectionView.snp.makeConstraints { (make) in make.top.equalTo(lineLabel.snp.bottom) make.left.right.bottom.equalTo(self.contentView) } } } extension ZZHomePromotionCellEight: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(ZZHomePromotionCollectionCellEight.self), for: indexPath) as! ZZHomePromotionCollectionCellEight collectionViewCell.littleBanener = dataSource[indexPath.item] return collectionViewCell } } extension ZZHomePromotionCellEight: UICollectionViewDelegate { }
mit
07b68ea35835e9f5c45017314db879ff
31.839286
203
0.655791
5.02917
false
false
false
false
doushiDev/ds_ios
TouTiao/RealmVideo.swift
1
550
// // RealmVideo.swift // TouTiao // // Created by Songlijun on 2017/2/26. // Copyright © 2017年 Songlijun. All rights reserved. // import Foundation import RealmSwift import Realm class RealmVideo: Object { dynamic var vid:String = "" dynamic var title:String = "" dynamic var pic:String = "" dynamic var shareUrl:String = "" dynamic var videoUrl:String = "" dynamic var createDate:String = "" dynamic var at:Int = 1 override static func primaryKey() -> String? { return "vid" } }
mit
df29672f5726572b986b523202970da4
17.862069
53
0.630713
3.721088
false
false
false
false
zs40x/PairProgrammingTimer
PairProgrammingTimer/ViewController/SessionLogViewController.swift
1
5722
// // SessionLogViewController.swift // PairProgrammingTimer // // Created by Stefan Mehnert on 11.04.17. // Copyright © 2017 Stefan Mehnert. All rights reserved. // import UIKit import MessageUI class SessionLogEntryCell : UITableViewCell { @IBOutlet weak var developerName: UILabel! @IBOutlet weak var otherDeveloperName: UILabel! @IBOutlet weak var from: UILabel! @IBOutlet weak var until: UILabel! @IBOutlet weak var duration: UILabel! @IBOutlet weak var sessionDuration: UILabel! @IBOutlet weak var sessionDurationDifference: UILabel! } class SessionLogViewController: UIViewController, SessionLogConsumer { @IBOutlet weak var tableViewLogEntries: UITableView! @IBOutlet weak var menuButtonSendAsMail: UIBarButtonItem! var sessionLog: SessionLog? fileprivate var logEntries = [SessionLogEntry]() override func viewDidLoad() { super.viewDidLoad() tableViewLogEntries.dataSource = self } override func viewWillAppear(_ animated: Bool) { updateTableView() } fileprivate func updateTableView() { guard let sessionLog = self.sessionLog else { return } logEntries = sessionLog.entries.sorted(by: { $0.startedOn > $1.startedOn }) tableViewLogEntries.reloadData() } @IBAction func actionClearLog(_ sender: Any) { let alertView = UIAlertController( title: NSLocalizedString("ClearLog", comment: "Clear log"), message: NSLocalizedString("InfoAllLogEntriesWillBeDeleted", comment: "All log entries will be deleted!"), preferredStyle: .actionSheet) let confirmAction = UIAlertAction(title: NSLocalizedString("Confirm", comment: "Confirm"), style: .destructive, handler: { _ in self.sessionLog?.clear() self.updateTableView() }) alertView.addAction(confirmAction) let abortAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel"), style: .cancel, handler: nil) alertView.addAction(abortAction) present(alertView, animated: true, completion: nil) } @IBAction func actionSendAsMail(_ sender: Any) { do { let fileUrl = try SessionUserDefaultsLogService().exportToFileSystem() guard fileUrl != nil else { showErrorMessage(title: NSLocalizedString("SharingFailed", comment: "Sharing failed"), message: NSLocalizedString("ExportFailedMsg", comment: "Failed to export: detailed error")) return } let activityViewController = UIActivityViewController( activityItems: [NSLocalizedString("ShareMessage", comment: "Message to show when sharing an exported file."), fileUrl as Any!], applicationActivities: nil) if let popoverPresentationController = activityViewController.popoverPresentationController { popoverPresentationController.barButtonItem = (sender as! UIBarButtonItem) } present(activityViewController, animated: true, completion: nil) } catch let error { showErrorMessage(title: NSLocalizedString("SharingFailed", comment: "Sharing failed"), message: error.localizedDescription) NSLog("Error sharing the PairProgTimer.log file: \(error.localizedDescription)") return } } } extension SessionLogViewController: SessionLogDelegate { func logUpdated() { updateTableView() } } extension SessionLogViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return logEntries.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: "SessionLogEntryCell", for: indexPath) as! SessionLogEntryCell let logEntry = logEntries[(indexPath as NSIndexPath).row] cell.developerName.text = logEntry.developerName cell.otherDeveloperName.text = logEntry.otherDeveloperName cell.from.text = logEntry.startedOn.formattedString(customDateFormat: .dateAndTime) if let until = logEntry.endedOn { cell.until.text = until.formattedString(customDateFormat: .timeOnly) } else { cell.until.text = "" } cell.duration.text = String(format: "%.2f", logEntry.actualDuration) cell.sessionDuration.text = String(format: "%.0f", logEntry.plannedDuration.TotalMinutes) var durationDifference = String(format: "%0.2f", logEntry.durationDifference) if logEntry.durationDifference > 0 { durationDifference = "+\(durationDifference)" } cell.sessionDurationDifference.text = durationDifference return cell } } extension SessionLogViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { self.dismiss(animated: true, completion: nil) } }
mit
426e15ca0d9b991dd9e56998b82293bc
35.208861
133
0.619472
5.715285
false
false
false
false
qx/SwiftSpinner
SwiftSpinner/SwiftSpinner.swift
5
14674
// // Copyright (c) 2015 Marin Todorov, Underplot ltd. // This code is distributed under the terms and conditions of the MIT license. // // 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 public class SwiftSpinner: UIView { // MARK: - Singleton // // Access the singleton instance // public class var sharedInstance: SwiftSpinner { struct Singleton { static let instance = SwiftSpinner(frame: CGRect.zeroRect) } return Singleton.instance } // MARK: - Init // // Custom init to build the spinner UI // public override init(frame: CGRect) { super.init(frame: frame) blurEffect = UIBlurEffect(style: blurEffectStyle) blurView = UIVisualEffectView(effect: blurEffect) addSubview(blurView) vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect)) addSubview(vibrancyView) let titleScale: CGFloat = 0.85 titleLabel.frame.size = CGSize(width: frameSize.width * titleScale, height: frameSize.height * titleScale) titleLabel.font = defaultTitleFont titleLabel.numberOfLines = 0 titleLabel.textAlignment = .Center titleLabel.lineBreakMode = .ByWordWrapping titleLabel.adjustsFontSizeToFitWidth = true vibrancyView.contentView.addSubview(titleLabel) blurView.contentView.addSubview(vibrancyView) outerCircleView.frame.size = frameSize outerCircle.path = UIBezierPath(ovalInRect: CGRect(x: 0.0, y: 0.0, width: frameSize.width, height: frameSize.height)).CGPath outerCircle.lineWidth = 8.0 outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 0.45 outerCircle.lineCap = kCALineCapRound outerCircle.fillColor = UIColor.clearColor().CGColor outerCircle.strokeColor = UIColor.whiteColor().CGColor outerCircleView.layer.addSublayer(outerCircle) outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 1.0 vibrancyView.contentView.addSubview(outerCircleView) innerCircleView.frame.size = frameSize let innerCirclePadding: CGFloat = 12 innerCircle.path = UIBezierPath(ovalInRect: CGRect(x: innerCirclePadding, y: innerCirclePadding, width: frameSize.width - 2*innerCirclePadding, height: frameSize.height - 2*innerCirclePadding)).CGPath innerCircle.lineWidth = 4.0 innerCircle.strokeStart = 0.5 innerCircle.strokeEnd = 0.9 innerCircle.lineCap = kCALineCapRound innerCircle.fillColor = UIColor.clearColor().CGColor innerCircle.strokeColor = UIColor.grayColor().CGColor innerCircleView.layer.addSublayer(innerCircle) innerCircle.strokeStart = 0.0 innerCircle.strokeEnd = 1.0 vibrancyView.contentView.addSubview(innerCircleView) userInteractionEnabled = true } public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { return self } // MARK: - Public interface public lazy var titleLabel = UILabel() public var subtitleLabel: UILabel? // // Show the spinner activity on screen, if visible only update the title // public class func show(title: String, animated: Bool = true) -> SwiftSpinner { let window = UIApplication.sharedApplication().windows.first as! UIWindow let spinner = SwiftSpinner.sharedInstance spinner.showWithDelayBlock = nil spinner.clearTapHandler() spinner.updateFrame() if spinner.superview == nil { //show the spinner spinner.alpha = 0.0 window.addSubview(spinner) UIView.animateWithDuration(0.33, delay: 0.0, options: .CurveEaseOut, animations: { spinner.alpha = 1.0 }, completion: nil) // Orientation change observer NSNotificationCenter.defaultCenter().addObserver( spinner, selector: "updateFrame", name: UIApplicationDidChangeStatusBarOrientationNotification, object: nil) } spinner.title = title spinner.animating = animated return spinner } // // Show the spinner activity on screen, after delay. If new call to show, // showWithDelay or hide is maked before execution this call is discarded // public class func showWithDelay(delay: Double, title: String, animated: Bool = true) -> SwiftSpinner { let spinner = SwiftSpinner.sharedInstance spinner.showWithDelayBlock = { SwiftSpinner.show(title, animated: animated) } spinner.delay(seconds: delay) { [weak spinner] in if let spinner = spinner { spinner.showWithDelayBlock?() } } return spinner } // // Hide the spinner // public class func hide(completion: (() -> Void)? = nil) { let spinner = SwiftSpinner.sharedInstance NSNotificationCenter.defaultCenter().removeObserver(spinner) dispatch_async(dispatch_get_main_queue(), { spinner.showWithDelayBlock = nil spinner.clearTapHandler() if spinner.superview == nil { return } UIView.animateWithDuration(0.33, delay: 0.0, options: .CurveEaseOut, animations: { spinner.alpha = 0.0 }, completion: {_ in spinner.alpha = 1.0 spinner.removeFromSuperview() spinner.titleLabel.font = spinner.defaultTitleFont spinner.titleLabel.text = nil completion?() }) spinner.animating = false }) } // // Set the default title font // public class func setTitleFont(font: UIFont?) { let spinner = SwiftSpinner.sharedInstance if let font = font { spinner.titleLabel.font = font } else { spinner.titleLabel.font = spinner.defaultTitleFont } } // // The spinner title // public var title: String = "" { didSet { let spinner = SwiftSpinner.sharedInstance UIView.animateWithDuration(0.15, delay: 0.0, options: .CurveEaseOut, animations: { spinner.titleLabel.transform = CGAffineTransformMakeScale(0.75, 0.75) spinner.titleLabel.alpha = 0.2 }, completion: {_ in spinner.titleLabel.text = self.title UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 0.0, options: nil, animations: { spinner.titleLabel.transform = CGAffineTransformIdentity spinner.titleLabel.alpha = 1.0 }, completion: nil) }) } } // // observe the view frame and update the subviews layout // public override var frame: CGRect { didSet { if frame == CGRect.zeroRect { return } blurView.frame = bounds vibrancyView.frame = blurView.bounds titleLabel.center = vibrancyView.center outerCircleView.center = vibrancyView.center innerCircleView.center = vibrancyView.center if let subtitle = subtitleLabel { subtitle.bounds.size = subtitle.sizeThatFits(CGRectInset(bounds, 20.0, 0.0).size) subtitle.center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMaxY(bounds) - CGRectGetMidY(subtitle.bounds) - subtitle.font.pointSize) } } } // // Start the spinning animation // public var animating: Bool = false { willSet (shouldAnimate) { if shouldAnimate && !animating { spinInner() spinOuter() } } didSet { // update UI if animating { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 0.45 self.innerCircle.strokeStart = 0.5 self.innerCircle.strokeEnd = 0.9 } else { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 1.0 self.innerCircle.strokeStart = 0.0 self.innerCircle.strokeEnd = 1.0 } } } // // Tap handler // public func addTapHandler(tap: (()->()), subtitle subtitleText: String? = nil) { clearTapHandler() //vibrancyView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTapSpinner"))) tapHandler = tap if subtitleText != nil { subtitleLabel = UILabel() if let subtitle = subtitleLabel { subtitle.text = subtitleText subtitle.font = UIFont(name: defaultTitleFont.familyName, size: defaultTitleFont.pointSize * 0.8) subtitle.textColor = UIColor.whiteColor() subtitle.numberOfLines = 0 subtitle.textAlignment = .Center subtitle.lineBreakMode = .ByWordWrapping subtitle.bounds.size = subtitle.sizeThatFits(CGRectInset(bounds, 20.0, 0.0).size) subtitle.center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMaxY(bounds) - CGRectGetMidY(subtitle.bounds) - subtitle.font.pointSize) vibrancyView.contentView.addSubview(subtitle) } } } public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) if tapHandler != nil { tapHandler?() tapHandler = nil } } public func clearTapHandler() { userInteractionEnabled = false subtitleLabel?.removeFromSuperview() tapHandler = nil } // MARK: - Private interface // // layout elements // private var blurEffectStyle: UIBlurEffectStyle = .Dark private var blurEffect: UIBlurEffect! private var blurView: UIVisualEffectView! private var vibrancyView: UIVisualEffectView! var defaultTitleFont = UIFont(name: "HelveticaNeue", size: 22.0)! let frameSize = CGSize(width: 200.0, height: 200.0) private lazy var outerCircleView = UIView() private lazy var innerCircleView = UIView() private let outerCircle = CAShapeLayer() private let innerCircle = CAShapeLayer() private var showWithDelayBlock: (()->())? required public init(coder aDecoder: NSCoder) { fatalError("Not coder compliant") } private var currentOuterRotation: CGFloat = 0.0 private var currentInnerRotation: CGFloat = 0.1 private func spinOuter() { if superview == nil { return } let duration = Double(Float(arc4random()) / Float(UInt32.max)) * 2.0 + 1.5 let randomRotation = Double(Float(arc4random()) / Float(UInt32.max)) * M_PI_4 + M_PI_4 //outer circle UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: nil, animations: { self.currentOuterRotation -= CGFloat(randomRotation) self.outerCircleView.transform = CGAffineTransformMakeRotation(self.currentOuterRotation) }, completion: {_ in let waitDuration = Double(Float(arc4random()) / Float(UInt32.max)) * 1.0 + 1.0 self.delay(seconds: waitDuration, completion: { if self.animating { self.spinOuter() } }) }) } private func spinInner() { if superview == nil { return } //inner circle UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: nil, animations: { self.currentInnerRotation += CGFloat(M_PI_4) self.innerCircleView.transform = CGAffineTransformMakeRotation(self.currentInnerRotation) }, completion: {_ in self.delay(seconds: 0.5, completion: { if self.animating { self.spinInner() } }) }) } public func updateFrame() { let window = UIApplication.sharedApplication().windows.first as! UIWindow SwiftSpinner.sharedInstance.frame = window.frame } // MARK: - Util methods func delay(#seconds: Double, completion:()->()) { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds )) dispatch_after(popTime, dispatch_get_main_queue()) { completion() } } override public func layoutSubviews() { super.layoutSubviews() updateFrame() } // MARK: - Tap handler private var tapHandler: (()->())? func didTapSpinner() { tapHandler?() } }
mit
56ec12f1b4d213a2ce64b4645b0be24f
35.321782
463
0.594794
5.39287
false
false
false
false
Lomotif/lomotif-ios-httprequest
Pods/SwiftyBeaver/sources/SBPlatformDestination.swift
2
22633
// // SBPlatformDestination // SwiftyBeaver // // Created by Sebastian Kreutzberger on 22.01.16. // Copyright © 2016 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation // platform-dependent import frameworks to get device details // valid values for os(): OSX, iOS, watchOS, tvOS, Linux // in Swift 3 the following were added: FreeBSD, Windows, Android #if os(iOS) || os(tvOS) || os(watchOS) import UIKit var DEVICE_MODEL: String { get { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } return identifier } } #else let DEVICE_MODEL = "" #endif #if os(iOS) || os(tvOS) var DEVICE_NAME = UIDevice.current.name #else // under watchOS UIDevice is not existing, http://apple.co/26ch5J1 let DEVICE_NAME = "" #endif public class SBPlatformDestination: BaseDestination { public var appID = "" public var appSecret = "" public var encryptionKey = "" public var analyticsUserName = "" // user email, ID, name, etc. public var analyticsUUID: String { get { return uuid } } // when to send to server public struct SendingPoints { public var verbose = 0 public var debug = 1 public var info = 5 public var warning = 8 public var error = 10 public var threshold = 10 // send to server if points reach that value } public var sendingPoints = SendingPoints() public var showNSLog = false // executes toNSLog statements to debug the class var points = 0 public var serverURL = URL(string: "https://api.swiftybeaver.com/api/entries/")! public var entriesFileURL = URL(string: "") public var sendingFileURL = URL(string: "") public var analyticsFileURL = URL(string: "") private let minAllowedThreshold = 1 // over-rules SendingPoints.Threshold private let maxAllowedThreshold = 1000 // over-rules SendingPoints.Threshold private var sendingInProgress = false private var initialSending = true // analytics var uuid = "" // destination override public var defaultHashValue: Int {return 3} let fileManager = FileManager.default let isoDateFormatter = DateFormatter() public init(appID: String, appSecret: String, encryptionKey: String) { super.init() self.appID = appID self.appSecret = appSecret self.encryptionKey = encryptionKey // setup where to write the json files var baseURL: URL? if OS == "OSX" { if let url = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first { baseURL = url // try to use ~/Library/Application Support/APP NAME instead of ~/Library/Application Support if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String { do { if let appURL = baseURL?.appendingPathComponent(appName, isDirectory: true) { try fileManager.createDirectory(at: appURL, withIntermediateDirectories: true, attributes: nil) baseURL = appURL } } catch let error as NSError { // it is too early in the class lifetime to be able to use toNSLog() print("Warning! Could not create folder ~/Library/Application Support/\(appName). \(error)") } } } } else { // iOS, watchOS, etc. are using the app’s document directory, tvOS can just use the caches directory #if os(tvOS) let saveDir: FileManager.SearchPathDirectory = .cachesDirectory #else let saveDir: FileManager.SearchPathDirectory = .documentDirectory #endif if let url = fileManager.urls(for: saveDir, in: .userDomainMask).first { baseURL = url } } if let baseURL = baseURL { entriesFileURL = baseURL.appendingPathComponent("sbplatform_entries.json", isDirectory: false) sendingFileURL = baseURL.appendingPathComponent("sbplatform_entries_sending.json", isDirectory: false) analyticsFileURL = baseURL.appendingPathComponent("sbplatform_analytics.json", isDirectory: false) // get, update loaded and save analytics data to file on start if let analyticsFileURL = analyticsFileURL { let dict = analytics(analyticsFileURL, update: true) let _ = saveDictToFile(dict, url: analyticsFileURL) } else { print("Warning! Could not set URLs. analyticsFileURL does not exist") } } } // append to file, each line is a JSON dict override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int) -> String? { var jsonString: String? let dict: [String: Any] = [ "timestamp": NSDate().timeIntervalSince1970, "level": level.rawValue, "message": msg, "thread": thread, "fileName": file.components(separatedBy: "/").last!, "function": function, "line":line] jsonString = jsonStringFromDict(dict) if let str = jsonString { toNSLog("saving '\(msg)' to file") let _ = saveToFile(str, url: entriesFileURL!) //toNSLog(entriesFileURL.path!) // now decide if the stored log entries should be sent to the server // add level points to current points amount and send to server if threshold is hit let newPoints = sendingPointsForLevel(level) points += newPoints toNSLog("current sending points: \(points)") if (points >= sendingPoints.threshold && points >= minAllowedThreshold) || points > maxAllowedThreshold { toNSLog("\(points) points is >= threshold") // above threshold, send to server sendNow() } else if initialSending { initialSending = false // first logging at this session // send if json file still contains old log entries if let logEntries = logsFromFile(entriesFileURL!) { let lines = logEntries.count if lines > 1 { var msg = "initialSending: \(points) points is below threshold " msg += "but json file already has \(lines) lines." toNSLog(msg) sendNow() } } } } return jsonString } // MARK: Send-to-Server Logic /// does a (manual) sending attempt of all unsent log entries to SwiftyBeaver Platform public func sendNow() { if sendFileExists() { toNSLog("reset points to 0") points = 0 } else { if !renameJsonToSendFile() { return } } if !sendingInProgress { sendingInProgress = true //let (jsonString, lines) = logsFromFile(sendingFileURL) var lines = 0 guard let logEntries = logsFromFile(sendingFileURL!) else { sendingInProgress = false return } lines = logEntries.count if lines > 0 { var payload = [String:Any]() // merge device and analytics dictionaries let deviceDetailsDict = deviceDetails() var analyticsDict = analytics(analyticsFileURL!) for key in deviceDetailsDict.keys { analyticsDict[key] = deviceDetailsDict[key] } payload["device"] = analyticsDict payload["entries"] = logEntries if let str = jsonStringFromDict(payload) { //toNSLog(str) // uncomment to see full payload toNSLog("Encrypting \(lines) log entries ...") if let encryptedStr = encrypt(str) { var msg = "Sending \(lines) encrypted log entries " msg += "(\(encryptedStr.characters.count) chars) to server ..." toNSLog(msg) //toNSLog("Sending \(encryptedStr) ...") sendToServerAsync(encryptedStr) { ok, status in self.toNSLog("Sent \(lines) encrypted log entries to server, received ok: \(ok)") if ok { let _ = self.deleteFile(self.sendingFileURL!) } self.sendingInProgress = false self.points = 0 } } } } else { sendingInProgress = false } } } /// sends a string to the SwiftyBeaver Platform server, returns ok if status 200 and HTTP status func sendToServerAsync(_ str: String?, complete: @escaping (_ ok: Bool, _ status: Int) -> ()) { // swiftlint:disable conditional_binding_cascade if let payload = str, let queue = self.queue { // swiftlint:enable conditional_binding_cascade // create operation queue which uses current serial queue of destination let operationQueue = OperationQueue() operationQueue.underlyingQueue = queue let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: operationQueue) // assemble request var request = URLRequest(url: serverURL) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") // basic auth header let credentials = "\(appID):\(appSecret)".data(using: String.Encoding.utf8)! let base64Credentials = credentials.base64EncodedString(options: []) request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization") // POST parameters let params = ["payload": payload] do { request.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) } catch let error as NSError { toNSLog("Error! Could not create JSON for server payload. \(error)") } //toNSLog("sending params: \(params)") //toNSLog("\n\nbefore sendToServer on thread '\(threadName())'") sendingInProgress = true // send request async to server on destination queue let task = session.dataTask(with: request) { _, response, error in var ok = false var status = 0 //toNSLog("callback of sendToServer on thread '\(self.threadName())'") if let error = error { // an error did occur self.toNSLog("Error! Could not send entries to server. \(error)") } else { if let response = response as? HTTPURLResponse { status = response.statusCode if status == 200 { // all went well, entries were uploaded to server ok = true } else { // status code was not 200 var msg = "Error! Sending entries to server failed " msg += "with status code \(status)" self.toNSLog(msg) } } } return complete(ok, status) } task.resume() } } /// returns sending points based on level func sendingPointsForLevel(_ level: SwiftyBeaver.Level) -> Int { switch level { case SwiftyBeaver.Level.debug: return sendingPoints.debug case SwiftyBeaver.Level.info: return sendingPoints.info case SwiftyBeaver.Level.warning: return sendingPoints.warning case SwiftyBeaver.Level.error: return sendingPoints.error default: return sendingPoints.verbose } } // MARK: File Handling /// appends a string as line to a file. /// returns boolean about success func saveToFile(_ str: String, url: URL, overwrite: Bool = false) -> Bool { do { if fileManager.fileExists(atPath: url.path) == false || overwrite { // create file if not existing let line = str + "\n" try line.write(to: url, atomically: true, encoding: String.Encoding.utf8) } else { // append to end of file let fileHandle = try FileHandle(forWritingTo: url) fileHandle.seekToEndOfFile() let line = str + "\n" let data = line.data(using: String.Encoding.utf8)! fileHandle.write(data) fileHandle.closeFile() } return true } catch let error { toNSLog("Error! Could not write to file \(url). \(error)") return false } } func sendFileExists() -> Bool { return fileManager.fileExists(atPath: sendingFileURL!.path) } func renameJsonToSendFile() -> Bool { do { try fileManager.moveItem(at: entriesFileURL!, to: sendingFileURL!) return true } catch let error as NSError { toNSLog("SwiftyBeaver Platform Destination could not rename json file. \(error)") return false } } /// returns optional array of log dicts from a file which has 1 json string per line func logsFromFile(_ url: URL) -> [[String:Any]]? { var lines = 0 do { // try to read file, decode every JSON line and put dict from each line in array let fileContent = try NSString(contentsOfFile: url.path, encoding: String.Encoding.utf8.rawValue) let linesArray = fileContent.components(separatedBy: "\n") var dicts = [[String: Any]()] // array of dictionaries for lineJSON in linesArray { lines += 1 if lineJSON.characters.first == "{" && lineJSON.characters.last == "}" { // try to parse json string into dict if let data = lineJSON.data(using: String.Encoding.utf8) { do { if let dict = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] { if !dict.isEmpty { dicts.append(dict) } } } catch let error { var msg = "Error! Could not parse " msg += "line \(lines) in file \(url). \(error)" toNSLog(msg) } } } } dicts.removeFirst() return dicts } catch let error { toNSLog("Error! Could not read file \(url). \(error)") } return nil } /// returns AES-256 CBC encrypted optional string func encrypt(_ str: String) -> String? { return AES256CBC.encryptString(str, password: encryptionKey) } /// Delete file to get started again func deleteFile(_ url: URL) -> Bool { do { try FileManager.default.removeItem(at: url) return true } catch let error { toNSLog("Warning! Could not delete file \(url). \(error)") } return false } // MARK: Device & Analytics // returns dict with device details. Amount depends on platform func deviceDetails() -> [String: String] { var details = [String: String]() details["os"] = OS let osVersion = ProcessInfo.processInfo.operatingSystemVersion // becomes for example 10.11.2 for El Capitan var osVersionStr = String(osVersion.majorVersion) osVersionStr += "." + String(osVersion.minorVersion) osVersionStr += "." + String(osVersion.patchVersion) details["osVersion"] = osVersionStr details["hostName"] = ProcessInfo.processInfo.hostName details["deviceName"] = "" details["deviceModel"] = "" if DEVICE_NAME != "" { details["deviceName"] = DEVICE_NAME } if DEVICE_MODEL != "" { details["deviceModel"] = DEVICE_MODEL } return details } /// returns (updated) analytics dict, optionally loaded from file. func analytics(_ url: URL, update: Bool = false) -> [String:Any] { var dict = [String:Any]() let now = NSDate().timeIntervalSince1970 uuid = NSUUID().uuidString dict["uuid"] = uuid dict["firstStart"] = now dict["lastStart"] = now dict["starts"] = 1 dict["userName"] = analyticsUserName dict["firstAppVersion"] = appVersion() dict["appVersion"] = appVersion() dict["firstAppBuild"] = appBuild() dict["appBuild"] = appBuild() if let loadedDict = dictFromFile(analyticsFileURL!) { if let val = loadedDict["firstStart"] as? Double { dict["firstStart"] = val } if let val = loadedDict["lastStart"] as? Double { if update { dict["lastStart"] = now } else { dict["lastStart"] = val } } if let val = loadedDict["starts"] as? Int { if update { dict["starts"] = val + 1 } else { dict["starts"] = val } } if let val = loadedDict["uuid"] as? String { dict["uuid"] = val uuid = val } if let val = loadedDict["userName"] as? String { if update && !analyticsUserName.isEmpty { dict["userName"] = analyticsUserName } else { if !val.isEmpty { dict["userName"] = val } } } if let val = loadedDict["firstAppVersion"] as? String { dict["firstAppVersion"] = val } if let val = loadedDict["firstAppBuild"] as? Int { dict["firstAppBuild"] = val } } return dict } /// Returns the current app version string (like 1.2.5) or empty string on error func appVersion() -> String { if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String { return version } return "" } /// Returns the current app build as integer (like 563, always incrementing) or 0 on error func appBuild() -> Int { if let version = Bundle.main.infoDictionary?["CFBundleVersion"] as? String { if let intVersion = Int(version) { return intVersion } } return 0 } /// returns optional dict from a json encoded file func dictFromFile(_ url: URL) -> [String:Any]? { do { // try to read file, decode every JSON line and put dict from each line in array let fileContent = try NSString(contentsOfFile: url.path, encoding: String.Encoding.utf8.rawValue) // try to parse json string into dict if let data = fileContent.data(using: String.Encoding.utf8.rawValue) { do { return try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] } catch let error { toNSLog("SwiftyBeaver Platform Destination could not parse file \(url). \(error)") } } } catch let error { toNSLog("SwiftyBeaver Platform Destination could not read file \(url). \(error)") } return nil } // turns dict into JSON and saves it to file func saveDictToFile(_ dict: [String: Any], url: URL) -> Bool { let jsonString = jsonStringFromDict(dict) if let str = jsonString { toNSLog("saving '\(str)' to \(url)") return saveToFile(str, url: url, overwrite: true) } return false } // MARK: Debug Helpers /// log String to toNSLog. Used to debug the class logic func toNSLog(_ str: String) { if showNSLog { NSLog("SBPlatform: \(str)") } } /// helper function for thread logging during development func threadName() -> String { if Thread.isMainThread { return "main" } else { if let threadName = Thread.current.name, !threadName.isEmpty { return threadName } else { return String(format: "%p", Thread.current) } /*else if let queueName = NSString(utf8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)) as String? where !queueName.isEmpty { return queueName } */ } } }
mit
96bde68b23c42c41e626dedf042f5efc
36.343234
117
0.532523
5.362559
false
false
false
false
Zhang-C-C/SWeibo
SWeibo/SWeibo/Classes/Home/HomeTableViewController.swift
1
5649
// // HomeTableViewController.swift // SWeibo // // Created by 诺达科技 on 16/10/9. // Copyright © 2016年 诺达科技. All rights reserved. // import UIKit import SVProgressHUD class HomeTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() //1.如果没有登录,就设置为登录界面信息 if !userLogin { visitorView?.setupVisitorInfo(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人,回这里看看有什么惊喜") return } //2.初始化导航条 setupNav() //3.接受通知,箭头方向改变 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.change), name: PopOverAniationShow, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.change), name: PopOverAniationDismiss, object: nil) } deinit { //移除通知 NSNotificationCenter.defaultCenter().removeObserver(self) } /** 修改箭头方向 */ func change() -> Void { //修改箭头方向 let titleBtn = navigationItem.titleView as! TitleButton titleBtn.selected = !titleBtn.selected } private func setupNav(){ //1.第一种写法 /* //左边按钮 let leftBtn = UIButton() leftBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30) leftBtn.setImage(UIImage(named: "navigationbar_friendattention"), forState: UIControlState.Normal) leftBtn.setImage(UIImage(named: "navigationbar_friendattention_highlighted"), forState: UIControlState.Highlighted) navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn) //右边按钮 let rightBtn = UIButton() rightBtn.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal) rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted) rightBtn.sizeToFit() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn) */ //2.第二种写法 /* navigationItem.leftBarButtonItem = createBarButtonItem("navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.leftItemClick)) navigationItem.rightBarButtonItem = createBarButtonItem("navigationbar_pop", target: self, action: #selector(HomeTableViewController.rightItemClick)) */ ////3.第三种写法 navigationItem.leftBarButtonItem = UIBarButtonItem.crateBarButtonItem("navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.leftItemClick)) navigationItem.rightBarButtonItem = UIBarButtonItem.crateBarButtonItem("navigationbar_pop", target: self, action: #selector(HomeTableViewController.rightItemClick)) //初始化标题按钮 let titleBtn = TitleButton() titleBtn.setTitle("极客江南 ", forState: UIControlState.Normal) titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleBtnClick(_:)), forControlEvents: UIControlEvents.TouchUpInside) titleBtn.sizeToFit() navigationItem.titleView = titleBtn } //MARK -Action- //导航栏左侧按钮点击事件 func leftItemClick() -> Void { } //导航栏右侧按钮点击事件 func rightItemClick() -> Void { let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil) let vc = sb.instantiateInitialViewController() presentViewController(vc!, animated: true, completion: nil) } //标题文字按钮点击事件 func titleBtnClick(btn:UIButton){ //1.箭头方向改变 //btn.selected = !btn.selected //2.弹出菜单 let sb = UIStoryboard(name: "PopoverViewController", bundle: nil) let vc = sb.instantiateInitialViewController() //2.1设置转场代理 //默认情况下,modal会移除以前的控制器,替换为弹出的控制器 //使用自定义,不会移除 vc?.transitioningDelegate = popoverAnimator //2.2设置专场的样式 vc?.modalPresentationStyle = UIModalPresentationStyle.Custom presentViewController(vc!, animated: true, completion: nil) } //MARK: -Lazy 转场动画对象 //一定要定义一个属性来保存自定义转场对象,否则报错 private lazy var popoverAnimator:PopoverAnimation = { let pa = PopoverAnimation() pa.presentFrame = CGRect(x: 100, y: 56, width: 200, height: 250) return pa }() //2.第二种写法 /* /** 创建按钮 - parameter imageName: 图片名字 - returns: UIBarButtonItem对象 */ private func createBarButtonItem(imageName:String, target:AnyObject?, action:Selector) ->UIBarButtonItem { let btn = UIButton() btn.setImage(UIImage(named: imageName), forState: UIControlState.Normal) btn.setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted) btn.sizeToFit() //添加点击事件 btn.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside) let barItem = UIBarButtonItem(customView: btn) return barItem } */ }
mit
7ffb1876ff560cccc9c3895b13f1c1a4
32.947368
182
0.64845
4.99516
false
false
false
false
lorentey/swift
test/SILOptimizer/definite_init.swift
57
866
// RUN: %target-swift-frontend -emit-sil %s -o /dev/null class SomeClass {} // These are tests for values that are only initialized on some path through the // CFG. func partialInit() { // Value of trivial type. func trivial(ni : Int) { var n = ni while (n > 0) { n -= 1 var x : Int if (n > 2) { continue } x = 1 _ = x } } // Tuple with only some elements specified. func trivial_tuple() { var a : (Int, Int) a.1 = 1 _ = a.1 } func tuple_test(cond : Bool) { var x : (SomeClass, SomeClass) if cond { x.0 = SomeClass() } else { x.1 = SomeClass() _ = x.1 } } } func tuple_test() -> Int { var t : (Int, Int) t.1 = 4 for _ in 0..<45 { } t.0 = 1 for _ in 0..<45 { } return t.1+t.0 // No diagnostic, everything is fully initialized. }
apache-2.0
5d25208ffe93aaca0c4bb8c76fc05ea1
14.745455
80
0.513857
3.092857
false
true
false
false
hooman/swift
test/SourceKit/ExpressionType/filtered.swift
14
2824
// RUN lines at the end - offset sensitive protocol Prot {} protocol Prot1 {} class Clas: Prot { var value: Clas { return self } func getValue() -> Clas { return self } } struct Stru: Prot, Prot1 { var value: Stru { return self } func getValue() -> Stru { return self } } class C {} func ArrayC(_ a: [C]) { _ = a.count _ = a.description.count.advanced(by: 1).description _ = a[0] } func ArrayClas(_ a: [Clas]) { _ = a[0].value.getValue().value } func ArrayClas(_ a: [Stru]) { _ = a[0].value.getValue().value } protocol Proto2 {} class Proto2Conformer: Proto2 {} func foo(_ c: Proto2Conformer) { _ = c } // BOTH: <ExpressionTypes> // BOTH: (126, 130): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (168, 172): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (232, 236): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (274, 278): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (434, 461): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (434, 455): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (434, 444): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (434, 438): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (500, 527): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (500, 521): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (500, 510): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (500, 504): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: </ExpressionTypes> // PROTO1: <ExpressionTypes> // PROTO1: (232, 236): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (274, 278): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (500, 527): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (500, 521): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (500, 510): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (500, 504): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: </ExpressionTypes> // PROTO2: <ExpressionTypes> // PROTO2: (622, 623): Proto2Conformer // PROTO2: conforming to: s:8filtered6Proto2P // PROTO2: </ExpressionTypes> // RUN: %sourcekitd-test -req=collect-type %s -req-opts=expectedtypes='[s:8filtered4ProtP;s:8filtered5Prot1P]' -- %s | %FileCheck %s -check-prefix=BOTH // RUN: %sourcekitd-test -req=collect-type %s -req-opts=expectedtypes='[s:8filtered5Prot1P]' -- %s | %FileCheck %s -check-prefix=PROTO1 // RUN: %sourcekitd-test -req=collect-type %s -req-opts=expectedtypes='[s:8filtered6Proto2P]' -- %s | %FileCheck %s -check-prefix=PROTO2
apache-2.0
9e8c35bb0637ee34ba38996ff9cc8ddd
29.376344
151
0.685552
2.849647
false
false
false
false
n8iveapps/N8iveKit
NetworkKit/NetworkKit/OpenSource/Alamofire/Validation.swift
1
11592
// // Validation.swift // // Copyright (c) 2014-2016 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 Foundation extension Request { // MARK: Helper Types fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason /// Used to represent whether validation was successful or encountered an error resulting in a failure. /// /// - success: The validation was successful. /// - failure: The validation failed encountering the provided error. public enum ValidationResult { case success case failure(Error) } fileprivate struct MIMEType { let type: String let subtype: String var isWildcard: Bool { return type == "*" && subtype == "*" } init?(_ string: String) { let components: [String] = { let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] return split.components(separatedBy: "/") }() if let type = components.first, let subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(_ mime: MIMEType) -> Bool { switch (type, subtype) { case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): return true default: return false } } } // MARK: Properties fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } fileprivate var acceptableContentTypes: [String] { if let accept = request?.value(forHTTPHeaderField: "Accept") { return accept.components(separatedBy: ",") } return ["*/*"] } // MARK: Status Code fileprivate func validate<S: Sequence>( statusCode acceptableStatusCodes: S, response: HTTPURLResponse) -> ValidationResult where S.Iterator.Element == Int { if acceptableStatusCodes.contains(response.statusCode) { return .success } else { let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) return .failure(AFError.responseValidationFailed(reason: reason)) } } // MARK: Content Type fileprivate func validate<S: Sequence>( contentType acceptableContentTypes: S, response: HTTPURLResponse, data: Data?) -> ValidationResult where S.Iterator.Element == String { guard let data = data, data.count > 0 else { return .success } guard let responseContentType = response.mimeType, let responseMIMEType = MIMEType(responseContentType) else { for contentType in acceptableContentTypes { if let mimeType = MIMEType(contentType), mimeType.isWildcard { return .success } } let error: AFError = { let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) return AFError.responseValidationFailed(reason: reason) }() return .failure(error) } for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { return .success } } let error: AFError = { let reason: ErrorReason = .unacceptableContentType( acceptableContentTypes: Array(acceptableContentTypes), responseContentType: responseContentType ) return AFError.responseValidationFailed(reason: reason) }() return .failure(error) } } // MARK: - extension DataRequest { /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the /// request was valid. public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(self.request, response, self.delegate.data) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, data in return self.validate(contentType: acceptableContentTypes, response: response, data: data) } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult public func validate() -> Self { return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) } } // MARK: - extension DownloadRequest { /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a /// destination URL, and returns whether the request was valid. public typealias Validation = ( _ request: URLRequest?, _ response: HTTPURLResponse, _ temporaryURL: URL?, _ destinationURL: URL?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in let request = self.request let temporaryURL = self.downloadDelegate.temporaryURL let destinationURL = self.downloadDelegate.destinationURL if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(request, response, temporaryURL, destinationURL) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, _, _ in let fileURL = self.downloadDelegate.fileURL guard let validFileURL = fileURL else { return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) } do { let data = try Data(contentsOf: validFileURL) return self.validate(contentType: acceptableContentTypes, response: response, data: data) } catch { return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) } } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult public func validate() -> Self { return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) } }
mit
34d80749ddee24b677480cfafdb5955f
36.514563
121
0.636215
5.28591
false
false
false
false
vvusu/LogAnalysis
Log Analysis/Libraries/SUSheetXLS/SUWorkSheet.swift
1
768
// // SUWorkSheet.swift // Log Analysis // // Created by vvusu on 10/30/15. // Copyright © 2015 vvusu. All rights reserved. // import Cocoa class SUWorkSheet: NSObject { var name: String! var rowHeight: Float var columnWidth: Float var arrayWorkSheetRow: Array<SUWorkSheetRow> override init() { name = "sheet" columnWidth = 100 rowHeight = 20 arrayWorkSheetRow = [SUWorkSheetRow]() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(nameSheet: String) { self.init() name = nameSheet } func addWorkSheetRow(row: SUWorkSheetRow) { arrayWorkSheetRow.append(row) } }
lgpl-3.0
34e6fb46b2efa6be449089798adc70e1
19.184211
59
0.611473
3.854271
false
false
false
false
APPSeed/DataTransfer
DataTransfer/Vender/TCBlobDownload/TCBlobDownload.swift
1
3136
// // TCBlobDownload.swift // TCBlobDownloadSwift // // Created by Thibault Charbonnier on 30/12/14. // Copyright (c) 2014 thibaultcha. All rights reserved. // import Foundation public class TCBlobDownload { // The underlaying session download task public let downloadTask: NSURLSessionDownloadTask // An optional delegate to get notified of events weak var delegate: TCBlobDownloadDelegate? // An optional file name set by the user. private let preferedFileName: String? // An optional destination path for the file. If nil, the file will be downloaded in the current user temporary directory private let directory: NSURL? // If the downloaded file couldn't be moved to its final destination, will contain the error var error: NSError? // Current pgoress of the download, a value between 0 and 1 public var progress: Float = 0 // If the final copy of the file was successful, will contain the URL to the final file public var resultingURL: NSURL? // A computed property to get the filename of the downloaded file public var fileName: String? { return self.preferedFileName ?? self.downloadTask.response?.suggestedFilename } // A computed destinationURL depending on the destinationPath, fileName, and suggestedFileName from the underlying NSURLResponse public var destinationURL: NSURL { let destinationPath = self.directory ?? NSURL(fileURLWithPath: NSTemporaryDirectory()) return NSURL(string: self.fileName!, relativeToURL: destinationPath!)!.URLByStandardizingPath! } // Initialize a new download assuming the NSURLSessionDownloadTask is already created init(downloadTask: NSURLSessionDownloadTask, toDirectory directory: NSURL?, fileName: String?, delegate: TCBlobDownloadDelegate?) { self.downloadTask = downloadTask self.directory = directory self.preferedFileName = fileName self.delegate = delegate } public func cancel() { self.downloadTask.cancel() } public func suspend() { self.downloadTask.suspend() } public func resume() { self.downloadTask.resume() } public func cancelWithResumeData(completionHandler: (NSData!) -> Void) { self.downloadTask.cancelByProducingResumeData(completionHandler) } // TODO: closures // TODO: remaining time } // MARK: - Printable extension TCBlobDownload: Printable { public var description: String { var parts: [String] = [] var state: String switch self.downloadTask.state { case .Running: state = "running" case .Completed: state = "completed" case .Canceling: state = "canceling" case .Suspended: state = "suspended" } parts.append("TCBlobDownload") parts.append("URL: \(self.downloadTask.originalRequest.URL)") parts.append("Download task state: \(state)") parts.append("destinationPath: \(self.directory)") parts.append("fileName: \(self.fileName)") return join(" | ", parts) } }
mit
7cb7636c080e462bdd5765e617c82a42
32.010526
135
0.681122
4.892356
false
false
false
false
SergeMaslyakov/audio-player
app/src/services/apple-music/AppleMusicArtistsDataService.swift
1
1354
// // AppleMusicArtistsDataService.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright © 2017 Maslyakov. All rights reserved. // import UIKit import MediaPlayer class AppleMusicArtistsDataService: Loggable { func loadAsync(with completion: @escaping ([(albums: Int, songs: MPMediaItemCollection)]) -> Void) { DispatchQueue.global(qos: .userInitiated).async { let artists: [MPMediaItemCollection]? = MPMediaQuery.artists().collections var filtered: [(Int, MPMediaItemCollection)] = [] if let artists = artists { for artist in artists { let artistFilter = MPMediaPropertyPredicate(value: artist.representativeItem?.artist, forProperty: MPMediaItemPropertyArtist, comparisonType: MPMediaPredicateComparison.equalTo) let query = MPMediaQuery(filterPredicates: [artistFilter]) query.groupingType = MPMediaGrouping.album if let collection = query.collections { filtered.append((collection.count, artist)) } else { filtered.append((0, artist)) } } } DispatchQueue.main.async { completion(filtered) } } } }
apache-2.0
d9597cc40be112b5f10b1bfcb8774016
32.825
197
0.594974
5.244186
false
false
false
false
xiaoyouPrince/DYLive
DYLive/DYLive/Classes/Home/ViewModel/RecommendViewModel.swift
1
5357
// // RecommendViewModel.swift // DYLive // // Created by 渠晓友 on 2017/4/18. // Copyright © 2017年 xiaoyouPrince. All rights reserved. // /* 1> 请求0/1数组,并转成模型对象 2> 对数据进行排序 3> 显示的HeaderView中内容 */ import UIKit class RecommendViewModel : BaseViewModel { // MARK: - 懒加载对应的Model fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup() fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup() lazy var cycleModels : [CycleModel] = [CycleModel]() } // MARK: - 请求推荐页面数据 extension RecommendViewModel{ // MARK: - 请求推荐数据 func requestData(_ finishCallBcak : @escaping() -> ()) { // 0.封装请求参数 let params = ["limit":"4" , "offset":"0" , "time": Date.getCurrentTime() as NSString] // 0.1 创建队列 let dGroup = DispatchGroup() // 1. 请求第1部分 热门推荐 dGroup.enter() NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : Date.getCurrentTime() as NSString]) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.1 设置组属性 self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" // 3.2.获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } // 请求完成离开队列 dGroup.leave() } // 2. 请求第2部分 颜值数据 dGroup.enter() NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: params) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.1 设置组属性 self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" // 3.2.获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } // 请求完成离开队列 dGroup.leave() } // 3. 请求第3部分 游戏数据 dGroup.enter() // NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: params) { (result) in // // // 处理对应的result // print(result) // // // 1. 先将result转成字典 // guard let resultDict = result as? [String : NSObject] else { return } // // // 2. 根据data的key取出数组 // guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // // // 3.遍历数组,获取字典,根据字典转化成model对象 // for dict in dataArray{ // // let group = AnchorGroup(dict: dict) // self.anchorGroups.append(group) // // } // // // 请求完成离开队列 // dGroup.leave() // // } loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: params) { // 请求完成离开队列 dGroup.leave() } // 4.数据请求完成之后dispatch回调 dGroup.notify(queue: DispatchQueue.main){ self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) print(self.anchorGroups) finishCallBcak() } } // MARK: - 请求轮播数据 func requestCycleData(_ finishCallBcak : @escaping() -> ()) { NetworkTools.requestData(type: .GET, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in // 1.获取整体字典数据 guard let resultDict = result as? [String : NSObject] else{ return } // 2.根据对应的data的key获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else{ return } // 3.字典转模型 for dict in dataArray{ self.cycleModels.append(CycleModel(dict: dict)) } finishCallBcak() //请求完成的回调 } } }
mit
307bcbd216a6f49849fe4a1120d0a4de
29.490566
176
0.502682
4.395286
false
false
false
false
xedin/swift
stdlib/public/core/Diffing.swift
2
27173
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2015 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // MARK: Diff application to RangeReplaceableCollection @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) // FIXME(availability-5.1) extension CollectionDifference { fileprivate func _fastEnumeratedApply( _ consume: (Change) -> Void ) { let totalRemoves = removals.count let totalInserts = insertions.count var enumeratedRemoves = 0 var enumeratedInserts = 0 while enumeratedRemoves < totalRemoves || enumeratedInserts < totalInserts { let change: Change if enumeratedRemoves < removals.count && enumeratedInserts < insertions.count { let removeOffset = removals[enumeratedRemoves]._offset let insertOffset = insertions[enumeratedInserts]._offset if removeOffset - enumeratedRemoves <= insertOffset - enumeratedInserts { change = removals[enumeratedRemoves] } else { change = insertions[enumeratedInserts] } } else if enumeratedRemoves < totalRemoves { change = removals[enumeratedRemoves] } else if enumeratedInserts < totalInserts { change = insertions[enumeratedInserts] } else { // Not reached, loop should have exited. preconditionFailure() } consume(change) switch change { case .remove(_, _, _): enumeratedRemoves += 1 case .insert(_, _, _): enumeratedInserts += 1 } } } } extension RangeReplaceableCollection { /// Applies the given difference to this collection. /// /// - Parameter difference: The difference to be applied. /// /// - Returns: An instance representing the state of the receiver with the /// difference applied, or `nil` if the difference is incompatible with /// the receiver's state. /// /// - Complexity: O(*n* + *c*), where *n* is `self.count` and *c* is the /// number of changes contained by the parameter. @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) // FIXME(availability-5.1) public func applying(_ difference: CollectionDifference<Element>) -> Self? { var result = Self() var enumeratedRemoves = 0 var enumeratedInserts = 0 var enumeratedOriginals = 0 var currentIndex = self.startIndex func append( into target: inout Self, contentsOf source: Self, from index: inout Self.Index, count: Int ) { let start = index source.formIndex(&index, offsetBy: count) target.append(contentsOf: source[start..<index]) } difference._fastEnumeratedApply { change in switch change { case .remove(offset: let offset, element: _, associatedWith: _): let origCount = offset - enumeratedOriginals append(into: &result, contentsOf: self, from: &currentIndex, count: origCount) enumeratedOriginals += origCount + 1 // Removal consumes an original element currentIndex = self.index(after: currentIndex) enumeratedRemoves += 1 case .insert(offset: let offset, element: let element, associatedWith: _): let origCount = (offset + enumeratedRemoves - enumeratedInserts) - enumeratedOriginals append(into: &result, contentsOf: self, from: &currentIndex, count: origCount) result.append(element) enumeratedOriginals += origCount enumeratedInserts += 1 } _internalInvariant(enumeratedOriginals <= self.count) } let origCount = self.count - enumeratedOriginals append(into: &result, contentsOf: self, from: &currentIndex, count: origCount) _internalInvariant(currentIndex == self.endIndex) _internalInvariant(enumeratedOriginals + origCount == self.count) _internalInvariant(result.count == self.count + enumeratedInserts - enumeratedRemoves) return result } } // MARK: Definition of API extension BidirectionalCollection { /// Returns the difference needed to produce this collection's ordered /// elements from the given collection, using the given predicate as an /// equivalence test. /// /// This function does not infer element moves. If you need to infer moves, /// call the `inferringMoves()` method on the resulting difference. /// /// - Parameters: /// - other: The base state. /// - areEquivalent: A closure that returns a Boolean value indicating /// whether two elements are equivalent. /// /// - Returns: The difference needed to produce the reciever's state from /// the parameter's state. /// /// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the /// count of this collection and *m* is `other.count`. You can expect /// faster execution when the collections share many common elements. @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) // FIXME(availability-5.1) public func difference<C: BidirectionalCollection>( from other: C, by areEquivalent: (Element, C.Element) -> Bool ) -> CollectionDifference<Element> where C.Element == Self.Element { var rawChanges: [CollectionDifference<Element>.Change] = [] let source = _CountingIndexCollection(other) let target = _CountingIndexCollection(self) let result = _CollectionChanges(from: source, to: target, by: areEquivalent) for change in result { switch change { case let .removed(r): for i in source.indices[r] { rawChanges.append( .remove( offset: i.offset!, element: source[i], associatedWith: nil)) } case let .inserted(r): for i in target.indices[r] { rawChanges.append( .insert( offset: i.offset!, element: target[i], associatedWith: nil)) } case .matched: break } } return CollectionDifference<Element>(_validatedChanges: rawChanges) } } extension BidirectionalCollection where Element : Equatable { /// Returns the difference needed to produce this collection's ordered /// elements from the given collection. /// /// This function does not infer element moves. If you need to infer moves, /// call the `inferringMoves()` method on the resulting difference. /// /// - Parameters: /// - other: The base state. /// /// - Returns: The difference needed to produce this collection's ordered /// elements from the given collection. /// /// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the /// count of this collection and *m* is `other.count`. You can expect /// faster execution when the collections share many common elements, or /// if `Element` conforms to `Hashable`. @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) // FIXME(availability-5.1) public func difference<C: BidirectionalCollection>( from other: C ) -> CollectionDifference<Element> where C.Element == Self.Element { return difference(from: other, by: ==) } } extension BidirectionalCollection { /// Returns a pair of subsequences containing the initial elements that /// `self` and `other` have in common. fileprivate func _commonPrefix<Other: BidirectionalCollection>( with other: Other, by areEquivalent: (Element, Other.Element) -> Bool ) -> (SubSequence, Other.SubSequence) where Element == Other.Element { let (s1, s2) = (startIndex, other.startIndex) let (e1, e2) = (endIndex, other.endIndex) var (i1, i2) = (s1, s2) while i1 != e1 && i2 != e2 { if !areEquivalent(self[i1], other[i2]) { break } formIndex(after: &i1) other.formIndex(after: &i2) } return (self[s1..<i1], other[s2..<i2]) } } // MARK: Diff production from OrderedCollection (soon to be BidirectionalCollection) /// A collection of changes between a source and target collection. /// /// It can be used to traverse the [longest common subsequence][lcs] of /// source and target: /// /// let changes = CollectionChanges(from: source, to target) /// for case let .match(s, t) in changes { /// // use `s`, `t` /// } /// /// It can also be used to traverse the [shortest edit script][ses] of /// remove and insert operations: /// /// let changes = CollectionChanges(from: source, to target) /// for c in changes { /// switch c { /// case let .removed(s): /// // use `s` /// case let .inserted(t): /// // use `t` /// case .matched: continue /// } /// } /// /// [lcs]: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem /// [ses]: http://en.wikipedia.org/wiki/Edit_distance /// /// - Note: `CollectionChanges` holds a reference to state used to run the /// difference algorithm, which can be exponentially larger than the /// changes themselves. fileprivate struct _CollectionChanges<SourceIndex, TargetIndex> where SourceIndex: Comparable, TargetIndex: Comparable { fileprivate typealias Endpoint = (x: SourceIndex, y: TargetIndex) /// An encoding of change elements as an array of index pairs stored in /// `pathStorage[pathStartIndex...]`. /// /// This encoding allows the same storage to be used to run the difference /// algorithm, report the result, and repeat in place using /// `formChanges`. /// /// The collection of changes between XABCD and XYCD is: /// /// [.match(0..<1, 0..<1), .remove(1..<3), .insert(1..<2), /// .match(3..<5, 2..<4)] /// /// Which gets encoded as: /// /// [(0, 0), (1, 1), (3, 1), (3, 2), (5, 4)] /// /// You can visualize it as a two-dimensional path composed of remove /// (horizontal), insert (vertical), and match (diagonal) segments: /// /// X A B C D /// X \ _ _ /// Y | /// C \ /// D \ /// private var pathStorage: [Endpoint] /// The index in `pathStorage` of the first segment in the difference path. private var pathStartIndex: Int /// Creates a collection of changes from a difference path. fileprivate init( pathStorage: [Endpoint], pathStartIndex: Int ) { self.pathStorage = pathStorage self.pathStartIndex = pathStartIndex } /// Creates an empty collection of changes, i.e. the changes between two /// empty collections. private init() { self.pathStorage = [] self.pathStartIndex = 0 } } extension _CollectionChanges { /// A range of elements removed from the source, inserted in the target, or /// that the source and target have in common. fileprivate enum Element { case removed(Range<SourceIndex>) case inserted(Range<TargetIndex>) case matched(Range<SourceIndex>, Range<TargetIndex>) } } extension _CollectionChanges: RandomAccessCollection { fileprivate typealias Index = Int fileprivate var startIndex: Index { return 0 } fileprivate var endIndex: Index { return Swift.max(0, pathStorage.endIndex - pathStartIndex - 1) } fileprivate func index(after i: Index) -> Index { return i + 1 } fileprivate subscript(position: Index) -> Element { _internalInvariant((startIndex..<endIndex).contains(position)) let current = pathStorage[position + pathStartIndex] let next = pathStorage[position + pathStartIndex + 1] if current.x != next.x && current.y != next.y { return .matched(current.x..<next.x, current.y..<next.y) } else if current.x != next.x { return .removed(current.x..<next.x) } else { // current.y != next.y return .inserted(current.y..<next.y) } } } extension _CollectionChanges: CustomStringConvertible { fileprivate var description: String { return _makeCollectionDescription() } } extension _CollectionChanges { /// Creates the collection of changes between `source` and `target`. /// /// - Runtime: O(*n* * *d*), where *n* is `source.count + target.count` and /// *d* is the minimal number of inserted and removed elements. /// - Space: O(*d* * *d*), where *d* is the minimal number of inserted and /// removed elements. fileprivate init<Source: BidirectionalCollection, Target: BidirectionalCollection>( from source: Source, to target: Target, by areEquivalent: (Source.Element, Target.Element) -> Bool ) where Source.Element == Target.Element, Source.Index == SourceIndex, Target.Index == TargetIndex { self.init() formChanges(from: source, to: target, by: areEquivalent) } /// Replaces `self` with the collection of changes between `source` /// and `target`. /// /// - Runtime: O(*n* * *d*), where *n* is `source.count + target.count` and /// *d* is the minimal number of inserted and removed elements. /// - Space: O(*d*²), where *d* is the minimal number of inserted and /// removed elements. private mutating func formChanges< Source: BidirectionalCollection, Target: BidirectionalCollection >( from source: Source, to target: Target, by areEquivalent: (Source.Element, Target.Element) -> Bool ) where Source.Element == Target.Element, Source.Index == SourceIndex, Target.Index == TargetIndex { let pathStart = (x: source.startIndex, y: target.startIndex) let pathEnd = (x: source.endIndex, y: target.endIndex) let matches = source._commonPrefix(with: target, by: areEquivalent) let (x, y) = (matches.0.endIndex, matches.1.endIndex) if pathStart == pathEnd { pathStorage.removeAll(keepingCapacity: true) pathStartIndex = 0 } else if x == pathEnd.x || y == pathEnd.y { pathStorage.removeAll(keepingCapacity: true) pathStorage.append(pathStart) if pathStart != (x, y) && pathEnd != (x, y) { pathStorage.append((x, y)) } pathStorage.append(pathEnd) pathStartIndex = 0 } else { formChangesCore(from: source, to: target, x: x, y: y, by: areEquivalent) } } /// The core difference algorithm. /// /// - Precondition: There is at least one difference between `a` and `b` /// - Runtime: O(*n* * *d*), where *n* is `a.count + b.count` and /// *d* is the number of inserts and removes. /// - Space: O(*d* * *d*), where *d* is the number of inserts and removes. private mutating func formChangesCore< Source: BidirectionalCollection, Target: BidirectionalCollection >( from a: Source, to b: Target, x: Source.Index, y: Target.Index, by areEquivalent: (Source.Element, Target.Element) -> Bool ) where Source.Element == Target.Element, Source.Index == SourceIndex, Target.Index == TargetIndex { // Written to correspond, as closely as possible, to the psuedocode in // Myers, E. "An O(ND) Difference Algorithm and Its Variations". // // See "FIGURE 2: The Greedy LCS/SES Algorithm" on p. 6 of the [paper]. // // Note the following differences from the psuedocode in FIGURE 2: // // 1. FIGURE 2 relies on both *A* and *B* being Arrays. In a generic // context, it isn't true that *y = x - k*, as *x*, *y*, *k* could // all be different types, so we store both *x* and *y* in *V*. // 2. FIGURE 2 only reports the length of the LCS/SES. Reporting a // solution path requires storing a copy of *V* (the search frontier) // after each iteration of the outer loop. // 3. FIGURE 2 stops the search after *MAX* iterations. We run the loop // until a solution is found. We also guard against incrementing past // the end of *A* and *B*, both to satisfy the termination condition // and because that would violate preconditions on collection. // // [paper]: http://www.xmailserver.org/diff2.pdf var (x, y) = (x, y) let (n, m) = (a.endIndex, b.endIndex) var v = _SearchState<Source.Index, Target.Index>(consuming: &pathStorage) v.appendFrontier(repeating: (x, y)) var d = 1 var delta = 0 outer: while true { v.appendFrontier(repeating: (n, m)) for k in stride(from: -d, through: d, by: 2) { if k == -d || (k != d && v[d - 1, k - 1].x < v[d - 1, k + 1].x) { (x, y) = v[d - 1, k + 1] if y != m { b.formIndex(after: &y) } } else { (x, y) = v[d - 1, k - 1] if x != n { a.formIndex(after: &x) } } let matches = a[x..<n]._commonPrefix(with: b[y..<m], by: areEquivalent) (x, y) = (matches.0.endIndex, matches.1.endIndex) v[d, k] = (x, y) if x == n && y == m { delta = k break outer } } d += 1 } self = v.removeCollectionChanges(a: a, b: b, d: d, delta: delta) } } /// The search paths being explored. fileprivate struct _SearchState< SourceIndex: Comparable, TargetIndex: Comparable > { fileprivate typealias Endpoint = (x: SourceIndex, y: TargetIndex) /// The search frontier for each iteration. /// /// The nth iteration of the core algorithm requires storing n + 1 search /// path endpoints. Thus, the shape of the storage required is a triangle. private var endpoints = _LowerTriangularMatrix<Endpoint>() /// Creates an instance, taking the capacity of `storage` for itself. /// /// - Postcondition: `storage` is empty. fileprivate init(consuming storage: inout [Endpoint]) { storage.removeAll(keepingCapacity: true) swap(&storage, &endpoints.storage) } /// Returns the endpoint of the search frontier for iteration `d` on /// diagonal `k`. fileprivate subscript(d: Int, k: Int) -> Endpoint { get { _internalInvariant((-d...d).contains(k)) _internalInvariant((d + k) % 2 == 0) return endpoints[d, (d + k) / 2] } set { _internalInvariant((-d...d).contains(k)) _internalInvariant((d + k) % 2 == 0) endpoints[d, (d + k) / 2] = newValue } } /// Adds endpoints initialized to `repeatedValue` for the search frontier of /// the next iteration. fileprivate mutating func appendFrontier(repeating repeatedValue: Endpoint) { endpoints.appendRow(repeating: repeatedValue) } } extension _SearchState { /// Removes and returns `_CollectionChanges`, leaving `_SearchState` empty. /// /// - Precondition: There is at least one difference between `a` and `b` fileprivate mutating func removeCollectionChanges< Source: BidirectionalCollection, Target: BidirectionalCollection >( a: Source, b: Target, d: Int, delta: Int ) -> _CollectionChanges<Source.Index, Target.Index> where Source.Index == SourceIndex, Target.Index == TargetIndex { // Calculating the difference path is very similar to running the core // algorithm in reverse: // // var k = delta // for d in (1...d).reversed() { // if k == -d || (k != d && self[d - 1, k - 1].x < self[d - 1, k + 1].x) { // // insert of self[d - 1, k + 1].y // k += 1 // } else { // // remove of self[d - 1, k - 1].x // k -= 1 // } // } // // It is more complicated below because: // // 1. We want to include segments for matches // 2. We want to coallesce consecutive like segments // 3. We don't want to allocate, so we're overwriting the elements of // endpoints.storage we've finished reading. let pathStart = (a.startIndex, b.startIndex) let pathEnd = (a.endIndex, b.endIndex) // `endpoints.storage` may need space for an additional element in order // to store the difference path when `d == 1`. // // `endpoints.storage` has `(d + 1) * (d + 2) / 2` elements stored, // but a difference path requires up to `2 + d * 2` elements[^1]. // // If `d == 1`: // // (1 + 1) * (1 + 2) / 2 < 2 + 1 * 2 // 3 < 4 // // `d == 1` is the only special case because: // // - It's a precondition that `d > 0`. // - Once `d >= 2` `endpoints.storage` will have sufficient space: // // (d + 1) * (d + 2) / 2 = 2 + d * 2 // d * d - d - 2 = 0 // (d - 2) * (d + 1) = 0 // d = 2; d = -1 // // [1]: An endpoint for every remove, insert, and match segment. (Recall // *d* is the minimal number of inserted and removed elements). If there // are no consecutive removes or inserts and every remove or insert is // sandwiched between matches, the path will need `2 + d * 2` elements. _internalInvariant(d > 0, "Must be at least one difference between `a` and `b`") if d == 1 { endpoints.storage.append(pathEnd) } var i = endpoints.storage.endIndex - 1 // `isInsertion` tracks whether the element at `endpoints.storage[i]` // is an insertion (`true`), a removal (`false`), or a match (`nil`). var isInsertion: Bool? = nil var k = delta endpoints.storage[i] = pathEnd for d in (1...d).reversed() { if k == -d || (k != d && self[d - 1, k - 1].x < self[d - 1, k + 1].x) { let (x, y) = self[d - 1, k + 1] // There was match before this insert, so add a segment. if x != endpoints.storage[i].x { i -= 1; endpoints.storage[i] = (x, b.index(after: y)) isInsertion = nil } // If the previous segment is also an insert, overwrite it. if isInsertion != .some(true) { i -= 1 } endpoints.storage[i] = (x, y) isInsertion = true k += 1 } else { let (x, y) = self[d - 1, k - 1] // There was a match before this remove, so add a segment. if y != endpoints.storage[i].y { i -= 1; endpoints.storage[i] = (a.index(after: x), y) isInsertion = nil } // If the previous segment is also a remove, overwrite it. if isInsertion != .some(false) { i -= 1 } endpoints.storage[i] = (x, y) isInsertion = false k -= 1 } } if pathStart != endpoints.storage[i] { i -= 1; endpoints.storage[i] = pathStart } let pathStorage = endpoints.storage endpoints.storage = [] return _CollectionChanges(pathStorage: pathStorage, pathStartIndex: i) } } /// An index that counts its offset from the start of its collection. private struct _CountingIndex<Base: Comparable>: Equatable { /// The position in the underlying collection. let base: Base /// The offset from the start index of the collection or `nil` if `self` is /// the end index. let offset: Int? } extension _CountingIndex: Comparable { fileprivate static func <(lhs: _CountingIndex, rhs: _CountingIndex) -> Bool { return (lhs.base, lhs.offset ?? Int.max) < (rhs.base, rhs.offset ?? Int.max) } } /// A collection that counts the offset of its indices from its start index. /// /// You can use `_CountingIndexCollection` with algorithms on `Collection` to /// calculate offsets of significance: /// /// if let i = _CountingIndexCollection("Café").index(of: "f") { /// print(i.offset) /// } /// // Prints "2" /// /// - Note: The offset of `endIndex` is `nil` private struct _CountingIndexCollection<Base: BidirectionalCollection> { private let base: Base fileprivate init(_ base: Base) { self.base = base } } extension _CountingIndexCollection : BidirectionalCollection { fileprivate typealias Index = _CountingIndex<Base.Index> fileprivate typealias Element = Base.Element fileprivate var startIndex: Index { return Index(base: base.startIndex, offset: base.isEmpty ? nil : 0) } fileprivate var endIndex: Index { return Index(base: base.endIndex, offset: nil) } fileprivate func index(after i: Index) -> Index { let next = base.index(after: i.base) return Index( base: next, offset: next == base.endIndex ? nil : i.offset! + 1) } fileprivate func index(before i: Index) -> Index { let prev = base.index(before: i.base) return Index( base: prev, offset: prev == base.endIndex ? nil : i.offset! + 1) } fileprivate subscript(position: Index) -> Element { return base[position.base] } } /// Returns the nth [triangular number]. /// /// [triangular number]: https://en.wikipedia.org/wiki/Triangular_number fileprivate func _triangularNumber(_ n: Int) -> Int { return n * (n + 1) / 2 } /// A square matrix that only provides subscript access to elements on, or /// below, the main diagonal. /// /// A [lower triangular matrix] can be dynamically grown: /// /// var m = _LowerTriangularMatrix<Int>() /// m.appendRow(repeating: 1) /// m.appendRow(repeating: 2) /// m.appendRow(repeating: 3) /// /// assert(Array(m.rowMajorOrder) == [ /// 1, /// 2, 2, /// 3, 3, 3, /// ]) /// /// [lower triangular matrix]: http://en.wikipedia.org/wiki/Triangular_matrix fileprivate struct _LowerTriangularMatrix<Element> { /// The matrix elements stored in [row major order][rmo]. /// /// [rmo]: http://en.wikipedia.org/wiki/Row-_and_column-major_order fileprivate var storage: [Element] = [] /// The dimension of the matrix. /// /// Being a square matrix, the number of rows and columns are equal. fileprivate var dimension: Int = 0 fileprivate subscript(row: Int, column: Int) -> Element { get { _internalInvariant((0...row).contains(column)) return storage[_triangularNumber(row) + column] } set { _internalInvariant((0...row).contains(column)) storage[_triangularNumber(row) + column] = newValue } } fileprivate mutating func appendRow(repeating repeatedValue: Element) { dimension += 1 storage.append(contentsOf: repeatElement(repeatedValue, count: dimension)) } } extension _LowerTriangularMatrix { /// A collection that visits the elements in the matrix in [row major /// order][rmo]. /// /// [rmo]: http://en.wikipedia.org/wiki/Row-_and_column-major_order fileprivate struct RowMajorOrder : RandomAccessCollection { private var base: _LowerTriangularMatrix fileprivate init(base: _LowerTriangularMatrix) { self.base = base } fileprivate var startIndex: Int { return base.storage.startIndex } fileprivate var endIndex: Int { return base.storage.endIndex } fileprivate func index(after i: Int) -> Int { return i + 1 } fileprivate func index(before i: Int) -> Int { return i - 1 } fileprivate subscript(position: Int) -> Element { return base.storage[position] } } fileprivate var rowMajorOrder: RowMajorOrder { return RowMajorOrder(base: self) } fileprivate subscript(row r: Int) -> Slice<RowMajorOrder> { return rowMajorOrder[_triangularNumber(r)..<_triangularNumber(r + 1)] } } extension _LowerTriangularMatrix: CustomStringConvertible { fileprivate var description: String { var rows: [[Element]] = [] for row in 0..<dimension { rows.append(Array(self[row: row])) } return String(describing: rows) } }
apache-2.0
19f1092d85b5b5bb30847d9de24a2d83
32.710918
94
0.631114
3.905001
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/WindowLevelSelectionTableViewCell.swift
3
1394
// // WindowLevelTableViewCell.swift // SwiftEntryKit_Example // // Created by Daniel Huri on 4/24/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit class WindowLevelSelectionTableViewCell: SelectionTableViewCell { override func configure(attributesWrapper: EntryAttributeWrapper) { super.configure(attributesWrapper: attributesWrapper) titleValue = "Window Level" descriptionValue = "Where the entry should be displayed in the application window hierarchy" insertSegments(by: ["Normal", "Status Bar", "Alerts"]) selectSegment() } private func selectSegment() { switch attributesWrapper.attributes.windowLevel { case .normal: segmentedControl.selectedSegmentIndex = 0 case .statusBar: segmentedControl.selectedSegmentIndex = 1 case .alerts: segmentedControl.selectedSegmentIndex = 2 default: break } } @objc override func segmentChanged() { switch segmentedControl.selectedSegmentIndex { case 0: attributesWrapper.attributes.windowLevel = .normal case 1: attributesWrapper.attributes.windowLevel = .statusBar case 2: attributesWrapper.attributes.windowLevel = .alerts default: break } } }
apache-2.0
59c27f466114fff50c8a9f2926e11a1d
29.304348
100
0.649211
5.30038
false
false
false
false
kedu/FULL_COPY
xingLangWeiBo/xingLangWeiBo/Classes/Modeul/Base/BaseTableViewController.swift
1
2391
// // BaseTableViewController.swift // xingLangWeiBo // // Created by Apple on 16/10/8. // Copyright © 2016年 lkb-求工作qq:1218773641. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController,VistorLoginViewDelegate { //loadview专门为手写代码 等效于 sb 与 xib //一旦实现 xib和sb 自动失败 //添加用户是否登录 var userLogin = userAccountViewModel().useLogin var vistorLoginView:VistorLoginView? func userLogin_kvo(){ } override func loadView() { userLogin ? super.loadView() : loadVisterVier() } func vistorWillLogin() { print("登录") let Oauth2vc=Oauth2ViewController() let nav=UINavigationController(rootViewController: Oauth2vc) presentViewController(nav, animated: true) { () -> Void in print("进入登录页面") } } func visitorWillRegister() { print("注册") } private func loadVisterVier(){ vistorLoginView = VistorLoginView() vistorLoginView?.visitorDelegate=self view = vistorLoginView self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "登录", style: .Plain, target: self, action: "vistorWillLogin") self.navigationItem.leftBarButtonItem=UIBarButtonItem(title: "注册", style: .Plain, target: self, action: "visitorWillRegister") } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } }
mit
b3a1251fdc8eeb87a0e0e6eec636f165
30.479452
134
0.67624
4.757764
false
false
false
false
StartAppsPe/StartAppsKitLoadAction
Sources/LoadActionViewDelegates.swift
1
6641
// // LoadActionViewDelegates.swift // Pods // // Created by Gabriel Lanata on 11/30/15. // // #if os(iOS) import UIKit import StartAppsKitExtensions extension UIActivityIndicatorView: LoadActionDelegate { public func loadActionUpdated<L: LoadActionType>(loadAction: L, updatedProperties: Set<LoadActionProperties>) { guard updatedProperties.contains(.status) else { return } switch loadAction.status { case .loading: self.startAnimating() case .ready: self.stopAnimating() } } public var loadingStatus: LoadingStatus { get { return (isAnimating ? .loading : .ready) } set { self.active = (newValue == .loading) } } } extension UIRefreshControl { public convenience init(loadAction: LoadActionLoadableType) { self.init() setAction(loadAction: loadAction) loadAction.addDelegate(self) } public func setAction(loadAction: LoadActionLoadableType) { setAction(controlEvents: .valueChanged, loadAction: loadAction) } public var loadingStatus: LoadingStatus { get { return (isRefreshing ? .loading : .ready) } set { self.active = (newValue == .loading) } } } extension UIControl { public func setAction(controlEvents: UIControlEvents, loadAction: LoadActionLoadableType) { setAction(controlEvents: controlEvents) { (sender) in loadAction.loadNew(completion: nil) } } } extension UIControl: LoadActionDelegate { public func loadActionUpdated<L: LoadActionType>(loadAction: L, updatedProperties: Set<LoadActionProperties>) { guard updatedProperties.contains(.status) || updatedProperties.contains(.error) else { return } switch loadAction.status { case .loading: isEnabled = false isUserInteractionEnabled = false if let selfButton = self as? UIButton { selfButton.activityIndicatorView?.startAnimating() selfButton.tempTitle = "" } if let selfRefreshControl = self as? UIRefreshControl { selfRefreshControl.active = true } case .ready: isEnabled = true isUserInteractionEnabled = true if let selfButton = self as? UIButton { selfButton.activityIndicatorView?.stopAnimating() selfButton.activityIndicatorView = nil if loadAction.error != nil { selfButton.tempTitle = selfButton.errorTitle } else { selfButton.tempTitle = nil } } if let selfRefreshControl = self as? UIRefreshControl { selfRefreshControl.active = false } } } } private var _rcak: UInt8 = 1 public extension UIScrollView { public var refreshControlCompat: UIRefreshControl? { get { if #available(iOS 10.0, *) { return refreshControl } else { return objc_getAssociatedObject(self, &_rcak) as? UIRefreshControl } } set { if #available(iOS 10.0, *) { refreshControl = newValue } else { objc_setAssociatedObject(self, &_rcak, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } if let newValue = newValue { alwaysBounceVertical = true addSubview(newValue) } } } } extension UIScrollView: LoadActionDelegate { public func loadActionUpdated<L: LoadActionType>(loadAction: L, updatedProperties: Set<LoadActionProperties>) { if #available(iOS 10.0, *) { refreshControl?.loadActionUpdated(loadAction: loadAction, updatedProperties: updatedProperties) } else { refreshControlCompat?.loadActionUpdated(loadAction: loadAction, updatedProperties: updatedProperties) } if let tableView = self as? UITableView { tableView.displayStateView.loadActionUpdated(loadAction: loadAction, updatedProperties: updatedProperties) tableView.tempSeparatorStyle = (loadAction.value != nil ? nil : .none) tableView.reloadData() } if let collectionView = self as? UICollectionView { collectionView.displayStateView.loadActionUpdated(loadAction: loadAction, updatedProperties: updatedProperties) collectionView.reloadData() } } } private var _sdkh: UInt8 = 0 extension UITableView { private var _storedSeparatorStyle: UITableViewCellSeparatorStyle? { get { guard let rawValue = objc_getAssociatedObject(self, &_sdkh) as? Int else { return nil } return UITableViewCellSeparatorStyle(rawValue: rawValue) } set { objc_setAssociatedObject(self, &_sdkh, newValue?.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } public var tempSeparatorStyle: UITableViewCellSeparatorStyle? { get { if _storedSeparatorStyle == nil { return nil } return separatorStyle } set { if newValue == UITableViewCellSeparatorStyle.none { if _storedSeparatorStyle == nil { _storedSeparatorStyle = separatorStyle } separatorStyle = UITableViewCellSeparatorStyle.none } else if newValue == UITableViewCellSeparatorStyle.singleLineEtched { if _storedSeparatorStyle == nil { _storedSeparatorStyle = separatorStyle } separatorStyle = UITableViewCellSeparatorStyle.singleLineEtched } else if let storedSeparatorStyle = _storedSeparatorStyle { separatorStyle = storedSeparatorStyle _storedSeparatorStyle = nil } } } } #endif
mit
88f5ee557033bb163c345980d33b62c1
36.100559
127
0.554133
5.999097
false
false
false
false
RyanTech/Tuan
Tuan/Deal/HMSortsViewController.swift
8
3016
// // HMSortsViewController.swift // Tuan // // Created by nero on 15/5/15. // Copyright (c) 2015年 nero. All rights reserved. // import UIKit class HMSortButton:UIButton { var sort:HMSort = HMSort() { willSet { self.title = newValue.label } } override init(frame: CGRect) { super.init(frame: frame) self.bgImage = "btn_filter_normal" self.selectedBgImage = "btn_filter_selected" self.titleColor = UIColor.blackColor() self.selectedTitleColor = UIColor.whiteColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class HMSortsViewController: UIViewController { var seletedButton:HMSortButton? override func viewDidLoad() { super.viewDidLoad() // 设置在popover中的尺寸 self.preferredContentSize = self.view.size; // 根据排序模型的个数,创建对应的按钮 var buttonX:CGFloat = 20.0 var buttonW = view.width - 2 * buttonX var buttonP:CGFloat = 15 var sorts = HMMetaDataTool.sharedMetaDataTool().sorts as! Array<HMSort> var contentH:CGFloat = 0 for i in 0 ..< sorts.count { // 创建按钮 var button = HMSortButton(frame: CGRectZero) // 取出模型 button.sort = sorts[i] // 设置尺寸 button.x = buttonX button.width = buttonW button.height = 30 button.y = buttonP + CGFloat(i) * ( button.height + buttonP) button.addTarget(self, action: Selector("sortButtonClick:"), forControlEvents: UIControlEvents.TouchDown) view.addSubview(button) contentH = button.maxX + buttonP } // // 设置contentSize var scrollview = self.view as! UIScrollView scrollview.contentSize = CGSize(width: 0, height: contentH) } func sortButtonClick(button:HMSortButton) { self.seletedButton?.selected = false button.selected = true self.seletedButton = button // 2.发出通知 HMNotificationCenter.postNotificationName(HMSortNotification.HMSortDidSelectNotification, object: nil, userInfo: [HMSortNotification.HMSelectedSort:button.sort]) } /** 当前选中的排序 */ // @property (strong, nonatomic) HMSort *selectedSort; var selectedSort:HMSort! { willSet { // if newValue == nil {return } var subview = self.view.subviews as! [UIView] for button in subview{ if let sortButton = button as? HMSortButton { if sortButton.sort == newValue { seletedButton?.selected = false sortButton.selected = true seletedButton = sortButton } } } } } }
mit
c109027c8beeead4e4bcb276225e03f4
28.454545
169
0.570645
4.506955
false
false
false
false
phimage/Prephirences
Sources/PatternPreferences.swift
1
20283
// // PatternPreferences.swift // Prephirences /* The MIT License (MIT) Copyright (c) 2017 Eric Marchand (phimage) 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 // MARK: composite pattern /// A `PreferencesType` which could agregate multiple `PreferencesType`. /// The first `PreferencesType` which defined a key, will return its value. open class CompositePreferences: ExpressibleByArrayLiteral { var _array: [PreferencesType] = [] /// Array of `PreferencesType`. public var array: [PreferencesType] { return _array } // MARK: singleton /// Shared instance. static let sharedInstance = CompositePreferences([]) // MARK: init /// Initialize using an array of `PreferencesType`. public init(_ array: [PreferencesType]) { self._array = array } // MARK: ArrayLiteralConvertible public typealias Element = PreferencesType public convenience required init(arrayLiteral elements: Element...) { self.init([]) for element in elements { self._array.append(element) } } open subscript(key: PreferenceKey) -> PreferenceObject? { // first return win for prefs in _array { if let value = prefs.object(forKey: key) { return value } } return nil } } // MARK: PreferencesType extension CompositePreferences: PreferencesType { open func object(forKey key: PreferenceKey) -> PreferenceObject? { return self[key] } open func hasObject(forKey key: PreferenceKey) -> Bool { return self[key] != nil } open func string(forKey key: PreferenceKey) -> String? { return self[key] as? String } open func array(forKey key: PreferenceKey) -> [PreferenceObject]? { return self[key] as? [AnyObject] } open func dictionary(forKey key: PreferenceKey) -> PreferencesDictionary? { return self[key] as? PreferencesDictionary } open func data(forKey key: PreferenceKey) -> Data? { return self[key] as? Data } open func stringArray(forKey key: PreferenceKey) -> [String]? { return self.array(forKey: key) as? [String] } open func integer(forKey key: PreferenceKey) -> Int { return self[key] as? Int ?? 0 } open func float(forKey key: PreferenceKey) -> Float { return self[key] as? Float ?? 0 } open func double(forKey key: PreferenceKey) -> Double { return self[key] as? Double ?? 0 } open func bool(forKey key: PreferenceKey) -> Bool { if let b = self[key] as? Bool { return b } return false } open func url(forKey key: PreferenceKey) -> URL? { return self[key] as? URL } open func dictionary() -> PreferencesDictionary { var dico = PreferencesDictionary() for prefs in _array.reversed() { dico += prefs.dictionary() } return dico } } extension CompositePreferences { /// Return only `MutablePreferencesType`. public var mutableArray: [PreferencesType] { return self._array.filter { $0 is MutablePreferencesType } } /// Return only `PreferencesType` which is not `MutablePreferencesType`. public var immutableArray: [PreferencesType] { return self._array.filter { !($0 is MutablePreferencesType) } } /// Return the first `PreferencesType` which define the value for a specific key. /// /// - parameter key: the key to check. /// /// - returns: The `PreferencesType` that we seek. open func preferences(with key: PreferenceKey) -> PreferencesType? { // the first return win for prefs in _array { if prefs.hasObject(forKey: key) { return prefs } } return nil } /// Return the first `MutablePreferencesType` which define the value for a specific key. /// /// - parameter key: the key to check. /// /// - returns: The `MutablePreferencesType` that we seek. open func mutablePreferences(with key: PreferenceKey) -> MutablePreferencesType? { // the first return win for prefs in _array { if let mutablePrefs = prefs as? MutablePreferencesType, prefs.hasObject(forKey: key) { return mutablePrefs } } return nil } } /// A `MutablePreferencesType` which could agregate multiple `PreferencesType`. /// The first `PreferencesType` which defined a key, will return its value. /// The first `MutablePreferencesType` will be affected when setting value if `affectOnlyFirstMutable` is `true`, /// else all `MutablePreferencesType` open class MutableCompositePreferences: CompositePreferences, MutablePreferencesType { /// A boolean which defined if only the first `MutablePreferencesType` will be affected when setting a new value. open var affectOnlyFirstMutable: Bool /// Initialize using an array of `PreferencesType`. public override convenience init(_ array: [PreferencesType]) { self.init(array, affectOnlyFirstMutable: true) } /// Initialize using an array of `PreferencesType` and choose `affectOnlyFirstMutable` value. public init(_ array: [PreferencesType], affectOnlyFirstMutable: Bool) { self.affectOnlyFirstMutable = affectOnlyFirstMutable super.init(array) } override open subscript(key: PreferenceKey) -> PreferenceObject? { get { // first return win for prefs in _array { if let value = prefs.object(forKey: key) { return value } } return nil } set { for prefs in _array { if let mutablePrefs = prefs as? MutablePreferencesType { mutablePrefs.set(newValue, forKey: key) if affectOnlyFirstMutable { break } } } } } open func set(_ value: PreferenceObject?, forKey key: PreferenceKey) { self[key] = value } open func removeObject(forKey key: PreferenceKey) { self[key] = nil } open func set(_ value: Int, forKey key: PreferenceKey) { self[key] = value } open func set(_ value: Float, forKey key: PreferenceKey) { self[key] = value } open func set(_ value: Double, forKey key: PreferenceKey) { self[key] = value } open func set(_ value: Bool, forKey key: PreferenceKey) { self[key] = value } open func set(_ url: URL?, forKey key: PreferenceKey) { self[key] = url } open func set(dictionary: PreferencesDictionary) { for prefs in _array { if let mutablePrefs = prefs as? MutablePreferencesType { mutablePrefs.set(dictionary: dictionary) if affectOnlyFirstMutable { break } } } } open func clearAll() { for prefs in _array { if let mutablePrefs = prefs as? MutablePreferencesType { mutablePrefs.clearAll() } } } } // MARK: proxy pattern /// A `PreferencesType` proxy of another `PreferencesType`. open class ProxyPreferences { fileprivate let proxiable: PreferencesType fileprivate let parentKey: String var separator: String? /// Create a proxy with same key and values. public convenience init(preferences proxiable: PreferencesType) { self.init(preferences: proxiable, key: "") } /// Create a proxy with a prefix `key`. /// Before accessing the underlying `preferences`, the `key` will be added as prefix. public convenience init(preferences proxiable: PreferencesType, key parentKey: String) { self.init(preferences: proxiable, key: parentKey, separator: nil) } // using a separator for recustion -> not tested public init(preferences proxiable: PreferencesType, key parentKey: String, separator: String?) { self.proxiable = proxiable self.parentKey = parentKey self.separator = separator } /// Genetated the final key. fileprivate func computeKey(_ key: String) -> String { return self.parentKey + (self.separator ?? "") + key } /// Genetated the original key. fileprivate func computeInverseKey(_ key: String) -> String? { let prefix = self.parentKey + (self.separator ?? "") if key.starts(with: prefix) { let index = key.index(key.startIndex, offsetBy: prefix.count) // to remove prefix return String(key[index...]) } return nil } /// Want a recustion with multiple proxy, testing ["key1"]["key2"] fileprivate func hasRecursion() -> Bool { return self.separator != nil } /// Get the value for `key`. open subscript(key: String) -> PreferenceObject? { let finalKey = computeKey(key) if let value = self.proxiable.object(forKey: finalKey) { return value } if hasRecursion() { return ProxyPreferences(preferences: self.proxiable, key: finalKey, separator: self.separator) } return nil } } extension ProxyPreferences: PreferencesType { public func object(forKey key: PreferenceKey) -> PreferenceObject? { return self.proxiable.object(forKey: computeKey(key)) } public func hasObject(forKey key: PreferenceKey) -> Bool { return self.proxiable.hasObject(forKey: computeKey(key)) } public func string(forKey key: PreferenceKey) -> String? { return self.proxiable.string(forKey: computeKey(key)) } public func array(forKey key: PreferenceKey) -> [PreferenceObject]? { return self.proxiable.array(forKey: computeKey(key)) } public func dictionary(forKey key: PreferenceKey) -> PreferencesDictionary? { return self.proxiable.dictionary(forKey: computeKey(key)) } public func data(forKey key: PreferenceKey) -> Data? { return self.proxiable.data(forKey: computeKey(key)) } public func stringArray(forKey key: PreferenceKey) -> [String]? { return self.proxiable.stringArray(forKey: computeKey(key)) } public func integer(forKey key: PreferenceKey) -> Int { return self.proxiable.integer(forKey: computeKey(key)) } public func float(forKey key: PreferenceKey) -> Float { return self.proxiable.float(forKey: computeKey(key)) } public func double(forKey key: PreferenceKey) -> Double { return self.proxiable.double(forKey: computeKey(key)) } public func bool(forKey key: PreferenceKey) -> Bool { return self.proxiable.bool(forKey: computeKey(key)) } public func url(forKey key: PreferenceKey) -> URL? { return self.proxiable.url(forKey: computeKey(key)) } public func unarchiveObject(forKey key: PreferenceKey) -> PreferenceObject? { return self.proxiable.unarchiveObject(forKey: computeKey(key)) } public func dictionary() -> PreferencesDictionary { let proxiableDictionary = self.proxiable.dictionary() if self.parentKey.isEmpty && separator?.isEmpty ?? false { return proxiableDictionary } var result: PreferencesDictionary = [:] for (key, value) in proxiableDictionary { if let inverseKey = computeInverseKey(key) { result[inverseKey]=value } // else cannot be proxied } return result } } /// A `MutablePreferencesType` proxy of another `MutablePreferencesType`. open class MutableProxyPreferences: ProxyPreferences { fileprivate var mutable: MutablePreferencesType { // swiftlint:disable:next force_cast return self.proxiable as! MutablePreferencesType } public init(preferences proxiable: MutablePreferencesType, key parentKey: PreferenceKey = "", separator: String? = nil) { super.init(preferences: proxiable, key: parentKey, separator: separator) } override open subscript(key: PreferenceKey) -> PreferenceObject? { get { let finalKey = computeKey(key) if let value = self.proxiable.object(forKey: finalKey) { return value } if hasRecursion() { return ProxyPreferences(preferences: self.proxiable, key: finalKey, separator: self.separator) } return nil } set { let finalKey = computeKey(key) if newValue == nil { self.mutable.removeObject(forKey: finalKey) } else { self.mutable.set(newValue, forKey: finalKey) } } } } extension MutableProxyPreferences: MutablePreferencesType { public func set(_ value: PreferenceObject?, forKey key: PreferenceKey) { self.mutable.set(value, forKey: computeKey(key)) } public func removeObject(forKey key: PreferenceKey) { self.mutable.removeObject(forKey: computeKey(key)) } public func set(_ value: Int, forKey key: PreferenceKey) { self.mutable.set(value, forKey: computeKey(key)) } public func set(_ value: Float, forKey key: PreferenceKey) { self.mutable.set(value, forKey: computeKey(key)) } public func set(_ value: Double, forKey key: PreferenceKey) { self.mutable.set(value, forKey: computeKey(key)) } public func set(_ value: Bool, forKey key: PreferenceKey) { self.mutable.set(value, forKey: computeKey(key)) } public func set(_ url: URL?, forKey key: PreferenceKey) { self.mutable.set(url, forKey: computeKey(key)) } public func set(objectToArchive value: PreferenceObject?, forKey key: PreferenceKey) { self.mutable.set(objectToArchive: value, forKey: computeKey(key)) } public func clearAll() { self.mutable.clearAll() } public func set(dictionary registrationDictionary: PreferencesDictionary) { let proxiableDictionary = self.proxiable.dictionary() if self.parentKey.isEmpty && separator?.isEmpty ?? false { self.mutable.set(dictionary: registrationDictionary) } else { var result: PreferencesDictionary = [:] for (key, value) in proxiableDictionary { result[computeKey(key)]=value } self.mutable.set(dictionary: result) } } } extension PreferencesType { public func immutableProxy() -> PreferencesType { return ProxyPreferences(preferences: self) } } // MARK: adapter generic // Allow to implement 'dictionary' using the new 'keys' // Subclasses must implement objectForKey & keys public protocol PreferencesAdapter: PreferencesType { func keys() -> [String] } extension PreferencesAdapter { public func dictionary() -> PreferencesDictionary { var dico: PreferencesDictionary = [:] for name in self.keys() { if let value = self.object(forKey: name) { dico[name] = value } } return dico } } // MARK: KVC // object must informal protocol NSKeyValueCoding open class KVCPreferences: PreferencesAdapter { fileprivate let object: NSObject public init(_ object: NSObject) { self.object = object } open func object(forKey key: PreferenceKey) -> PreferenceObject? { return self.object.value(forKey: key) } open func keys() -> [String] { var count: UInt32 = 0 // FIXME: not recursive? guard let properties = class_copyPropertyList(self.object.classForCoder, &count) else { return [] } var names: [String] = [] for i in 0 ..< Int(count) { let property: objc_property_t = properties[i] let name: String = String(cString: property_getName(property)) names.append(name) } free(properties) return names } } open class MutableKVCPreferences: KVCPreferences { public override init(_ object: NSObject) { super.init(object) } open subscript(key: PreferenceKey) -> PreferenceObject? { get { return self.object(forKey: key) } set { self.set(newValue, forKey: key) } } } extension MutableKVCPreferences: MutablePreferencesType { public func set(_ value: PreferenceObject?, forKey key: PreferenceKey) { if self.object.responds(to: NSSelectorFromString(key)) { self.object.setValue(value, forKey: key) } } public func removeObject(forKey key: PreferenceKey) { if self.object.responds(to: NSSelectorFromString(key)) { self.object.setValue(nil, forKey: key) } } public func set(_ value: Int, forKey key: PreferenceKey) { self.set(NSNumber(value: value), forKey: key) } public func set(_ value: Float, forKey key: PreferenceKey) { self.set(NSNumber(value: value), forKey: key) } public func set(_ value: Double, forKey key: PreferenceKey) { self.set(NSNumber(value: value), forKey: key) } public func set(_ value: Bool, forKey key: PreferenceKey) { self.set(NSNumber(value: value), forKey: key) } public func clearAll() { // not implemented, maybe add protocol to set defaults attributes values } } // MARK: - Collection // Adapter for collection to conform to PreferencesType // using two closure to get key and value from an object open class CollectionPreferencesAdapter<C: Collection> { let collection: C public typealias MapPreferenceKey = (C.Iterator.Element) -> PreferenceKey public typealias MapPreferenceObject = (C.Iterator.Element) -> PreferenceObject let mapKey: MapPreferenceKey let mapValue: MapPreferenceObject public init(collection: C, mapKey: @escaping MapPreferenceKey, mapValue: @escaping MapPreferenceObject) { self.collection = collection self.mapKey = mapKey self.mapValue = mapValue } } extension CollectionPreferencesAdapter: PreferencesType { public func object(forKey key: PreferenceKey) -> PreferenceObject? { if let object = collection.find({ mapKey($0) == key }) { return mapValue(object) } return nil } public func dictionary() -> PreferencesDictionary { return collection.dictionary { ( mapKey($0), mapValue($0) ) } } } extension Collection { func mapFilterNil<T>(_ transform: (Self.Iterator.Element) -> T?) -> [T] { return self.map(transform).filter { $0 != nil }.compactMap { $0 } } func dictionary<K, V>(_ transform: (Self.Iterator.Element) throws -> (key: K, value: V)?) rethrows -> [K: V] { var dict: [K: V] = [:] for element in self { if let (key, value) = try transform(element) { dict[key] = value } } return dict } func find(_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Self.Iterator.Element? { return try firstIndex(where: predicate).map { self[$0] } } }
mit
d3c463d96045df95f9c63ac691b67e78
32.088091
125
0.634078
4.575457
false
false
false
false
ReneLindhorst/MapScaleBar
Example/ViewController.swift
1
1984
// ViewController.swift // // Copyright (c) 2015 René Lindhorst // // 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 MapKit class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet var mapScaleBar: MapScaleBar! // The MapScaleBar get adjusted using a DisplayLink so it's size is updated during pan gestures as well as double taps. private lazy var displayLink: CADisplayLink = { let displayLink = CADisplayLink(target: self.mapScaleBar, selector: Selector("adjustScale")) displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode:NSRunLoopCommonModes) displayLink.paused = true return displayLink }() func mapView(mapView: MKMapView!, regionWillChangeAnimated animated: Bool) { displayLink.paused = false } func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) { displayLink.paused = true } }
mit
d27c2b74975357006d1f4cd9a0ae8ec1
38.66
123
0.738275
4.920596
false
false
false
false
yoichitgy/SwinjectMVVMExample
Carthage/Checkouts/ReactiveSwift/ReactiveSwift.playground/Pages/Signal.xcplaygroundpage/Contents.swift
2
8482
/*: > # IMPORTANT: To use `ReactiveSwift.playground`, please: 1. Retrieve the project dependencies using one of the following terminal commands from the ReactiveSwift project root directory: - `script/bootstrap` **OR**, if you have [Carthage](https://github.com/Carthage/Carthage) installed - `carthage checkout` 1. Open `ReactiveSwift.xcworkspace` 1. Build `Result-Mac` scheme 1. Build `ReactiveSwift-macOS` scheme 1. Finally open the `ReactiveSwift.playground` 1. Choose `View > Show Debug Area` */ import Result import ReactiveSwift import Foundation /*: ## Signal A **signal**, represented by the [`Signal`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/ReactiveSwift/Signal.swift) type, is any series of [`Event`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/ReactiveSwift/Event.swift) values over time that can be observed. Signals are generally used to represent event streams that are already “in progress”, like notifications, user input, etc. As work is performed or data is received, events are _sent_ on the signal, which pushes them out to any observers. All observers see the events at the same time. Users must observe a signal in order to access its events. Observing a signal does not trigger any side effects. In other words, signals are entirely producer-driven and push-based, and consumers (observers) cannot have any effect on their lifetime. While observing a signal, the user can only evaluate the events in the same order as they are sent on the signal. There is no random access to values of a signal. Signals can be manipulated by applying [primitives](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Documentation/BasicOperators.md) to them. Typical primitives to manipulate a single signal like `filter`, `map` and `reduce` are available, as well as primitives to manipulate multiple signals at once (`zip`). Primitives operate only on the `value` events of a signal. The lifetime of a signal consists of any number of `value` events, followed by one terminating event, which may be any one of `failed`, `completed`, or `interrupted` (but not a combination). Terminating events are not included in the signal’s values—they must be handled specially. */ /*: ### `Subscription` A Signal represents and event stream that is already "in progress", sometimes also called "hot". This means, that a subscriber may miss events that have been sent before the subscription. Furthermore, the subscription to a signal does not trigger any side effects */ scopedExample("Subscription") { // Signal.pipe is a way to manually control a signal. the returned observer can be used to send values to the signal let (signal, observer) = Signal<Int, NoError>.pipe() let subscriber1 = Observer<Int, NoError>(value: { print("Subscriber 1 received \($0)") } ) let subscriber2 = Observer<Int, NoError>(value: { print("Subscriber 2 received \($0)") } ) print("Subscriber 1 subscribes to the signal") signal.observe(subscriber1) print("Send value `10` on the signal") // subscriber1 will receive the value observer.send(value: 10) print("Subscriber 2 subscribes to the signal") // Notice how nothing happens at this moment, i.e. subscriber2 does not receive the previously sent value signal.observe(subscriber2) print("Send value `20` on the signal") // Notice that now, subscriber1 and subscriber2 will receive the value observer.send(value: 20) } /*: ### `empty` A Signal that completes immediately without emitting any value. */ scopedExample("`empty`") { let emptySignal = Signal<Int, NoError>.empty let observer = Observer<Int, NoError>( value: { _ in print("value not called") }, failed: { _ in print("error not called") }, completed: { print("completed not called") }, interrupted: { print("interrupted called") } ) emptySignal.observe(observer) } /*: ### `never` A Signal that never sends any events to its observers. */ scopedExample("`never`") { let neverSignal = Signal<Int, NoError>.never let observer = Observer<Int, NoError>( value: { _ in print("value not called") }, failed: { _ in print("error not called") }, completed: { print("completed not called") }, interrupted: { print("interrupted not called") } ) neverSignal.observe(observer) } /*: ## `Operators` ### `uniqueValues` Forwards only those values from `self` that are unique across the set of all values that have been seen. Note: This causes the values to be retained to check for uniqueness. Providing a function that returns a unique value for each sent value can help you reduce the memory footprint. */ scopedExample("`uniqueValues`") { let (signal, observer) = Signal<Int, NoError>.pipe() let subscriber = Observer<Int, NoError>(value: { print("Subscriber received \($0)") } ) let uniqueSignal = signal.uniqueValues() uniqueSignal.observe(subscriber) observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) observer.send(value: 4) observer.send(value: 3) observer.send(value: 3) observer.send(value: 5) } /*: ### `map` Maps each value in the signal to a new value. */ scopedExample("`map`") { let (signal, observer) = Signal<Int, NoError>.pipe() let subscriber = Observer<Int, NoError>(value: { print("Subscriber received \($0)") } ) let mappedSignal = signal.map { $0 * 2 } mappedSignal.observe(subscriber) print("Send value `10` on the signal") observer.send(value: 10) } /*: ### `mapError` Maps errors in the signal to a new error. */ scopedExample("`mapError`") { let (signal, observer) = Signal<Int, NSError>.pipe() let subscriber = Observer<Int, NSError>(failed: { print("Subscriber received error: \($0)") } ) let mappedErrorSignal = signal.mapError { (error:NSError) -> NSError in let userInfo = [NSLocalizedDescriptionKey: "🔥"] let code = error.code + 10000 let mappedError = NSError(domain: "com.reactivecocoa.errordomain", code: code, userInfo: userInfo) return mappedError } mappedErrorSignal.observe(subscriber) print("Send error `NSError(domain: \"com.reactivecocoa.errordomain\", code: 4815, userInfo: nil)` on the signal") observer.send(error: NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil)) } /*: ### `filter` Preserves only the values of the signal that pass the given predicate. */ scopedExample("`filter`") { let (signal, observer) = Signal<Int, NoError>.pipe() let subscriber = Observer<Int, NoError>(value: { print("Subscriber received \($0)") } ) // subscriber will only receive events with values greater than 12 let filteredSignal = signal.filter { $0 > 12 ? true : false } filteredSignal.observe(subscriber) observer.send(value: 10) observer.send(value: 11) observer.send(value: 12) observer.send(value: 13) observer.send(value: 14) } /*: ### `skipNil` Unwraps non-`nil` values and forwards them on the returned signal, `nil` values are dropped. */ scopedExample("`skipNil`") { let (signal, observer) = Signal<Int?, NoError>.pipe() // note that the signal is of type `Int?` and observer is of type `Int`, given we're unwrapping // non-`nil` values let subscriber = Observer<Int, NoError>(value: { print("Subscriber received \($0)") } ) let skipNilSignal = signal.skipNil() skipNilSignal.observe(subscriber) observer.send(value: 1) observer.send(value: nil) observer.send(value: 3) } /*: ### `take(first:)` Returns a signal that will yield the first `count` values from `self` */ scopedExample("`take(first:)`") { let (signal, observer) = Signal<Int, NoError>.pipe() let subscriber = Observer<Int, NoError>(value: { print("Subscriber received \($0)") } ) let takeSignal = signal.take(first: 2) takeSignal.observe(subscriber) observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) observer.send(value: 4) } /*: ### `collect` Returns a signal that will yield an array of values when `self` completes. - Note: When `self` completes without collecting any value, it will send an empty array of values. */ scopedExample("`collect`") { let (signal, observer) = Signal<Int, NoError>.pipe() // note that the signal is of type `Int` and observer is of type `[Int]` given we're "collecting" // `Int` values for the lifetime of the signal let subscriber = Observer<[Int], NoError>(value: { print("Subscriber received \($0)") } ) let collectSignal = signal.collect() collectSignal.observe(subscriber) observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) observer.send(value: 4) observer.sendCompleted() }
mit
1ea74990ae09bf279d423ed6a8facd74
34.295833
256
0.730492
3.699127
false
false
false
false
tlax/GaussSquad
GaussSquad/View/LinearEquations/Plot/VLinearEquationsPlotBarZoom.swift
1
4224
import UIKit class VLinearEquationsPlotBarZoom:UIView { private weak var controller:CLinearEquationsPlot! private weak var stepper:UIStepper! private weak var label:UILabel! private let numberFormatter:NumberFormatter private let kMinInteger:Int = 1 private let kMinFraction:Int = 0 private let kMaxFraction:Int = 3 private let kLabelRight:CGFloat = -10 private let kLabelWidth:CGFloat = 70 private let kLabelBottom:CGFloat = -8 private let kLabelHeight:CGFloat = 30 private let kStepperWidth:CGFloat = 110 private let kStepperHeight:CGFloat = 38 private let kMinZoom:Double = -28 private let kMaxZoom:Double = 30 init(controller:CLinearEquationsPlot) { numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal numberFormatter.minimumFractionDigits = kMinFraction numberFormatter.maximumFractionDigits = kMaxFraction numberFormatter.minimumIntegerDigits = kMinInteger super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let label:UILabel = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.isUserInteractionEnabled = false label.backgroundColor = UIColor.clear label.textAlignment = NSTextAlignment.right label.font = UIFont.bold(size:14) label.textColor = UIColor.black self.label = label let stepper:UIStepper = UIStepper() stepper.translatesAutoresizingMaskIntoConstraints = false stepper.tintColor = UIColor.black stepper.minimumValue = kMinZoom stepper.maximumValue = kMaxZoom stepper.value = controller.model.zoom stepper.addTarget( self, action:#selector(actionStepper(sender:)), for:UIControlEvents.valueChanged) self.stepper = stepper addSubview(label) addSubview(stepper) NSLayoutConstraint.bottomToBottom( view:stepper, toView:self) NSLayoutConstraint.height( view:stepper, constant:kStepperHeight) NSLayoutConstraint.rightToRight( view:stepper, toView:self) NSLayoutConstraint.width( view:stepper, constant:kStepperWidth) NSLayoutConstraint.bottomToBottom( view:label, toView:self, constant:kLabelBottom) NSLayoutConstraint.height( view:label, constant:kLabelHeight) NSLayoutConstraint.rightToLeft( view:label, toView:stepper, constant:kLabelRight) NSLayoutConstraint.width( view:label, constant:kLabelWidth) showZoom() } required init?(coder:NSCoder) { return nil } //MARK: actions func actionStepper(sender stepper:UIStepper) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in var value:Double = stepper.value if value < 1 { let negativeValue:Double = abs(value - 2) value = 1 / negativeValue } self?.controller.updateZoom(zoom:value) DispatchQueue.main.async { [weak self] in self?.showZoom() } } } //MARK: private private func showZoom() { let zoom:Double = controller.model.zoom let zoomNumber:NSNumber = zoom as NSNumber guard let zoomString:String = numberFormatter.string(from:zoomNumber) else { return } let zoomDescr:String = String( format:NSLocalizedString("VLinearEquationsPlotBarZoom_descr", comment:""), zoomString) label.text = zoomDescr } }
mit
35ceb501f6f9770a0e750056c47a682f
28.957447
86
0.598958
5.609562
false
false
false
false
rolson/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Edit data/Edit features (connected)/FeatureTemplatePickerViewController.swift
1
4956
// Copyright 2016 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 FeatureTemplateInfo { var featureType:AGSFeatureType! var featureTemplate:AGSFeatureTemplate! var featureLayer:AGSFeatureLayer! } protocol FeatureTemplatePickerDelegate:class { func featureTemplatePickerViewControllerWantsToDismiss(controller:FeatureTemplatePickerViewController) func featureTemplatePickerViewController(controller:FeatureTemplatePickerViewController, didSelectFeatureTemplate template:AGSFeatureTemplate, forFeatureLayer featureLayer:AGSFeatureLayer) } class FeatureTemplatePickerViewController: UIViewController, UIBarPositioningDelegate { var infos = [FeatureTemplateInfo]() @IBOutlet weak var featureTemplateTableView: UITableView! weak var delegate:FeatureTemplatePickerDelegate? override func viewDidLoad() { super.viewDidLoad() } func addTemplatesFromLayer(featureLayer:AGSFeatureLayer) { let featureTable = featureLayer.featureTable as! AGSServiceFeatureTable //if layer contains only templates (no feature types) if featureTable.featureTemplates.count > 0 { //for each template for template in featureTable.featureTemplates { let info = FeatureTemplateInfo() info.featureLayer = featureLayer info.featureTemplate = template info.featureType = nil //add to array self.infos.append(info) } } //otherwise if layer contains feature types else { //for each type for type in featureTable.featureTypes { //for each temple in type for template in type.templates { let info = FeatureTemplateInfo() info.featureLayer = featureLayer info.featureTemplate = template info.featureType = type //add to array self.infos.append(info) } } } print("infos count :: \(self.infos.count)") } @IBAction func cancelAction() { //Notify the delegate that user tried to dismiss the view controller self.delegate?.featureTemplatePickerViewControllerWantsToDismiss(self) } //MARK: - table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.infos.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return nil } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //Get a cell let cellIdentifier = "TemplatePickerCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell! if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } cell.selectionStyle = .Blue //Set its label, image, etc for the template let info = self.infos[indexPath.row] cell.textLabel?.font = UIFont.systemFontOfSize(12) cell.textLabel?.text = info.featureTemplate.name // cell.imageView?.image = info.featureLayer.renderer.symb .swatchForFeatureWithAttributes(info.featureTemplate.prototypeAttributes, geometryType: info.featureLayer.geometryType, size: CGSizeMake(20, 20)) return cell } //MARK: - table view delegate func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { //Notify the delegate that the user picked a feature template let info = self.infos[indexPath.row] self.delegate?.featureTemplatePickerViewController(self, didSelectFeatureTemplate: info.featureTemplate, forFeatureLayer: info.featureLayer) //unselect the cell tableView.cellForRowAtIndexPath(indexPath)?.selected = false } //MARK: - UIBarPositioningDelegate func positionForBar(bar: UIBarPositioning) -> UIBarPosition { return .TopAttached } }
apache-2.0
7059931a709d6fcce8d8c8246905f5a8
37.418605
211
0.66586
5.369447
false
false
false
false
dwsjoquist/ELWebService
Source/Core/ServiceTaskResult.swift
1
1812
// // ServiceTaskResult.swift // ELWebService // // Created by Angelo Di Paolo on 11/5/15. // Copyright © 2015 WalmartLabs. All rights reserved. // import Foundation /// Represents the result of a service task. public enum ServiceTaskResult { /// Defines an empty task result case empty /// Defines a task result as a value case value(Any) /// Defines a task resulting in an error case failure(Error) func taskValue() throws -> Any? { switch self { case .failure(let error): throw error case .empty: return nil case .value(let value): return value } } } // MARK: - Objective-C Interop extension ServiceTaskResult { /// Initialize a service task result value from an Obj-C result init(objCHandlerResult result: ObjCHandlerResult?) { if let error = result?.error { self = .failure(error) } else if let value = result?.value { self = .value(value) } else { self = .empty } } } /// Represents the result of a Obj-C response handler @objc public final class ObjCHandlerResult: NSObject { /// The resulting value fileprivate(set) var value: AnyObject? /// The resulting error fileprivate(set) var error: NSError? public class func resultWithValue(_ value: AnyObject) -> ObjCHandlerResult { return ObjCHandlerResult(value: value) } public class func resultWithError(_ error: NSError) -> ObjCHandlerResult { return ObjCHandlerResult(error: error) } /// Initialize a result with a value fileprivate init(value: AnyObject) { self.value = value } /// Initialize a result with an error fileprivate init(error: NSError) { self.error = error } }
mit
9227bd158740ac85036f89792eec51d3
25.246377
80
0.628382
4.482673
false
false
false
false
overtake/TelegramSwift
TelegramShare/SEUnauthorizedViewController.swift
1
2046
// // SEUnauthorizedViewController.swift // Telegram // // Created by keepcoder on 29/03/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import Localization class SEUnauthorizedView : View { fileprivate let imageView:ImageView = ImageView() fileprivate let cancel:TitleButton = TitleButton() fileprivate let textView:TextView = TextView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) imageView.image = #imageLiteral(resourceName: "Icon_TelegramLogin").precomposed() imageView.sizeToFit() self.backgroundColor = theme.colors.background cancel.set(font: .medium(.title), for: .Normal) cancel.set(color: theme.colors.accent, for: .Normal) cancel.set(text: L10n.shareExtensionUnauthorizedOK, for: .Normal) let layout = TextViewLayout(.initialize(string: L10n.shareExtensionUnauthorizedDescription, color: theme.colors.text, font: .normal(.text)), alignment: .center) textView.backgroundColor = theme.colors.background textView.update(layout) addSubview(cancel) addSubview(textView) addSubview(imageView) } override func layout() { super.layout() imageView.centerX(y: 30) textView.textLayout?.measure(width: frame.width - 60) textView.update(textView.textLayout) textView.center() cancel.centerX(y: textView.frame.maxY + 20) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SEUnauthorizedViewController: GenericViewController<SEUnauthorizedView> { private let cancelImpl:()->Void init(cancelImpl:@escaping()->Void) { self.cancelImpl = cancelImpl super.init() } override func viewDidLoad() { super.viewDidLoad() genericView.cancel.set(handler: { [weak self] _ in self?.cancelImpl() }, for: .Click) } }
gpl-2.0
0f985c0c1962747951a0f74d9c910287
29.984848
168
0.652812
4.504405
false
false
false
false
brentsimmons/Evergreen
Shared/UserNotifications/UserNotificationManager.swift
1
4397
// // NotificationManager.swift // NetNewsWire // // Created by Maurice Parker on 10/2/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import Foundation import Account import Articles import UserNotifications final class UserNotificationManager: NSObject { override init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(accountDidDownloadArticles(_:)), name: .AccountDidDownloadArticles, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil) registerCategoriesAndActions() } @objc func accountDidDownloadArticles(_ note: Notification) { guard let articles = note.userInfo?[Account.UserInfoKey.newArticles] as? Set<Article> else { return } for article in articles { if !article.status.read, let webFeed = article.webFeed, webFeed.isNotifyAboutNewArticles ?? false { sendNotification(webFeed: webFeed, article: article) } } } @objc func statusesDidChange(_ note: Notification) { if let statuses = note.userInfo?[Account.UserInfoKey.statuses] as? Set<ArticleStatus>, !statuses.isEmpty { let identifiers = statuses.filter({ $0.read }).map { "articleID:\($0.articleID)" } UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifiers) return } if let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String>, let statusKey = note.userInfo?[Account.UserInfoKey.statusKey] as? ArticleStatus.Key, let flag = note.userInfo?[Account.UserInfoKey.statusFlag] as? Bool, statusKey == .read, flag == true { let identifiers = articleIDs.map { "articleID:\($0)" } UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifiers) } } } private extension UserNotificationManager { func sendNotification(webFeed: WebFeed, article: Article) { let content = UNMutableNotificationContent() content.title = webFeed.nameForDisplay if !ArticleStringFormatter.truncatedTitle(article).isEmpty { content.subtitle = ArticleStringFormatter.truncatedTitle(article) } content.body = ArticleStringFormatter.truncatedSummary(article) content.threadIdentifier = webFeed.webFeedID content.summaryArgument = "\(webFeed.nameForDisplay)" content.summaryArgumentCount = 1 content.sound = UNNotificationSound.default content.userInfo = [UserInfoKey.articlePath: article.pathUserInfo] content.categoryIdentifier = "NEW_ARTICLE_NOTIFICATION_CATEGORY" if let attachment = thumbnailAttachment(for: article, webFeed: webFeed) { content.attachments.append(attachment) } let request = UNNotificationRequest.init(identifier: "articleID:\(article.articleID)", content: content, trigger: nil) UNUserNotificationCenter.current().add(request) } /// Determine if there is an available icon for the article. This will then move it to the caches directory and make it avialble for the notification. /// - Parameters: /// - article: `Article` /// - webFeed: `WebFeed` /// - Returns: A `UNNotifcationAttachment` if an icon is available. Otherwise nil. /// - Warning: In certain scenarios, this will return the `faviconTemplateImage`. func thumbnailAttachment(for article: Article, webFeed: WebFeed) -> UNNotificationAttachment? { if let imageURL = article.iconImageUrl(webFeed: webFeed) { let thumbnail = try? UNNotificationAttachment(identifier: webFeed.webFeedID, url: imageURL, options: nil) return thumbnail } return nil } func registerCategoriesAndActions() { let readAction = UNNotificationAction(identifier: "MARK_AS_READ", title: NSLocalizedString("Mark as Read", comment: "Mark as Read"), options: []) let starredAction = UNNotificationAction(identifier: "MARK_AS_STARRED", title: NSLocalizedString("Mark as Starred", comment: "Mark as Starred"), options: []) let openAction = UNNotificationAction(identifier: "OPEN_ARTICLE", title: NSLocalizedString("Open", comment: "Open"), options: [.foreground]) let newArticleCategory = UNNotificationCategory(identifier: "NEW_ARTICLE_NOTIFICATION_CATEGORY", actions: [openAction, readAction, starredAction], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "", options: []) UNUserNotificationCenter.current().setNotificationCategories([newArticleCategory]) } }
mit
8d5ccb192b00ef90384c798927116374
40.084112
159
0.75273
4.267961
false
false
false
false
tinypass/piano-sdk-for-ios
PianoAPI/Models/TermConversion.swift
1
855
import Foundation @objc(PianoAPITermConversion) public class TermConversion: NSObject, Codable { /// Term conversion id @objc public var termConversionId: String? = nil /// The term that was converted @objc public var term: Term? = nil /// The term conversion type @objc public var type: String? = nil /// Application aid @objc public var aid: String? = nil /// The access that was created as a result of the term conversion @objc public var userAccess: Access? = nil /// The creation date @objc public var createDate: Date? = nil public enum CodingKeys: String, CodingKey { case termConversionId = "term_conversion_id" case term = "term" case type = "type" case aid = "aid" case userAccess = "user_access" case createDate = "create_date" } }
apache-2.0
a1d258381bd56d709ac9564d22b33b42
25.71875
70
0.643275
4.275
false
false
false
false
Srinija/SAGeometry
Example/SAGeometry/Graph.swift
1
5333
// // Graph.swift // SwiftGeometry // // Created by Srinija on 15/09/17. // Copyright © 2017 Srinija. All rights reserved. // import UIKit class Graph: UIView { public var chartTransform: CGAffineTransform? @IBInspectable var axisColor: UIColor = UIColor.black @IBInspectable var showInnerLines: Bool = true @IBInspectable var labelFontSize: CGFloat = 10 var axisLineWidth: CGFloat = 1 var deltaX: CGFloat = 10 // The change between each tick on the x axis var deltaY: CGFloat = 10 // and y axis var xMax: CGFloat = 100 var yMax: CGFloat = 100 var xMin: CGFloat = 0 var yMin: CGFloat = 0 var screenWidth = UIScreen.main.bounds.size.width var screenHeight = UIScreen.main.bounds.size.height override init(frame: CGRect) { super.init(frame: frame) combinedInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) combinedInit() } func combinedInit() { yMax = xMax * (screenHeight/screenWidth) setTransform(minX: xMin, maxX: xMax, minY: yMin, maxY: yMax) layer.borderWidth = 1 layer.borderColor = axisColor.cgColor } func setTransform(minX: CGFloat, maxX: CGFloat, minY: CGFloat, maxY: CGFloat) { let xOffset:CGFloat = 20.0 let yOffset:CGFloat = 20.0 let xScale = (screenWidth - yOffset - 10)/(maxX - minX) let yScale = ((screenHeight - xOffset - 30) - (screenHeight - xOffset - 30).truncatingRemainder(dividingBy: 10))/(maxY - minY) chartTransform = CGAffineTransform(a: xScale, b: 0, c: 0, d: -yScale, tx: yOffset, ty: screenHeight - xOffset) setNeedsDisplay() } override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext(), let t = chartTransform else { return } drawAxes(in: context, usingTransform: t) } public func setAxisRange() { setTransform(minX: xMin, maxX: xMax, minY: yMin, maxY: yMax) } func drawAxes(in context: CGContext, usingTransform t: CGAffineTransform) { context.saveGState() // make two paths, one for thick lines, one for thin let thickerLines = CGMutablePath() let thinnerLines = CGMutablePath() // the two line chart axes let xAxisPoints = [CGPoint(x: xMin, y: 0), CGPoint(x: xMax, y: 0)] let yAxisPoints = [CGPoint(x: 0, y: yMin), CGPoint(x: 0, y: yMax)] thickerLines.addLines(between: xAxisPoints, transform: t) thickerLines.addLines(between: yAxisPoints, transform: t) for x in stride(from: xMin, through: xMax, by: deltaX) { let tickPoints = showInnerLines ? [CGPoint(x: x, y: yMin).applying(t), CGPoint(x: x, y: yMax).applying(t)] : [CGPoint(x: x, y: 0).applying(t), CGPoint(x: x, y: 0).applying(t).adding(y: -5)] thinnerLines.addLines(between: tickPoints) if x != xMin { // draw the tick label (it is too buy if you draw it at the origin for both x & y let label = "\(Int(x))" as NSString // Int to get rid of the decimal, NSString to draw let labelSize = "\(Int(x))".size(withSystemFontSize: labelFontSize) let labelDrawPoint = CGPoint(x: x, y: 0).applying(t) .adding(x: -labelSize.width/2) .adding(y: 1) label.draw(at: labelDrawPoint, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: labelFontSize), NSAttributedStringKey.foregroundColor: axisColor]) } } // repeat for y for y in stride(from: yMin, through: yMax, by: deltaY) { let tickPoints = showInnerLines ? [CGPoint(x: xMin, y: y).applying(t), CGPoint(x: xMax, y: y).applying(t)] : [CGPoint(x: 0, y: y).applying(t), CGPoint(x: 0, y: y).applying(t).adding(x: 5)] thinnerLines.addLines(between: tickPoints) if y != yMin { let label = "\(Int(y))" as NSString let labelSize = "\(Int(y))".size(withSystemFontSize: labelFontSize) let labelDrawPoint = CGPoint(x: 0, y: y).applying(t) .adding(x: -labelSize.width - 1) .adding(y: -labelSize.height/2) label.draw(at: labelDrawPoint, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: labelFontSize), NSAttributedStringKey.foregroundColor: axisColor]) } } context.setStrokeColor(axisColor.cgColor) context.setLineWidth(axisLineWidth) context.addPath(thickerLines) context.strokePath() context.setStrokeColor(axisColor.withAlphaComponent(0.5).cgColor) context.setLineWidth(axisLineWidth/2) context.addPath(thinnerLines) context.strokePath() context.restoreGState() } }
mit
7ade4635af08cba05acb4a3279e30082
35.272109
134
0.567892
4.432253
false
false
false
false
danielhonies/stars
RatingSystem/RatingControl.swift
1
5913
// Created by Daniel Honies on 23.07.15. // Copyright © 2015 Daniel Honies. All rights reserved. // import UIKit @IBDesignable class RatingControl: UIView { // MARK: Properties @IBInspectable public var rating: Double = 0 { didSet { setNeedsLayout() } } var ratingButtons = [UIButton]() @IBInspectable public var spacing: Int = 5{ didSet { setNeedsLayout() } } @IBInspectable public var stars: Int = 5{ didSet { buttonInit() } } @IBInspectable public var filledStarImage: UIImage? = UIImage? (){ didSet { updateButtonImages() } } @IBInspectable public var emptyStarImage: UIImage? = UIImage?(){ didSet { updateButtonImages() } } var splitButton = UIButton() // MARK: Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.filledStarImage = UIImage(named: "filledStar") self.emptyStarImage = UIImage(named: "emptyStar") buttonInit() } override init(frame: CGRect){ super.init(frame: frame) buttonInit() } convenience init( frame: CGRect, rating: Double, spacing: Int, stars: Int) { self.init(frame: frame) self.spacing = spacing self.stars = stars self.rating = rating buttonInit() } override public func awakeFromNib() { super.awakeFromNib() buttonInit() } override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() buttonInit() } func buttonInit(){ let bundle = NSBundle(forClass: RatingControl.self) if emptyStarImage == nil { emptyStarImage = UIImage(named: "emptyStar", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) } if filledStarImage == nil { filledStarImage = UIImage(named: "filledStar", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) } ratingButtons = [UIButton]() for _ in 0..<stars{ let button = UIButton() button.setImage(emptyStarImage, forState: .Normal) button.setImage(filledStarImage, forState: .Selected) button.setImage(filledStarImage, forState: [.Highlighted, .Selected]) button.adjustsImageWhenHighlighted = false button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown) ratingButtons += [button] addSubview(button) } } override func layoutSubviews() { // Set the button's width and height to a square the size of the frame's height. let buttonSize = Int(frame.size.height) var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize) // Offset each button's origin by the length of the button plus spacing. for (index, button) in ratingButtons.enumerate() { buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing)) button.frame = buttonFrame } updateButtonSelectionStates() } // MARK: Button Action func ratingButtonTapped(button: UIButton) { self.splitButton.removeFromSuperview() rating = Double(ratingButtons.indexOf(button)!) + 1 updateButtonSelectionStates() } func updateButtonSelectionStates() { for (index, button) in ratingButtons.enumerate() { let dindex: Double = Double(index) if ((rating-dindex)>=1){ button.selected = dindex < rating } else if((rating-dindex)<1)&&(rating-dindex)>0 && !splitButton.isDescendantOfView(self){ button.selected = false splitButton = UIButton() splitButton.selected = true let length: CGFloat = CGFloat(rating-dindex) splitButton.setImage(ImageUtil.cropToLength(image: filledStarImage!, length:length), forState: .Selected) let buttonSize = Int(frame.size.height) var splitButtonFrame = CGRect(x: 0, y: 0, width: CGFloat(buttonSize) * length, height: CGFloat(buttonSize)) splitButtonFrame.origin.x = CGFloat(index * (buttonSize + spacing)) splitButton.frame = splitButtonFrame self.addSubview(splitButton) } else{ button.selected = false } } } func updateButtonImages(){ for button in ratingButtons{ button.setImage(emptyStarImage, forState: .Normal) button.setImage(filledStarImage, forState: .Selected) button.setImage(filledStarImage, forState: [.Highlighted, .Selected]) button.adjustsImageWhenHighlighted = false } } } class ImageUtil: NSObject { static func cropToLength(image originalImage: UIImage, length: CGFloat) -> UIImage { let contextImage: UIImage = UIImage(CGImage: originalImage.CGImage!) let contextSize: CGSize = contextImage.size let posX: CGFloat let posY: CGFloat let width: CGFloat let height: CGFloat posX = 0 posY = 0//((contextSize.height - contextSize.width) / 2) width = contextSize.width * length height = contextSize.height let rect: CGRect = CGRectMake(posX, posY, width, height) let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, rect)! let image: UIImage = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation) return image } }
mit
11c4367dfce5768ce6faede14bfb0448
33.776471
129
0.59929
4.993243
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDK/Room/Polls/PollModels.swift
1
1775
// // Copyright 2021 The Matrix.org Foundation C.I.C // // 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 public enum PollKind { case disclosed case undisclosed } public protocol PollAnswerOptionProtocol { var id: String { get } var text: String { get } var count: UInt { get } var isWinner: Bool { get } var isCurrentUserSelection: Bool { get } } public protocol PollProtocol { var text: String { get } var answerOptions: [PollAnswerOptionProtocol] { get } var kind: PollKind { get } var maxAllowedSelections: UInt { get } var isClosed: Bool { get } var totalAnswerCount: UInt { get } var hasBeenEdited: Bool { get } } class PollAnswerOption: PollAnswerOptionProtocol { var id: String = "" var text: String = "" var count: UInt = 0 var isWinner: Bool = false var isCurrentUserSelection: Bool = false } class Poll: PollProtocol { var text: String = "" var answerOptions: [PollAnswerOptionProtocol] = [] var kind: PollKind = .disclosed var maxAllowedSelections: UInt = 1 var isClosed: Bool = false var hasBeenEdited: Bool = false var totalAnswerCount: UInt { return self.answerOptions.reduce(0) { $0 + $1.count} } }
apache-2.0
62b88b1dd0cb0b22b4ad20be10d918c7
27.174603
75
0.68507
4.061785
false
false
false
false
philipgreat/b2b-swift-app
B2BSimpleApp/B2BSimpleApp/UniversalPriceReviewRemoteManagerImpl.swift
1
2523
//Domain B2B/UniversalPriceReview/ import SwiftyJSON import Alamofire import ObjectMapper class UniversalPriceReviewRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{ override init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } override var remoteURLPrefix:String{ //Every manager need to config their own URL return "https://philipgreat.github.io/naf/universalPriceReviewManager/" } func loadUniversalPriceReviewDetail(universalPriceReviewId:String, universalPriceReviewSuccessAction: (UniversalPriceReview)->String, universalPriceReviewErrorAction: (String)->String){ let methodName = "loadUniversalPriceReviewDetail" let parameters = [universalPriceReviewId] let url = compositeCallURL(methodName, parameters: parameters) Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let universalPriceReview = self.extractUniversalPriceReviewFromJSON(json){ universalPriceReviewSuccessAction(universalPriceReview) } } case .Failure(let error): print(error) universalPriceReviewErrorAction("\(error)") } } } func extractUniversalPriceReviewFromJSON(json:JSON) -> UniversalPriceReview?{ let jsonTool = SwiftyJSONTool() let universalPriceReview = jsonTool.extractUniversalPriceReview(json) return universalPriceReview } //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). let result = "UniversalPriceReviewRemoteManagerImpl, V1" return result } static var CLASS_VERSION = 1 //This value is for serializer like message pack to identify the versions match between //local and remote object. } //Reference http://grokswift.com/simple-rest-with-swift/ //Reference https://github.com/SwiftyJSON/SwiftyJSON //Reference https://github.com/Alamofire/Alamofire //Reference https://github.com/Hearst-DD/ObjectMapper //let remote = RemoteManagerImpl() //let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"]) //print(result)
mit
2341d8874d58b88ca383c34024bc4bd9
28.768293
100
0.722553
4.0368
false
false
false
false
futomtom/DynoOrder
Segmentio/Source/Cells/SegmentioCellWithImageBeforeLabel.swift
3
2109
// // SegmentioCellWithImageBeforeLabel.swift // Segmentio // // Created by Dmitriy Demchenko // Copyright © 2016 Yalantis Mobile. All rights reserved. // import UIKit class SegmentioCellWithImageBeforeLabel: SegmentioCell { override func setupConstraintsForSubviews() { super.setupConstraintsForSubviews() guard let imageContainerView = imageContainerView else { return } guard let containerView = containerView else { return } let metrics = ["labelHeight": segmentTitleLabelHeight] let views = [ "imageContainerView": imageContainerView, "containerView": containerView ] // main constraints let segmentImageViewVerticalConstraint = NSLayoutConstraint.constraints( withVisualFormat: "V:[imageContainerView(labelHeight)]", options: [.alignAllCenterY], metrics: metrics, views: views) NSLayoutConstraint.activate(segmentImageViewVerticalConstraint) let contentViewHorizontalConstraints = NSLayoutConstraint.constraints( withVisualFormat: "|-[imageContainerView(labelHeight)]-[containerView]-|", options: [.alignAllCenterY], metrics: metrics, views: views) NSLayoutConstraint.activate(contentViewHorizontalConstraints) // custom constraints topConstraint = NSLayoutConstraint( item: containerView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: padding ) topConstraint?.isActive = true bottomConstraint = NSLayoutConstraint( item: contentView, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: padding ) bottomConstraint?.isActive = true } }
mit
2aa5194b4b24ffc0b308da684e5f921d
29.550725
86
0.5963
6.36858
false
false
false
false
chain/chain
desktop/mac/ChainCore/ChainCore.swift
1
5576
import Cocoa // Manages the cored process class ChainCore: NSObject { let port: UInt let dbPort: UInt private var queue: DispatchQueue private var task: Process? private var taskCleaner: TaskCleaner? private var expectingTermination: Bool = false var databaseURL: String { return "postgres://localhost:\(dbPort)/core?sslmode=disable" } var homeDir: String { return NSHomeDirectory() + "/Library/Application Support/Chain Core" } var corectlPath: String { return Bundle.main.path(forResource: "corectl", ofType: nil)! } var dashboardURL: URL { return URL(string: "http://localhost:\(port)/dashboard")! } var infoURL: URL { return URL(string: "http://localhost:\(port)/info")! } var docsURL: URL { return URL(string: "http://localhost:\(port)/docs")! } var logURL: URL { return URL(fileURLWithPath: FileManager().applicationSupportDirectoryPath().appendingFormat("/cored.log")) } static var shared: ChainCore = ChainCore() override init() { self.port = Config.shared.corePort self.dbPort = Config.shared.dbPort self.queue = DispatchQueue(label: "com.chain.cored") super.init() } func reset() { } // Main thread func startIfNeeded(_ completion: @escaping (OperationStatus) -> Void) { expectingTermination = false if let t = self.task { if t.isRunning { completion(.Success) return } else { self.task = nil } } start(completion) } func start(_ completion: @escaping (OperationStatus) -> Void) { if Config.portInUse(self.port) { completion(.Failure(NSError(domain: "com.chain.ChainCore.cored-status", code: 0, userInfo: [NSLocalizedDescriptionKey: "Chain Core cannot run on localhost:\(self.port), port is in use."]))) return } self.task?.terminate() let t = makeTask() self.task = t queue.async { t.launch() let pid = t.processIdentifier DispatchQueue.main.async { self.taskCleaner?.terminate() self.taskCleaner = TaskCleaner(childPid: pid) self.taskCleaner?.watch() } t.waitUntilExit() if !self.expectingTermination { // If task died unexpectedly, kill the whole app. We are not smart enough to deal with restarts while our tasks are robust enough not to die spontaneously. NSLog("Chain Core stopped unexpectedly. Exiting.") DispatchQueue.main.async { ServerManager.shared.registerFailure("Chain Core stopped unexpectedly. Please check the logs and try again.") } } } DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) { let testRequest = URLSession.shared.dataTask(with: self.infoURL, completionHandler: { (data, response, error) in DispatchQueue.main.async { if let t = self.task { if t.isRunning { if data != nil { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { completion(.Success) } } else if error != nil { self.task?.terminate() self.task = nil completion(.Failure(error! as NSError)) } else { self.task?.terminate() self.task = nil completion(.Failure(NSError(domain: "com.chain.ChainCore.cored-status", code: 0, userInfo: [NSLocalizedDescriptionKey: "Chain Core failed to respond"]))) } } else { self.task = nil completion(.Failure(NSError(domain: "com.chain.ChainCore.cored-status", code: 0, userInfo: [NSLocalizedDescriptionKey: "Chain Core failed to launch"]))) } } else { completion(.Failure(NSError(domain: "com.chain.ChainCore.cored-status", code: 0, userInfo: [NSLocalizedDescriptionKey: "Chain Core was stopped"]))) } } }) testRequest.resume() } } func makeTask() -> Process { let task = Process() task.launchPath = Bundle.main.path(forResource: "cored", ofType: nil) task.arguments = [] task.environment = [ "DATABASE_URL": databaseURL, "CHAIN_CORE_HOME": homeDir, "LISTEN": ":\(port)", "LOGFILE": self.logURL.path, // FIXME: cored binaries built with bin/build-cored-release have trouble acquiring a default user for Postgres connections. This ensures the current user's login name is always available in the environment. "USER": NSUserName(), ] //task.standardOutput = Pipe() //task.standardError = Pipe() return task } func stopSync() { expectingTermination = true self.taskCleaner?.terminate() self.taskCleaner = nil self.task?.terminate() self.task = nil } }
agpl-3.0
14fa61dc6ba5f27c7486f06ac04d704f
35.207792
218
0.533895
5.005386
false
false
false
false
terikon/cordova-plugin-photo-library
src/ios/PhotoLibraryProtocol.swift
1
7246
import Foundation @objc(PhotoLibraryProtocol) class PhotoLibraryProtocol : CDVURLProtocol { static let PHOTO_LIBRARY_PROTOCOL = "cdvphotolibrary" static let DEFAULT_WIDTH = "512" static let DEFAULT_HEIGHT = "384" static let DEFAULT_QUALITY = "0.5" lazy var concurrentQueue: OperationQueue = { var queue = OperationQueue() queue.name = "PhotoLibrary Protocol Queue" queue.qualityOfService = .background queue.maxConcurrentOperationCount = 4 return queue }() override init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { super.init(request: request, cachedResponse: cachedResponse, client: client) } override class func canInit(with request: URLRequest) -> Bool { let scheme = request.url?.scheme if scheme?.lowercased() == PHOTO_LIBRARY_PROTOCOL { return true } return false } override func startLoading() { if let url = self.request.url { if url.path == "" { let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) let queryItems = urlComponents?.queryItems // Errors are 404 as android plugin only supports returning 404 let photoId = queryItems?.filter({$0.name == "photoId"}).first?.value if photoId == nil { self.sendErrorResponse(404, error: "Missing 'photoId' query parameter") return } if !PhotoLibraryService.hasPermission() { self.sendErrorResponse(404, error: PhotoLibraryService.PERMISSION_ERROR) return } let service = PhotoLibraryService.instance if url.host?.lowercased() == "thumbnail" { let widthStr = queryItems?.filter({$0.name == "width"}).first?.value ?? PhotoLibraryProtocol.DEFAULT_WIDTH let width = Int(widthStr) if width == nil { self.sendErrorResponse(404, error: "Incorrect 'width' query parameter") return } let heightStr = queryItems?.filter({$0.name == "height"}).first?.value ?? PhotoLibraryProtocol.DEFAULT_HEIGHT let height = Int(heightStr) if height == nil { self.sendErrorResponse(404, error: "Incorrect 'height' query parameter") return } let qualityStr = queryItems?.filter({$0.name == "quality"}).first?.value ?? PhotoLibraryProtocol.DEFAULT_QUALITY let quality = Float(qualityStr) if quality == nil { self.sendErrorResponse(404, error: "Incorrect 'quality' query parameter") return } concurrentQueue.addOperation { service.getThumbnail(photoId!, thumbnailWidth: width!, thumbnailHeight: height!, quality: quality!) { (imageData) in if (imageData == nil) { self.sendErrorResponse(404, error: PhotoLibraryService.PERMISSION_ERROR) return } self.sendResponseWithResponseCode(200, data: imageData!.data, mimeType: imageData!.mimeType) } } return } else if url.host?.lowercased() == "photo" { concurrentQueue.addOperation { service.getPhoto(photoId!) { (imageData) in if (imageData == nil) { self.sendErrorResponse(404, error: PhotoLibraryService.PERMISSION_ERROR) return } self.sendResponseWithResponseCode(200, data: imageData!.data, mimeType: imageData!.mimeType) } } return } else if url.host?.lowercased() == "video" { concurrentQueue.addOperation { service.getVideo(photoId!) { (videoData) in if (videoData == nil) { self.sendErrorResponse(404, error: PhotoLibraryService.PERMISSION_ERROR) return } self.sendResponseWithResponseCode(200, data: videoData!.data, mimeType: videoData!.mimeType) } } return } } } let body = "URI not supported by PhotoLibrary" self.sendResponseWithResponseCode(404, data: body.data(using: String.Encoding.ascii), mimeType: nil) } override func stopLoading() { // do any cleanup here } fileprivate func sendErrorResponse(_ statusCode: Int, error: String) { self.sendResponseWithResponseCode(statusCode, data: error.data(using: String.Encoding.ascii), mimeType: nil) } // Cannot use sendResponseWithResponseCode from CDVURLProtocol, so copied one here. fileprivate func sendResponseWithResponseCode(_ statusCode: Int, data: Data?, mimeType: String?) { var mimeType = mimeType if mimeType == nil { mimeType = "text/plain" } let encodingName: String? = mimeType == "text/plain" ? "UTF-8" : nil let response: CDVHTTPURLResponse = CDVHTTPURLResponse(url: self.request.url!, mimeType: mimeType, expectedContentLength: data?.count ?? 0, textEncodingName: encodingName) response.statusCode = statusCode self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: URLCache.StoragePolicy.notAllowed) if (data != nil) { self.client?.urlProtocol(self, didLoad: data!) } self.client?.urlProtocolDidFinishLoading(self) } class CDVHTTPURLResponse: HTTPURLResponse { var _statusCode: Int = 0 override var statusCode: Int { get { return _statusCode } set { _statusCode = newValue } } override var allHeaderFields: [AnyHashable: Any] { get { return [:] } } } }
mit
b3bda9402eeb1a8fd536a30c8d50a0be
38.937853
178
0.486475
6.109612
false
false
false
false
zhaobin19918183/zhaobinCode
swift_NavigationController/swift_iPad/popViewController.swift
1
4332
// // popViewController.swift // swift_iPad // // Created by Zhao.bin on 16/3/29. // Copyright © 2016年 Zhao.bin. All rights reserved. // import UIKit import AssetsLibrary import Photos protocol popViewControllerDelegate { func popViewControllerPhotosArray(photosImage : UIImage) } class popViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource { @IBOutlet weak var photosCollectionView: UICollectionView! var delegate : popViewControllerDelegate! //资源库管理类 var assetsFetchResults = PHFetchResult() //保存照片集合 var PHIassets = PHImageManager() var asset = PHAsset() var options = PHFetchOptions() var imageManager = PHImageManager() var imageArray:NSMutableArray? var layout = UICollectionViewFlowLayout() var isSelect = false override func viewDidLoad() { photosCollectionView.registerNib(UINib(nibName: "popCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCellID") self.photosCollectionView.collectionViewLayout = layout photosCollectionView.allowsMultipleSelection = true assetsFetchResults = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: nil) } static func collectionSeletctNmuber(number:NSInteger) { print(number) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return assetsFetchResults.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCellID", forIndexPath: indexPath) as? popCollectionViewCell if cell == nil { let nibArray : NSArray = NSBundle.mainBundle().loadNibNamed("popCollectionViewCell", owner:self, options:nil) cell = nibArray.firstObject as? popCollectionViewCell } asset = assetsFetchResults[indexPath.row] as! PHAsset imageManager.requestImageForAsset(asset, targetSize: CGSize.init(width:60, height:40), contentMode: PHImageContentMode.AspectFill, options: nil) { (resultimage, info) in cell?.backgroundImagview.image = resultimage print(cell?.backgroundImagview.image?.size) } // print(cell?.backgroundImagview.image?.size) layout.itemSize = CGSizeMake(90, 65) return cell! } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{ return UIEdgeInsetsMake(5, 5,0, 5) } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) as! popCollectionViewCell cell.backgroundColor = UIColor.greenColor() print("didSelect====\(indexPath.row)") asset = assetsFetchResults[indexPath.row] as! PHAsset imageManager.requestImageForAsset(asset, targetSize:PHImageManagerMaximumSize, contentMode: PHImageContentMode.Default, options: nil) { (resultimage, info) in self.delegate.popViewControllerPhotosArray(resultimage!) } // self.dismissViewControllerAnimated(true, completion: nil) } func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } //didDeselectItemAtIndexPath func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) as! popCollectionViewCell cell.backgroundColor = UIColor.whiteColor() print("didDeselec====\(indexPath.row)") } // override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
901f0d1f06fcfa2bfcfa618bc14ace77
32.372093
178
0.683391
5.857143
false
false
false
false
Dewire/SwiftCommon
SwiftCommon/SequenceType.swift
1
2552
// // SequenceType.swift // SwiftCommon // // Created by Kalle Lindström on 20/01/16. // Copyright © 2016 Dewire. All rights reserved. // import Foundation // MARK: find, any, all public extension Sequence { /** Returns the first element in self for which predicate is true, or nil if no element returns true. Example: ``` let array = [1, 2, 3, 4, 5, 6, 7] array.find { $0 % 2 == 0 } // => 2 ``` */ public func find(_ predicate: (Self.Iterator.Element) -> Bool) -> Self.Iterator.Element? { for e in self { if predicate(e) { return e } } return nil } /** Returns true if the sequence contains an element for which the predicate returns true, otherwise returns false. Example: ``` let array = [1, 2, 3, 4, 5, 6, 7] array.any { $0 > 5 } // => true array.any { $0 > 7 } // => false ``` */ public func any(_ predicate: (Self.Iterator.Element) -> Bool) -> Bool { for element in self { if predicate(element) { return true } } return false } /** Returns true if the predicate returns true for all elements in the sequence, otherwise returns false. Example: ``` let array = ["hello", "world"] array.all { $0.characters.count == 5 } // => true ``` */ public func all(_ predicate: (Self.Iterator.Element) -> Bool) -> Bool { for element in self { if !predicate(element) { return false } } return true } } // MARK: unique public extension Sequence where Iterator.Element: Hashable { /** Returns an array where duplicated elements are removed. The original order is kept. Example: ``` let array = [1, 1, 2, 1, 3] array.unique // => [1, 2, 3] ``` */ public func unique() -> [Iterator.Element] { var buffer: [Iterator.Element] = [] var lookup = Set<Iterator.Element>() for element in self { guard !lookup.contains(element) else { continue } buffer.append(element) lookup.insert(element) } return buffer } } public extension Sequence where Iterator.Element: Equatable { /** Returns an array where duplicated elements are removed. The original order is kept. Example: ``` let array = [1, 1, 2, 1, 3] array.unique // => [1, 2, 3] ``` */ public func unique() -> [Iterator.Element] { var buffer: [Iterator.Element] = [] for element in self { guard !buffer.contains(element) else { continue } buffer.append(element) } return buffer } }
mit
f51b271f895342cd975f3371e53e5287
20.982759
94
0.587843
3.722628
false
false
false
false
JesusAntonioGil/OnTheMap
OnTheMap/Controllers/Location/LocationViewController.swift
1
2239
// // LocationViewController.swift // OnTheMap // // Created by Jesús Antonio Gil on 30/03/16. // Copyright © 2016 Jesús Antonio Gil. All rights reserved. // import UIKit import PKHUD import CoreLocation class LocationViewController: UIViewController { @IBOutlet weak var locationTextField: UITextField! //Injected var controllerAssembly: ControllerAssembly! var studentLocation: StudentLocationStruct! //MARK: LIFE CYCLE override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: ACTIONS @IBAction func onCancelButtonTap(sender: AnyObject) { navigationController?.dismissViewControllerAnimated(true, completion: nil) } @IBAction func onMapButtonTap(sender: AnyObject) { if(locationTextField.text?.isEmpty == true) { HUD.show(.Label("Must enter a Location")) HUD.hide(afterDelay: 2.0) } else { checkAddressString() } } //MARK: PRIVATE private func checkAddressString() { HUD.show(.Progress) let geocoder = CLGeocoder() geocoder.geocodeAddressString(locationTextField.text!) { (placemarks, error) in if(error != nil) { HUD.show(.Label("Could not geocode the address")) HUD.hide(afterDelay: 2.0) } else { HUD.hide() self.pushToLinkViewController(placemarks![0]) } } } private func pushToLinkViewController(placemark: CLPlacemark) { let linkViewController: LinkViewController = controllerAssembly.linkViewController() as! LinkViewController linkViewController.placemark = placemark linkViewController.mapString = locationTextField.text linkViewController.studentLocation = studentLocation navigationController?.pushViewController(linkViewController, animated: true) } } extension LocationViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
0dc0ac4974d22f388030906ca3ae8f33
26.604938
115
0.649374
5.286052
false
false
false
false
the-grid/Disc
DiscTests/Networking/Resources/User/GitHubToken/GetPublicGitHubTokenSpec.swift
1
1442
import Disc import Mockingjay import MockingjayMatchers import Nimble import Quick import Result import Swish class GetPublicGitHubTokenSpec: QuickSpec { override func spec() { describe("getting a public GitHub token") { it("should result in a GitHub token") { let passportToken = "token" let passport = APIClient(token: passportToken) let username = "gridbear" let value = "nijcoqf3h3287f7g" let responseBody = [ "username": username, "token": value ] let githubToken = GitHubToken(username: username, value: value) let matcher = api(.GET, "https://passport.thegrid.io/api/user/github", token: passportToken) let builder = json(responseBody) self.stub(matcher, builder: builder) var responseValue: GitHubToken? var responseError: SwishError? passport.getPublicGitHubToken() { result in responseValue = result.value responseError = result.error } expect(responseValue).toEventually(equal(githubToken)) expect(responseError).toEventually(beNil()) } } } }
mit
d2ce9dd7e6a3c48a42432cd4694c94ce
32.534884
108
0.519417
5.610895
false
false
false
false
vladimirkofman/TableTie
TableTie/Section.swift
1
571
// // Section.swift // TableTie // // Created by Vladimir Kofman on 21/04/2017. // Copyright © 2017 Vladimir Kofman. All rights reserved. // import Foundation /** Stores the information about a section in a UITableView */ public struct Section { /// header title let header: String? /// footer title let footer: String? /// rows let rows: [AnyRow] public init(_ header: String? = nil, footer: String? = nil, _ rows: [AnyRow]) { self.header = header self.footer = footer self.rows = rows } }
mit
858dc4d2df6f54e324bf194f646e43f3
18.655172
83
0.6
3.877551
false
false
false
false
socialbanks/ios-wallet
SocialWallet/HistoryVC.swift
1
3864
// // HistoryVC.swift // SocialWallet // // Created by Mauricio de Oliveira on 5/16/15. // Copyright (c) 2015 SocialBanks. All rights reserved. // import UIKit import Parse class HistoryVC: BaseTableVC { var wallet:Wallet? var items:Array<Transaction> = [] func fetchData() { /*APIManager.sharedInstance.getBalances { (results, error) -> Void in let result:NSArray = results!["result"] as! NSArray self.items = [] for dict in result { self.items.append(SocialBank(dictionary: dict as! NSDictionary)!) } self.tableView.reloadData() println("end") }*/ items = [] APIManager.sharedInstance.getTransactionsFromWallet(wallet!, completion: { (results) -> Void in var i = 0 for transaction in results { i = i+1 println(i) if(transaction.getSenderWallet() != nil && self.wallet!.isEqual(transaction.getSenderWallet()!)) { transaction.isSender = true } self.items.append(transaction) } self.tableView.reloadData() }) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) fetchData() } //MARK: - UITableView Delegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:TransactionCell = self.tableView.dequeueReusableCellWithIdentifier("TransactionCell") as! TransactionCell //cell.loadFromTransaction(transaction) let transaction = self.items[indexPath.row] cell.loadFromTransaction(transaction) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 64 } } class TransactionCell: UITableViewCell { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var operationLabel: UILabel! @IBOutlet weak var amountLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! func loadFromTransaction(object:Transaction) { let creation:NSDate = object.createdAt! let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle dateFormatter.timeZone = NSTimeZone.localTimeZone() self.dateLabel.text = dateFormatter.stringFromDate(creation) self.timeLabel.text = "" let major:Int = object.getValue()/100 let minor:Int = object.getValue() % 100 if minor < 10 { self.amountLabel.text = major.description + "," + "0" + minor.description }else{ self.amountLabel.text = major.description + "," + minor.description } if(object.isSender) { operationLabel.text = "-" descriptionLabel.text = object.getSenderDescription() operationLabel.textColor = UIColor.redColor() amountLabel.textColor = UIColor.redColor() }else{ operationLabel.text = "+" descriptionLabel.text = object.getReceiverDescription() operationLabel.textColor = UIColor.greenColor() amountLabel.textColor = UIColor.greenColor() } } }
mit
983059aaf05db662c4128c57263a1fcf
30.169355
122
0.614389
5.322314
false
false
false
false
Bizzi-Body/Bizzi-Body-ParseTutorialPart3-Complete-Solution
SignUpInViewController.swift
2
3382
// // SignUpInViewController.swift // ParseTutorial // // Created by Ian Bradbury on 10/02/2015. // Copyright (c) 2015 bizzi-body. All rights reserved. // import UIKit class SignUpInViewController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var message: UILabel! @IBOutlet weak var emailAddress: UITextField! @IBOutlet weak var password: UITextField! @IBAction func signUp(sender: AnyObject) { // Build the terms and conditions alert let alertController = UIAlertController(title: "Agree to terms and conditions", message: "Click I AGREE to signal that you agree to the End User Licence Agreement.", preferredStyle: UIAlertControllerStyle.Alert ) alertController.addAction(UIAlertAction(title: "I AGREE", style: UIAlertActionStyle.Default, handler: { alertController in self.processSignUp()}) ) alertController.addAction(UIAlertAction(title: "I do NOT agree", style: UIAlertActionStyle.Default, handler: nil) ) // Display alert self.presentViewController(alertController, animated: true, completion: nil) } @IBAction func signIn(sender: AnyObject) { activityIndicator.hidden = false activityIndicator.startAnimating() var userEmailAddress = emailAddress.text userEmailAddress = userEmailAddress.lowercaseString var userPassword = password.text PFUser.logInWithUsernameInBackground(userEmailAddress, password:userPassword) { (user: PFUser?, error: NSError?) -> Void in if user != nil { dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("signInToNavigation", sender: self) } } else { self.activityIndicator.stopAnimating() if let message: AnyObject = error!.userInfo!["error"] { self.message.text = "\(message)" } } } } override func viewDidLoad() { super.viewDidLoad() activityIndicator.hidden = true activityIndicator.hidesWhenStopped = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func processSignUp() { var userEmailAddress = emailAddress.text var userPassword = password.text // Ensure username is lowercase userEmailAddress = userEmailAddress.lowercaseString // Add email address validation // Start activity indicator activityIndicator.hidden = false activityIndicator.startAnimating() // Create the user var user = PFUser() user.username = userEmailAddress user.password = userPassword user.email = userEmailAddress user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in if error == nil { dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("signInToNavigation", sender: self) } } else { self.activityIndicator.stopAnimating() if let message: AnyObject = error!.userInfo!["error"] { self.message.text = "\(message)" } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
27c4bc71ff2c7e58d2bf9ba195a52cfc
25.217054
103
0.719397
4.30828
false
false
false
false
maletzt/Alien-Adventure
Alien Adventure/Settings.swift
1
1043
// // Settings.swift // Alien Adventure // // Created by Jarrod Parkes on 9/18/15. // Copyright © 2015 Udacity. All rights reserved. // import UIKit // MARK: - Settings struct Settings { // MARK: Common struct Common { static let GameDataURL = NSBundle.mainBundle().URLForResource("GameData", withExtension: "plist")! static let Font = "Superclarendon-Italic" static let FontColor = UIColor.whiteColor() static var Level = 2 static var ShowBadges = false static let RequestsToSkip = 0 } // MARK: Dialogue (Set by UDDataLoader) struct Dialogue { static var StartingDialogue = "" static var RequestingDialogue = "" static var TransitioningDialogue = "" static var WinningDialogue = "" static var LosingDialogue = "" } // MARK: Names struct Names { static let Hero = "Hero" static let Background = "Background" static let Treasure = "Treasure" } }
mit
3489970d1145f32abb200c22b29cc1d5
23.232558
106
0.597889
4.530435
false
false
false
false
Drusy/auvergne-webcams-ios
AuvergneWebcams/CGSizeExtension.swift
1
1236
// // CGSizeExtension.swift // AuvergneWebcams // // Created by Drusy on 20/02/2017. // // import Foundation extension CGSize { static func aspectFit(aspectRatio : CGSize, boundingSize: CGSize) -> CGSize { var boundingSize = boundingSize let mW = boundingSize.width / aspectRatio.width; let mH = boundingSize.height / aspectRatio.height; if( mH < mW ) { boundingSize.width = boundingSize.height / aspectRatio.height * aspectRatio.width; } else if( mW < mH ) { boundingSize.height = boundingSize.width / aspectRatio.width * aspectRatio.height; } return boundingSize } static func aspectFill(aspectRatio :CGSize, minimumSize: CGSize) -> CGSize { var minimumSize = minimumSize let mW = minimumSize.width / aspectRatio.width; let mH = minimumSize.height / aspectRatio.height; if( mH > mW ) { minimumSize.width = minimumSize.height / aspectRatio.height * aspectRatio.width; } else if( mW > mH ) { minimumSize.height = minimumSize.width / aspectRatio.width * aspectRatio.height; } return minimumSize } }
apache-2.0
75998ad157edaa5ef45cdc5dac089c77
29.146341
94
0.607605
4.629213
false
false
false
false
RoverPlatform/rover-ios-beta
Sources/Models/Row.swift
2
4175
// // Row.swift // Rover // // Created by Sean Rucker on 2017-10-19. // Copyright © 2017 Rover Labs Inc. All rights reserved. // public struct Row { public var background: Background public var blocks: [Block] public var height: Height public var id: String public var name: String public var keys: [String: String] public var tags: [String] public init(background: Background, blocks: [Block], height: Height, id: String, name: String, keys: [String: String], tags: [String]) { self.background = background self.blocks = blocks self.height = height self.id = id self.name = name self.keys = keys self.tags = tags } } // MARK: Decodable extension Row: Decodable { enum CodingKeys: String, CodingKey { case background case blocks case height case id case name case keys case tags } enum BlockType: Decodable { case barcodeBlock case buttonBlock case imageBlock case rectangleBlock case textBlock case webViewBlock case textPollBlock case imagePollBlock enum CodingKeys: String, CodingKey { case typeName = "__typename" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let typeName = try container.decode(String.self, forKey: .typeName) switch typeName { case "BarcodeBlock": self = .barcodeBlock case "ButtonBlock": self = .buttonBlock case "ImageBlock": self = .imageBlock case "RectangleBlock": self = .rectangleBlock case "TextBlock": self = .textBlock case "WebViewBlock": self = .webViewBlock case "TextPollBlock": self = .textPollBlock case "ImagePollBlock": self = .imagePollBlock default: throw DecodingError.dataCorruptedError(forKey: CodingKeys.typeName, in: container, debugDescription: "Expected one of BarcodeBlock, ButtonBlock, ImageBlock, RectangleBlock, TextBlock, WebViewBlock, TextPollBlock, ImagePollBlock – found \(typeName)") } } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) background = try container.decode(Background.self, forKey: .background) height = try container.decode(Height.self, forKey: .height) id = try container.decode(String.self, forKey: .id) name = try container.decode(String.self, forKey: .name) keys = try container.decode([String: String].self, forKey: .keys) tags = try container.decode([String].self, forKey: .tags) blocks = [Block]() let blockTypes = try container.decode([BlockType].self, forKey: .blocks) var blocksContainer = try container.nestedUnkeyedContainer(forKey: .blocks) while !blocksContainer.isAtEnd { let block: Block switch blockTypes[blocksContainer.currentIndex] { case .barcodeBlock: block = try blocksContainer.decode(BarcodeBlock.self) case .buttonBlock: block = try blocksContainer.decode(ButtonBlock.self) case .imageBlock: block = try blocksContainer.decode(ImageBlock.self) case .rectangleBlock: block = try blocksContainer.decode(RectangleBlock.self) case .textBlock: block = try blocksContainer.decode(TextBlock.self) case .webViewBlock: block = try blocksContainer.decode(WebViewBlock.self) case .textPollBlock: block = try blocksContainer.decode(TextPollBlock.self) case .imagePollBlock: block = try blocksContainer.decode(ImagePollBlock.self) } blocks.append(block) } } }
mit
d7ad3f0f3620ce55b306df30f21eab57
34.347458
265
0.590746
4.838747
false
false
false
false
ryanipete/AmericanChronicle
Tests/UnitTests/FakeSessionManager.swift
1
3676
@testable import AmericanChronicle import Alamofire import Foundation final class FakeSessionManager: SessionManagerProtocol { // MARK: SessionManagerProtocol conformance func beginRequest(_ request: URLRequestConvertible, completion: @escaping (DataResponse<Data>) -> Void) -> RequestProtocol { let returnedRequest = FakeRequest() beginRequest_recorder.record((request, completion), returnVal: returnedRequest) return returnedRequest } func download(_ url: URLConvertible, to destination: DownloadRequest.DownloadFileDestination?, responseQueue: DispatchQueue?, completion: @escaping (DefaultDownloadResponse) -> Void) -> RequestProtocol { let returnedRequest = FakeRequest() download_recorder.record((url, destination, responseQueue, completion), returnVal: returnedRequest) return returnedRequest } func cancel(_ request: RequestProtocol) { cancel_recorder.record(request) } // MARK: Test stuff // - beginRequest(...) typealias BeginRequestParams = (request: URLRequestConvertible, completion: (DataResponse<Data>) -> Void) let beginRequest_recorder = InvocationRecorder<BeginRequestParams, FakeRequest>(name: "beginRequest") func fake_beginRequest_response(_ response: DataResponse<Data>) { for call in beginRequest_recorder.callLog { call.params.completion(response) } } // - download(...) typealias DownloadParams = ( url: URLConvertible, destination: DownloadRequest.DownloadFileDestination?, responseQueue: DispatchQueue?, completion: (DefaultDownloadResponse) -> Void) let download_recorder = InvocationRecorder<DownloadParams, FakeRequest>(name: "download") func fake_download_success() { let fileURL = URL(fileURLWithPath: "") for call in download_recorder.callLog { let remoteURL: URL do { remoteURL = try call.params.url.asURL() } catch { fatalError() } let response = HTTPURLResponse(url: remoteURL, statusCode: 200, httpVersion: nil, headerFields: nil)! _ = call.params.destination?(fileURL, response) let downloadResponse = DefaultDownloadResponse(request: nil, response: response, temporaryURL: nil, destinationURL: fileURL, resumeData: nil, error: nil) call.params.completion(downloadResponse) } } func fake_download_failure(_ error: Error) { for call in download_recorder.callLog { let downloadResponse = DefaultDownloadResponse(request: nil, response: nil, temporaryURL: nil, destinationURL: nil, resumeData: nil, error: error) call.params.completion(downloadResponse) } } // - cancel(...) let cancel_recorder = InvocationRecorder<RequestProtocol, Void>(name: "cancel") }
mit
57f6f3761a96890de474528cc77aea50
40.303371
128
0.538085
6.348877
false
false
false
false
MenloHacks/ios-app
Menlo Hacks/Pods/PusherSwift/Sources/PusherChannel.swift
1
4954
import Foundation public enum PusherChannelType { case `private` case presence case normal public init(name: String) { self = Swift.type(of: self).type(forName: name) } public static func type(forName name: String) -> PusherChannelType { if (name.components(separatedBy: "-")[0] == "presence") { return .presence } else if (name.components(separatedBy: "-")[0] == "private") { return .private } else { return .normal } } public static func isPresenceChannel(name: String) -> Bool { return PusherChannelType(name: name) == .presence } } @objcMembers open class PusherChannel: NSObject { open var eventHandlers: [String: [EventHandler]] = [:] open var subscribed = false open let name: String open weak var connection: PusherConnection? open var unsentEvents = [PusherEvent]() open let type: PusherChannelType public var auth: PusherAuth? /** Initializes a new PusherChannel with a given name and conenction - parameter name: The name of the channel - parameter connection: The connection that this channel is relevant to - parameter auth: A PusherAuth value if subscription is being made to an authenticated channel without using the default auth methods - returns: A new PusherChannel instance */ public init(name: String, connection: PusherConnection, auth: PusherAuth? = nil) { self.name = name self.connection = connection self.auth = auth self.type = PusherChannelType(name: name) } /** Binds a callback to a given event name, scoped to the PusherChannel the function is called on - parameter eventName: The name of the event to bind to - parameter callback: The function to call when a message is received with the relevant channel and event names - returns: A unique callbackId that can be used to unbind the callback at a later time */ @discardableResult open func bind(eventName: String, callback: @escaping (Any?) -> Void) -> String { let randomId = UUID().uuidString let eventHandler = EventHandler(id: randomId, callback: callback) if self.eventHandlers[eventName] != nil { self.eventHandlers[eventName]?.append(eventHandler) } else { self.eventHandlers[eventName] = [eventHandler] } return randomId } /** Unbinds the callback with the given callbackId from the given eventName, in the scope of the channel being acted upon - parameter eventName: The name of the event from which to unbind - parameter callbackId: The unique callbackId string used to identify which callback to unbind */ open func unbind(eventName: String, callbackId: String) { if let eventSpecificHandlers = self.eventHandlers[eventName] { self.eventHandlers[eventName] = eventSpecificHandlers.filter({ $0.id != callbackId }) } } /** Unbinds all callbacks from the channel */ open func unbindAll() { self.eventHandlers = [:] } /** Unbinds all callbacks for the given eventName from the channel - parameter eventName: The name of the event from which to unbind */ open func unbindAll(forEventName eventName: String) { self.eventHandlers[eventName] = [] } /** Calls the appropriate callbacks for the given eventName in the scope of the acted upon channel - parameter name: The name of the received event - parameter data: The data associated with the received message */ open func handleEvent(name: String, data: String) { if let eventHandlerArray = self.eventHandlers[name] { let jsonize = connection?.options.attemptToReturnJSONObject ?? true for eventHandler in eventHandlerArray { eventHandler.callback(jsonize ? connection?.getEventDataJSON(from: data) : data) } } } /** If subscribed, immediately call the connection to trigger a client event with the given eventName and data, otherwise queue it up to be triggered upon successful subscription - parameter eventName: The name of the event to trigger - parameter data: The data to be sent as the message payload */ open func trigger(eventName: String, data: Any) { if subscribed { connection?.sendEvent(event: eventName, data: data, channel: self) } else { unsentEvents.insert(PusherEvent(name: eventName, data: data), at: 0) } } } public struct EventHandler { let id: String let callback: (Any?) -> Void } public struct PusherEvent { public let name: String public let data: Any }
mit
92a5fc5311bd6f53f4429b6273b83932
33.402778
104
0.638272
4.890424
false
false
false
false
apiaryio/polls-app
Polls/AppDelegate.swift
2
1114
// // AppDelegate.swift // Polls // // Created by Kyle Fuller on 01/04/2015. // Copyright (c) 2015 Apiary. All rights reserved. // import UIKit #if SNAPSHOT import SimulatorStatusMagic #endif @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if let splitViewController = window?.rootViewController as? UISplitViewController { if UIDevice.currentDevice().userInterfaceIdiom == .Pad { splitViewController.preferredDisplayMode = .AllVisible } if let navigationController = splitViewController.viewControllers.first as? UINavigationController, viewController = navigationController.topViewController as? QuestionListViewController { splitViewController.delegate = viewController } } #if SNAPSHOT let statusBarManager = SDStatusBarManager.sharedInstance() statusBarManager.carrierName = "Apiary" statusBarManager.enableOverrides() #endif return true } }
mit
cdce2abe8d8436e2ce0a1e2594e9df89
27.564103
125
0.749551
5.181395
false
false
false
false
immustard/MSTTools_Swift
MSTTools_Swift/Categories/UIImageMST.swift
1
13406
// // UIImageMST.swift // MSTTools_Swift // // Created by 张宇豪 on 2017/6/7. // Copyright © 2017年 张宇豪. All rights reserved. // import UIKit fileprivate func DegreesToRadians(_ degrees: CGFloat) -> CGFloat { return degrees * CGFloat.pi / 180 } fileprivate func RadiansToDegrees(_ radians: CGFloat) -> CGFloat { return radians * 180 / CGFloat.pi } extension UIImage { /// 从资源文件中获取图像 /// /// - Parameter fileName: 文件名称 /// - Returns: 图片 public class func mst_newImageFromResource(fileName: String) -> UIImage? { let imageFile: String = "\(String(describing: Bundle.main.resourcePath))/\(fileName)" var image: UIImage? image = UIImage(contentsOfFile: imageFile) return image } /// 根据颜色创建图片颜色 /// /// - Parameter color: 颜色 /// - Returns: 返回 1*1 的图片 public class func mst_createImage(color: UIColor) -> UIImage { let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context: CGContext = UIGraphicsGetCurrentContext()! context.setFillColor(color.cgColor) context.fill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } /// 截取View为图片 /// /// - Parameter view: 被截取的View /// - Returns: 截取图片 public class func mst_image(view: UIView) -> UIImage { UIGraphicsBeginImageContext(view.bounds.size) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } /// 根据 rect 截取图片中的部分 /// /// - Parameter rect: 截取区域 /// - Returns: 截取图片 public func mst_image(rect: CGRect) -> UIImage { let imageRef: CGImage = cgImage!.cropping(to: rect)! return UIImage(cgImage: imageRef) } /// 等比例对图片进行缩放至最小尺寸 /// /// - Parameter targetSize: 目标尺寸 /// - Returns: 缩放后图片 public func mst_imageByScalingProportionally(toMinimumSize targetSize: CGSize) -> UIImage? { var newImage: UIImage? let width: CGFloat = size.width let height: CGFloat = size.height let targetWidth: CGFloat = targetSize.width let targetHeight: CGFloat = targetSize.height var scaleFactor: CGFloat = 0 var scaledWidth: CGFloat = targetWidth var scaledHeight: CGFloat = targetHeight var thumbnailPoint: CGPoint = CGPoint.zero if (!size.equalTo(targetSize)) { let widthFactor: CGFloat = targetWidth / width let heightFactor: CGFloat = targetHeight / height if (widthFactor > height) { scaleFactor = widthFactor } else { scaleFactor = heightFactor } scaledWidth = width * scaleFactor scaledHeight = height * scaleFactor if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5 } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5 } } UIGraphicsBeginImageContext(targetSize) var thumbnailRect: CGRect = CGRect.zero thumbnailRect.origin = thumbnailPoint thumbnailRect.size.width = scaledWidth thumbnailRect.size.height = scaledHeight draw(in: thumbnailRect) newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if (newImage == nil) { print("Could not scale image to minimum size.") } return newImage } /// 等比例对图片缩放至指定尺寸 /// /// - Parameter targetSize: 目标尺寸 /// - Returns: 缩放后图片 public func mst_imageByScalingProportionally(toSize targetSize: CGSize) -> UIImage? { var newImage: UIImage? let width: CGFloat = size.width let height: CGFloat = size.height let targetWidth: CGFloat = targetSize.width let targetHeight: CGFloat = targetSize.height var scaleFactor: CGFloat = 0.0 var scaledWidth: CGFloat = targetWidth var scaledHeight: CGFloat = targetHeight var thumbnailPoint: CGPoint = CGPoint.zero if (!size.equalTo(targetSize)) { let widthFactor: CGFloat = targetWidth / width let heightFactor: CGFloat = targetHeight / height if (widthFactor < heightFactor) { scaleFactor = widthFactor } else { scaleFactor = heightFactor } scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; if (widthFactor < heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor > heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } UIGraphicsBeginImageContext(targetSize); var thumbnailRect: CGRect = CGRect.zero thumbnailRect.origin = thumbnailPoint thumbnailRect.size.width = scaledWidth thumbnailRect.size.height = scaledHeight draw(in: thumbnailRect) newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if (newImage == nil) { print("Could not scale image to size.") } return newImage } /// 将图片压缩至指定宽度 /// /// - Parameter dedineWidth: 目标宽度 /// - Returns: 压缩后图片 public func mst_imageCompress(width defineWidth: CGFloat) -> UIImage? { var newImage: UIImage? let width: CGFloat = self.size.width let height: CGFloat = self.size.height let targetWidth: CGFloat = defineWidth let targetHeight: CGFloat = height / (width / targetWidth) let size = CGSize(width: targetWidth, height: targetHeight) var scaleFactor: CGFloat = 0.0 var scaledWidth: CGFloat = targetWidth var scaledHeight: CGFloat = targetHeight var thumbnailPoint: CGPoint = CGPoint.zero if (!self.size.equalTo(size)) { let widthFactor: CGFloat = targetWidth / width let heightFactor: CGFloat = targetHeight / height if (widthFactor > heightFactor) { scaleFactor = widthFactor } else{ scaleFactor = heightFactor } scaledWidth = width * scaleFactor scaledHeight = height * scaleFactor if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5 } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5 } } UIGraphicsBeginImageContext(size) var thumbnailRect: CGRect = CGRect.zero thumbnailRect.origin = thumbnailPoint thumbnailRect.size.width = scaledWidth thumbnailRect.size.height = scaledHeight draw(in: thumbnailRect) newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if (newImage == nil) { print("Compress image for width fail.") } return newImage } /// 将图片进行旋转(角度制) /// /// - Parameter degrees: 旋转角度 /// - Returns: 旋转后图片 public func mst_imageRotated(degrees: CGFloat) -> UIImage { // 首先计算旋转之后的视图的尺寸 let rotatedViewBox: UIView = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let t: CGAffineTransform = CGAffineTransform(rotationAngle: DegreesToRadians(degrees)) rotatedViewBox.transform = t let rotatedSize = rotatedViewBox.frame.size UIGraphicsBeginImageContext(rotatedSize) let bitmap: CGContext = UIGraphicsGetCurrentContext()! // 将定点移动到图片中间 bitmap.translateBy(x: rotatedSize.width/2, y: rotatedSize.height/2) // 旋转 bitmap.rotate(by: DegreesToRadians(degrees)) // 得到旋转之后的图片 bitmap.scaleBy(x: 1, y: -1) bitmap.draw(cgImage!, in: CGRect(x: -size.width/2, y: -size.height/2, width: size.width, height: size.height)) let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } /// 将图片进行旋转(角度制) /// /// - Parameter radians: 旋转角度 /// - Returns: 旋转后图片 public func mst_imageRotated(radians: CGFloat) -> UIImage { return mst_imageRotated(degrees: RadiansToDegrees(radians)) } /// 为图片添加毛玻璃效果 /// /// - Parameter blur: 效果参数 /// - Returns: 结果图片 public func mst_coreBlur(blurNumber blur: CGFloat) -> UIImage { let context: CIContext = CIContext(options: nil) let inputImage: CIImage = CIImage(cgImage: cgImage!) // 设置filter let filter: CIFilter = CIFilter(name: "CIGaussianBlur")! filter.setValue(inputImage, forKey: kCIInputImageKey) filter.setValue(blur, forKey: "inputRadius") // 模糊图片 let result: CIImage = filter.value(forKey: kCIOutputImageKey) as! CIImage let outImage:CGImage = context.createCGImage(result, from: result.extent)! let blurImage: UIImage = UIImage(cgImage: outImage) return blurImage } /// 根据指定点对图片进行拉伸 /// /// - Parameter point: 目标点 /// - Returns: 拉伸图片 public func mst_stretchImage(capPoint point: CGPoint) -> UIImage { let streImage: UIImage = stretchableImage(withLeftCapWidth: Int(point.x), topCapHeight: Int(point.y)) return streImage } /// 将图片截取为正方形 /// /// - Returns: 截取后图片 public func mst_cropedImageToSquare() -> UIImage { var cropRect: CGRect! if size.height > size.width { cropRect = CGRect(x: 0, y: (size.height - size.width)/2, width: size.width, height: size.width) } else { cropRect = CGRect(x: (size.width - size.height)/2, y: 0, width: size.height, height: size.height) } let imageRef: CGImage = (cgImage?.cropping(to: cropRect))! let cropImage: UIImage = UIImage(cgImage: imageRef) return cropImage } /// 修正图片方向 /// /// - Returns: 修正后图片 public func mst_fixOrientation() -> UIImage { guard imageOrientation != .up else { return self } var transform: CGAffineTransform = CGAffineTransform.identity switch imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: size.width, y: size.height) transform = transform.rotated(by: CGFloat.pi) case .left, .leftMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.rotated(by: CGFloat.pi/2) case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: size.height) transform = transform.rotated(by: -CGFloat.pi/2) default: break } switch imageOrientation { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform.scaledBy(x: -1, y: 1) case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: size.height, y: 0) transform = transform.scaledBy(x: -1, y: 1) default: break } let ctx: CGContext = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: (cgImage?.bitsPerComponent)!, bytesPerRow: 0, space: (cgImage?.colorSpace)!, bitmapInfo: (cgImage?.bitmapInfo.rawValue)!)! ctx.concatenate(transform) switch imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: ctx.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) default: ctx.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) } let cgImg: CGImage = ctx.makeImage()! let img: UIImage = UIImage(cgImage: cgImg) return img } }
mit
c315cd016243a58250c7f36eb5a655e6
32.206718
240
0.5812
4.919985
false
false
false
false
freshteapot/learnalist-ios
learnalist-ios/learnalist-ios/MyListView.swift
1
2087
import UIKit import Signals class MyListView: UIView, UITableViewDataSource, UITableViewDelegate { var tableView: UITableView! var selectedIndexPath: IndexPath? var items = [AlistSummary]() let onTapOnTableRow = Signal<(uuid:String, listType:String)>() override init (frame : CGRect) { super.init(frame : frame) self.backgroundColor = UIColor.red tableView = UITableView(frame: frame, style: .plain) tableView.dataSource = self tableView.delegate = self tableView.alwaysBounceVertical = false tableView.rowHeight = UITableViewAutomaticDimension; tableView.estimatedRowHeight = 44; tableView.sectionHeaderHeight = UITableViewAutomaticDimension; tableView.estimatedSectionHeaderHeight = 30; tableView.sectionFooterHeight = UITableViewAutomaticDimension; tableView.estimatedSectionFooterHeight = 30; tableView.register(UITableViewCell.self, forCellReuseIdentifier: "NameCell") addSubview(tableView) tableView.snp.makeConstraints{(make) -> Void in make.edges.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "NameCell")! as UITableViewCell cell.textLabel?.text = items[indexPath.row].title return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ selectedIndexPath = indexPath // tableView.deselectRow(at: indexPath as IndexPath, animated: false) self.onTapOnTableRow.fire((uuid: items[indexPath.row].uuid, items[indexPath.row].listType)) } func setItems(items: [AlistSummary]) { self.items = items tableView.reloadData() } }
mit
a0416e3329ad2e07dc2b4e0071d9bf44
33.213115
100
0.692861
5.406736
false
false
false
false
relayr/apple-iot-smartphone
IoT/ios/sources/GraphView.swift
1
17721
import UIKit import Metal import simd import Utilities import ReactiveCocoa class GraphView : UIView { // MARK: Definitions /// Stores the state of the uniforms of the graph view. private class Uniforms { /// Uniform related to the whole graph view. struct ViewUniform { /// The size of the view. var size : float2 /// The size of the left text column. var leftColumnSize : float2 /// The size of the actual graph (mesh). var meshSize : float2 /// The size of the right text column. var rightColumnSize : float2 /// The time (in seconds) that the graph will show. var timeWindow : Float /// The current time ("now") express on the graph. var time : Float init(currentTime time: Float, timeWindow: Float = 5, size: CGSize = CGSize(width: 100, height: 100), graphWidthMultipler mult: Float = 0.8, lineWidth: Float = 1) { (self.time, self.timeWindow) = (time, timeWindow) self.size = float2(Float(size.width), Float(size.height)) self.meshSize = float2(mult*self.size.x, self.size.y - lineWidth) self.leftColumnSize = float2(0.5*(self.size.x-self.meshSize.x), self.meshSize.y) self.rightColumnSize = self.leftColumnSize } } /// Uniform referencing axis data. struct AxisUniform { /// The number of horizontal and vertical lines (in that order). var numLines : float2 /// The line width on view coordinates. var lineWidth : Float } /// Uniform referencing samples data. struct SamplesUniform { /// The limits being displayed on the y axis of the graph [min, max]. var boundaries : float2 /// The radius of the triangle on view coordinates (not normalized): outter, inner var dotRadius : float2 /// The union-line width. var lineWidth : Float /// The number of triangles that the dot is made of. var trianglesPerDot : UInt16 /// The number of float values per sample (not including the timestamp) var valuesPerSample : UInt16 } /// Controls whether a frame should be rendered. let renderSemaphore : dispatch_semaphore_t /// The amount of concurrent renders (and thus the amount of uniform instances) that this view has. let concurrentRenders : Int /// The current index for uniforms (depends on the concurrent renders number). var currentIndex : Int /// The uniform data related to the whole graph view. var view : ViewUniform /// The uniform data related to the axis of the graph. var axis : AxisUniform /// The uniform data related to how samples are displayed. var samples : SamplesUniform /// Creates the uniform information data holder. /// - parameter currentTime: The value for time now! (in seconds) /// - parameter numAxisLInes: The number of axis lines that the graph should display. /// - parameter numRenders: The number of concurrent renders that can be calculated on the GPU. /// - parameter valueLimits: The limits that the *Y* axis will be bound to. init(withCurrentTime currentTime: Float, numAxisLines: (horizontal: Float, vertical: Float), concurrentRenders numRenders : Int = 3, valueLimits: (min: Float, max: Float) = (-1, 1)) { renderSemaphore = dispatch_semaphore_create(numRenders) concurrentRenders = numRenders currentIndex = -1 view = ViewUniform(currentTime: currentTime) axis = AxisUniform(numLines: float2(numAxisLines.horizontal, numAxisLines.vertical), lineWidth: 1) samples = SamplesUniform(boundaries: float2(valueLimits.min, valueLimits.max), dotRadius: [1, 0.9], lineWidth: 1, trianglesPerDot: 20, valuesPerSample: 1) } /// Updates the values stored by this instance and returns boolean flags specifying whether the values had changed (and thus the rendering system should update its values too). func update(withSize viewSize: CGSize, scaleFactor: Float) { let time = GraphRenderData.timeNow let needsResize = Float(viewSize.width) != view.size.x || Float(viewSize.height) != view.size.y if needsResize { let lineWidth : Float = 1 axis.lineWidth = lineWidth * scaleFactor view = ViewUniform(currentTime: time, timeWindow: 5, size: viewSize, graphWidthMultipler: 0.8, lineWidth: axis.lineWidth) let outterRadius = 6 * lineWidth * scaleFactor samples.dotRadius = [outterRadius, 0.9*outterRadius] samples.lineWidth = axis.lineWidth } else { view.time = time } currentIndex = (currentIndex+1) % concurrentRenders } } override static func layerClass() -> AnyClass { return CAMetalLayer.self } // MARK: Properties /// CPU Uniforms storing the information used by the shaders. private var uniforms = Uniforms(withCurrentTime: GraphRenderData.timeNow, numAxisLines: (11, 10)) /// GPU Uniforms storing the information used by the shaders. private var buffers : (view : MTLBuffer, axis : MTLBuffer, samples : MTLBuffer, colors : MTLBuffer)! /// Textures containing the labels for the vertical axis (they will contain the number of horizontal lines minus 2). private var textures : [MTLTexture?]? /// If it exists, there is a block trying to generate all the texture labels private var textureGenerator : dispatch_block_t? /// ReactiveCocoa disposable to stop the *display refresher*. private var refreshDisposable : Disposable? /// The associated data needed for rendering. private var data : (sampler: SystemSampler, meaning: GraphMeaning, state: GraphRenderState)? /// Convenience access to the `CAMetalLayer`. private var metalLayer : CAMetalLayer { return layer as! CAMetalLayer } /// The time window (in seconds) that the graph shows. var timeWindow : Int { get { return Int(uniforms.view.timeWindow) } set { guard newValue > 0 else { return } uniforms.view.timeWindow = Float(timeWindow) } } /// Sets the render variables needed for displaying this graph view. /// - parameter renderState: Render state shared with other graph views. /// - parameter samplerType: The type of data being displayed. /// - parameter graphMeaning: The buffers containing the data to be displayed. func renderData(withState renderState: GraphRenderState, samplerType: SystemSampler, graphMeaning: GraphMeaning) { // Check whether the shared render state has changed and new buffers needs to be generated. if data == nil || data!.state != renderState { refreshDisposable?.dispose() (metalLayer.device, metalLayer.pixelFormat) = (renderState.device, .BGRA8Unorm) let concurrentRenders = uniforms.concurrentRenders let viewBuf = renderState.device.newBufferWithLength(concurrentRenders*strideofValue(uniforms.view), options: .CPUCacheModeWriteCombined) viewBuf.label = "Graph: View Uniforms" let axisBuf = renderState.device.newBufferWithLength(concurrentRenders*strideofValue(uniforms.axis), options: .CPUCacheModeWriteCombined) axisBuf.label = "Graph: Axis Uniforms" let samplesBuf = renderState.device.newBufferWithLength(concurrentRenders*strideofValue(uniforms.samples), options: .CPUCacheModeWriteCombined) samplesBuf.label = "Graph: Sample Uniforms" let colors = [Colors.Grid.float4, Colors.Green.float4, Colors.Blue.float4, Colors.Red.float4] let colorsBuf = renderState.device.newBufferWithBytes(colors, length: sizeof(float4)*colors.count, options: .CPUCacheModeWriteCombined) colorsBuf.label = "Graph: Colors Uniforms" buffers = (viewBuf, axisBuf, samplesBuf, colorsBuf) uniforms.samples.trianglesPerDot = renderState.numTrianglesPerDot if let _ = window { refreshDisposable = renderState.displayRefresh.signal.observeNext { [weak self] in self?.render($0) } } else { refreshDisposable = nil } } // Check whether meaning has changed and new texture data need to be generated. if data == nil || data!.meaning != graphMeaning { if let generator = textureGenerator { dispatch_block_cancel(generator) } textures = nil let limits = graphMeaning.limits uniforms.samples.boundaries = float2(limits.min, limits.max) uniforms.samples.valuesPerSample = UInt16(graphMeaning.valuesPerSample) } data = (samplerType, graphMeaning, renderState) } override func didMoveToWindow() { super.didMoveToWindow() guard let window = self.window else { refreshDisposable?.dispose(); if let generator = textureGenerator { dispatch_block_cancel(generator) } return refreshDisposable = nil } metalLayer.contentsScale = window.screen.nativeScale guard let renderData = data else { return } if refreshDisposable == nil { refreshDisposable = renderData.state.displayRefresh.signal.observeNext { [weak self] in self?.render($0) } } } /// It renders a screen *full* of content. /// - warning: This method should always be called from the main thread. /// - parameter refreshData: Variables referencing the time of refresh triggering. func render(refreshData: DisplayRefresh.Value) { let unis = uniforms // Check first if I can get hold of the semaphore; If not, just skip the frame. guard let renderData = self.data where dispatch_semaphore_wait(unis.renderSemaphore, DISPATCH_TIME_NOW) == 0 else { return } // If there are no shared render state or there is no access to a drawable, return without doing any work. guard let drawable = metalLayer.nextDrawable() else { dispatch_semaphore_signal(unis.renderSemaphore); return } let drawableSize = metalLayer.drawableSize let scaleFactor = metalLayer.contentsScale let meaning = renderData.meaning let visibleSamples = meaning.numSamplesSince(unis.view.time - unis.view.timeWindow) ?? 0 let valuesPerSample = Int(unis.samples.valuesPerSample) unis.update(withSize: drawableSize, scaleFactor: Float(scaleFactor)) let unibuffers = self.buffers let size : (view: Int, axis: Int, samples: Int) = (strideofValue(unis.view), strideofValue(unis.axis), strideofValue(unis.samples)) let offset : (view: Int, axis: Int, samples: Int) = (size.view*unis.currentIndex, size.axis * unis.currentIndex, size.samples * unis.currentIndex) memcpy(unibuffers.view.contents() + offset.view, &unis.view, size.view) memcpy(unibuffers.axis.contents() + offset.axis, &unis.axis, size.axis) memcpy(unibuffers.samples.contents() + offset.samples, &unis.samples, size.samples) let renderState = renderData.state dispatch_async(renderState.renderQueue) { [weak self] in let cmdBuffer = renderState.cmdQueue.commandBuffer() let parallelEncoder = cmdBuffer.parallelRenderCommandEncoderWithDescriptor(MTLRenderPassDescriptor().then { $0.colorAttachments[0].texture = drawable.texture $0.colorAttachments[0].clearColor = Colors.Background.metal $0.colorAttachments[0].loadAction = .Clear $0.colorAttachments[0].storeAction = .Store }) defer { parallelEncoder.endEncoding() cmdBuffer.presentDrawable(drawable) cmdBuffer.addCompletedHandler { _ in dispatch_semaphore_signal(unis.renderSemaphore) } cmdBuffer.commit() } let horizontalAxisEncoder = parallelEncoder.renderCommandEncoder() horizontalAxisEncoder.setFrontFacingWinding(.CounterClockwise) horizontalAxisEncoder.setCullMode(.Back) horizontalAxisEncoder.setRenderPipelineState(renderState.stateAxisHorizontal) horizontalAxisEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) horizontalAxisEncoder.setVertexBuffer(unibuffers.axis, offset: offset.axis, atIndex: 1) horizontalAxisEncoder.setFragmentBuffer(unibuffers.colors, offset: 0, atIndex: 0) horizontalAxisEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: Int(unis.axis.numLines.x)) horizontalAxisEncoder.endEncoding() let verticalAxisEncoder = parallelEncoder.renderCommandEncoder() verticalAxisEncoder.setFrontFacingWinding(.Clockwise) verticalAxisEncoder.setCullMode(.Back) verticalAxisEncoder.setRenderPipelineState(renderState.stateAxisVertical) verticalAxisEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) verticalAxisEncoder.setVertexBuffer(unibuffers.axis, offset: offset.axis, atIndex: 1) verticalAxisEncoder.setFragmentBuffer(unibuffers.colors, offset: 0, atIndex: 0) verticalAxisEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: Int(unis.axis.numLines.y)) verticalAxisEncoder.endEncoding() guard valuesPerSample > 0 && visibleSamples > 0 else { return } let firstIndex = meaning.numSamples-visibleSamples let sampleEncoder = parallelEncoder.renderCommandEncoder() sampleEncoder.setFrontFacingWinding(.Clockwise) sampleEncoder.setCullMode(.Back) sampleEncoder.setRenderPipelineState(renderState.stateSamples) sampleEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) sampleEncoder.setVertexBuffer(unibuffers.samples, offset: offset.samples, atIndex: 1) sampleEncoder.setVertexBuffer(meaning.buffer, offset: firstIndex*meaning.sampleSize, atIndex: 2) sampleEncoder.setVertexBuffer(renderState.verticesDotBuffer, offset: 0, atIndex: 3) sampleEncoder.setFragmentBuffer(unibuffers.colors, offset: sizeof(float4), atIndex: 0) sampleEncoder.drawIndexedPrimitives(.Triangle, indexCount: renderState.indicesDotBuffer.length/sizeof(UInt16), indexType: .UInt16, indexBuffer: renderState.indicesDotBuffer, indexBufferOffset: 0, instanceCount: visibleSamples*valuesPerSample) sampleEncoder.endEncoding() let visibleLines = visibleSamples - 1 guard visibleLines > 0 else { return } let lineEncoder = parallelEncoder.renderCommandEncoder() lineEncoder.setRenderPipelineState(renderState.stateUnionLines) lineEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) lineEncoder.setVertexBuffer(unibuffers.samples, offset: offset.samples, atIndex: 1) lineEncoder.setVertexBuffer(meaning.buffer, offset: firstIndex*meaning.sampleSize, atIndex: 2) lineEncoder.setFragmentBuffer(unibuffers.colors, offset: sizeof(float4), atIndex: 0) lineEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: visibleLines*valuesPerSample) lineEncoder.endEncoding() guard let textures = self?.textures else { guard let graph = self where graph.textureGenerator == nil else { return } graph.textureGenerator = GraphLabels.texturesBlock(withDevice: renderData.state.device, columnSize: unis.view.leftColumnSize, numLines: Int(unis.axis.numLines.x), boundaries: unis.samples.boundaries) { [weak graph] (textures) in graph?.textureGenerator = nil graph?.textures = textures } return dispatch_async(renderData.state.textureQueue, graph.textureGenerator!) } let labelsEncoder = parallelEncoder.renderCommandEncoder() labelsEncoder.setFrontFacingWinding(.Clockwise) labelsEncoder.setCullMode(.Back) labelsEncoder.setRenderPipelineState(renderState.stateLabels) labelsEncoder.setVertexBuffer(unibuffers.view, offset: offset.view, atIndex: 0) labelsEncoder.setVertexBuffer(unibuffers.axis, offset: offset.axis, atIndex: 1) for case let (index, texture as MTLTexture) in textures.enumerate() { labelsEncoder.setVertexTexture(texture, atIndex: 0) labelsEncoder.setFragmentTexture(texture, atIndex: 0) labelsEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: 1, baseInstance: index) } labelsEncoder.endEncoding() } } }
mit
3df1a26eea9764355f544234f397ce64
54.205607
254
0.651035
4.980607
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01640-swift-typebase-getcanonicaltype.swift
1
571
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol A : A { typealias A { func b: C { func b) -> String { } } extension Array { } class A { } private class B == B<c) { } let f == .B { var b = { } } } } extension A =
apache-2.0
cc8bd171ebcfb899acce58b385760925
20.148148
79
0.686515
3.300578
false
false
false
false