repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
twobitlabs/AnalyticsKit
Providers/Mixpanel/AnalyticsKitMixpanelProvider.swift
1
3441
import Foundation import Mixpanel public class AnalyticsKitMixpanelProvider: NSObject, AnalyticsKitProvider { @objc(initWithAPIKey:) public init(withAPIKey apiKey: String) { Mixpanel.sharedInstance(withToken: apiKey) } public func uncaughtException(_ exception: NSException) { Mixpanel.sharedInstance()?.track("Uncaught Exceptions", properties: [ "ename" : exception.name, "reason" : exception.reason ?? "nil", "userInfo" : exception.userInfo ?? "nil" ]) } // Logging public func applicationWillEnterForeground() {} public func applicationDidEnterBackground() {} public func applicationWillTerminate() {} public func logScreen(_ screenName: String) { logEvent("Screen - \(screenName)") } public func logScreen(_ screenName: String, withProperties properties: [String: Any]) { logEvent("Screen - \(screenName)", withProperties: properties) } public func logEvent(_ event: String) { Mixpanel.sharedInstance()?.track(event) } public func logEvent(_ event: String, withProperties properties: [String: Any]) { Mixpanel.sharedInstance()?.track(event, properties: properties) } public func logEvent(_ event: String, timed: Bool) { if timed { Mixpanel.sharedInstance()?.timeEvent(event) } else { Mixpanel.sharedInstance()?.track(event) } } public func logEvent(_ event: String, withProperties properties: [String: Any], timed: Bool) { if timed { Mixpanel.sharedInstance()?.timeEvent(event) } else { Mixpanel.sharedInstance()?.track(event, properties: properties) } } public func logEvent(_ event: String, withProperty key: String, andValue value: String) { logEvent(event, withProperties: [key: value]) } public func endTimedEvent(_ event: String, withProperties properties: [String: Any]) { // Mixpanel documentation: timeEvent followed by a track with the same event name would record the duration Mixpanel.sharedInstance()?.track(event, properties: properties) } public func logError(_ name: String, message: String?, properties: [String: Any]?, exception: NSException?) { var loggedProperties = [String: Any]() loggedProperties["name"] = name loggedProperties["message"] = message if let exception = exception { loggedProperties["ename"] = exception.name loggedProperties["reason"] = exception.reason loggedProperties["userInfo"] = exception.userInfo } if let properties = properties { loggedProperties.merge(properties) { (current, _) in current } } Mixpanel.sharedInstance()?.track("Exceptions", properties: loggedProperties) } public func logError(_ name: String, message: String?, properties: [String: Any]?, error: Error?) { var loggedProperties = [String: Any]() loggedProperties["name"] = name loggedProperties["message"] = message if let error = error { loggedProperties["description"] = error.localizedDescription } if let properties = properties { loggedProperties.merge(properties) { (current, _) in current } } Mixpanel.sharedInstance()?.track("Errors", properties: loggedProperties) } }
mit
d183638a6e76f364b97f8a5402d22b76
35.221053
115
0.641093
5.105341
false
false
false
false
hyperconnect/Bond
Bond/Bond+UICollectionView.swift
1
7333
// // Bond+UICollectionView.swift // Bond // // Created by Srđan Rašić on 06/03/15. // Copyright (c) 2015 Bond. All rights reserved. // import UIKit @objc class CollectionViewDynamicArrayDataSource: NSObject, UICollectionViewDataSource { weak var dynamic: DynamicArray<DynamicArray<UICollectionViewCell>>? @objc weak var nextDataSource: UICollectionViewDataSource? init(dynamic: DynamicArray<DynamicArray<UICollectionViewCell>>) { self.dynamic = dynamic super.init() } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return self.dynamic?.count ?? 0 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.dynamic?[section].count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return self.dynamic?[indexPath.section][indexPath.item] ?? UICollectionViewCell() } // Forwards func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if let result = self.nextDataSource?.collectionView?(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) { return result } else { fatalError("Defining Supplementary view either in Storyboard or by registering a class or nib file requires you to implement method collectionView:viewForSupplementaryElementOfKind:indexPath in your data soruce! To provide data source, make a class (usually your view controller) adhere to protocol UICollectionViewDataSource and implement method collectionView:viewForSupplementaryElementOfKind:indexPath. Register instance of your class as next data source with UICollectionViewDataSourceBond object by setting its nextDataSource property. Make sure you set it before binding takes place!") } } } private class UICollectionViewDataSourceSectionBond<T>: ArrayBond<UICollectionViewCell> { weak var collectionView: UICollectionView? var section: Int init(collectionView: UICollectionView?, section: Int) { self.collectionView = collectionView self.section = section super.init() self.didInsertListener = { [unowned self] a, i in if let collectionView: UICollectionView = self.collectionView { collectionView.performBatchUpdates({ collectionView.insertItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }) }, completion: nil) } } self.didRemoveListener = { [unowned self] a, i in if let collectionView = self.collectionView { collectionView.performBatchUpdates({ collectionView.deleteItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }) }, completion: nil) } } self.didUpdateListener = { [unowned self] a, i in if let collectionView = self.collectionView { collectionView.performBatchUpdates({ collectionView.reloadItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }) }, completion: nil) } } self.didResetListener = { [weak self] array in if let collectionView = self?.collectionView { collectionView.reloadData() } } } deinit { self.unbindAll() } } public class UICollectionViewDataSourceBond<T>: ArrayBond<DynamicArray<UICollectionViewCell>> { weak var collectionView: UICollectionView? private var dataSource: CollectionViewDynamicArrayDataSource? private var sectionBonds: [UICollectionViewDataSourceSectionBond<Void>] = [] public weak var nextDataSource: UICollectionViewDataSource? { didSet(newValue) { dataSource?.nextDataSource = newValue } } public init(collectionView: UICollectionView) { self.collectionView = collectionView super.init() self.didInsertListener = { [weak self] array, i in if let s = self { if let collectionView: UICollectionView = self?.collectionView { collectionView.performBatchUpdates({ collectionView.insertSections(NSIndexSet(array: i)) }, completion: nil) for section in sorted(i, <) { let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: collectionView, section: section) let sectionDynamic = array[section] sectionDynamic.bindTo(sectionBond) s.sectionBonds.insert(sectionBond, atIndex: section) for var idx = section + 1; idx < s.sectionBonds.count; idx++ { s.sectionBonds[idx].section += 1 } } } } } self.didRemoveListener = { [weak self] array, i in if let s = self { if let collectionView = s.collectionView { collectionView.performBatchUpdates({ collectionView.deleteSections(NSIndexSet(array: i)) }, completion: nil) for section in sorted(i, >) { s.sectionBonds[section].unbindAll() s.sectionBonds.removeAtIndex(section) for var idx = section; idx < s.sectionBonds.count; idx++ { s.sectionBonds[idx].section -= 1 } } } } } self.didUpdateListener = { [weak self] array, i in if let collectionView = self?.collectionView { collectionView.performBatchUpdates({ collectionView.reloadSections(NSIndexSet(array: i)) }, completion: nil) for section in i { let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: collectionView, section: section) let sectionDynamic = array[section] sectionDynamic.bindTo(sectionBond) self?.sectionBonds[section].unbindAll() self?.sectionBonds[section] = sectionBond } } } self.didResetListener = { [weak self] array in if let collectionView = self?.collectionView { collectionView.reloadData() } } } public func bind(dynamic: DynamicArray<UICollectionViewCell>) { bind(DynamicArray([dynamic])) } public override func bind(dynamic: Dynamic<Array<DynamicArray<UICollectionViewCell>>>, fire: Bool, strongly: Bool) { super.bind(dynamic, fire: false, strongly: strongly) if let dynamic = dynamic as? DynamicArray<DynamicArray<UICollectionViewCell>> { for section in 0..<dynamic.count { let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: self.collectionView, section: section) let sectionDynamic = dynamic[section] sectionDynamic.bindTo(sectionBond) sectionBonds.append(sectionBond) } dataSource = CollectionViewDynamicArrayDataSource(dynamic: dynamic) dataSource?.nextDataSource = self.nextDataSource collectionView?.dataSource = dataSource collectionView?.reloadData() } } deinit { self.unbindAll() collectionView?.dataSource = nil self.dataSource = nil } } public func ->> <T>(left: DynamicArray<UICollectionViewCell>, right: UICollectionViewDataSourceBond<T>) { right.bind(left) }
mit
0e87af585d7000bec4b505199ec242b9
36.020202
598
0.685266
5.13665
false
false
false
false
brentsimmons/Evergreen
Shared/ArticleStyles/ArticleTheme.swift
1
3115
// // ArticleTheme.swift // NetNewsWire // // Created by Brent Simmons on 9/26/15. // Copyright © 2015 Ranchero Software, LLC. All rights reserved. // import Foundation struct ArticleTheme: Equatable { static let defaultTheme = ArticleTheme() static let nnwThemeSuffix = ".nnwtheme" private static let defaultThemeName = NSLocalizedString("Default", comment: "Default") private static let unknownValue = NSLocalizedString("Unknown", comment: "Unknown Value") let path: String? let template: String? let css: String? let isAppTheme: Bool var name: String { guard let path = path else { return Self.defaultThemeName } return Self.themeNameForPath(path) } var creatorHomePage: String { return info?.creatorHomePage ?? Self.unknownValue } var creatorName: String { return info?.creatorName ?? Self.unknownValue } var version: String { return String(describing: info?.version ?? 0) } private let info: ArticleThemePlist? init() { self.path = nil; self.info = ArticleThemePlist(name: "Article Theme", themeIdentifier: "com.ranchero.netnewswire.theme.article", creatorHomePage: "https://netnewswire.com/", creatorName: "Ranchero Software", version: 1) let corePath = Bundle.main.path(forResource: "core", ofType: "css")! let stylesheetPath = Bundle.main.path(forResource: "stylesheet", ofType: "css")! css = Self.stringAtPath(corePath)! + "\n" + Self.stringAtPath(stylesheetPath)! let templatePath = Bundle.main.path(forResource: "template", ofType: "html")! template = Self.stringAtPath(templatePath)! isAppTheme = true } init(path: String, isAppTheme: Bool) throws { self.path = path let infoPath = (path as NSString).appendingPathComponent("Info.plist") let data = try Data(contentsOf: URL(fileURLWithPath: infoPath)) self.info = try PropertyListDecoder().decode(ArticleThemePlist.self, from: data) let corePath = Bundle.main.path(forResource: "core", ofType: "css")! let stylesheetPath = (path as NSString).appendingPathComponent("stylesheet.css") if let stylesheetCSS = Self.stringAtPath(stylesheetPath) { self.css = Self.stringAtPath(corePath)! + "\n" + stylesheetCSS } else { self.css = nil } let templatePath = (path as NSString).appendingPathComponent("template.html") self.template = Self.stringAtPath(templatePath) self.isAppTheme = isAppTheme } static func stringAtPath(_ f: String) -> String? { if !FileManager.default.fileExists(atPath: f) { return nil } if let s = try? NSString(contentsOfFile: f, usedEncoding: nil) as String { return s } return nil } static func filenameWithThemeSuffixRemoved(_ filename: String) -> String { return filename.stripping(suffix: Self.nnwThemeSuffix) } static func themeNameForPath(_ f: String) -> String { let filename = (f as NSString).lastPathComponent return filenameWithThemeSuffixRemoved(filename) } static func pathIsPathForThemeName(_ themeName: String, path: String) -> Bool { let filename = (path as NSString).lastPathComponent return filenameWithThemeSuffixRemoved(filename) == themeName } }
mit
797d6e95182886169db32722bbbbc18b
29.23301
204
0.724791
3.667845
false
false
false
false
Baglan/MCViewport
MCViewport/ViewController.swift
1
4748
// // ViewController.swift // MCViewport // // Created by Baglan on 2/11/16. // Copyright © 2016 Mobile Creators. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass class ViewController: UIViewController { @IBOutlet weak var viewport: MCViewportWithScrollView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let verticalPages = 3 let horizontalPages = 5 for x in 0..<horizontalPages { for y in 0..<verticalPages { let item = PageIndicator(pageNumber: y * horizontalPages + x) item.place(frame: CGRect(x: (viewport.bounds.width - 100) / 2, y: viewport.bounds.height - 120, width: 100, height: 100), viewportOffset: CGPoint(x: viewport.bounds.width * CGFloat(x), y: viewport.bounds.height * CGFloat(y)), parallax: CGPoint(x: 0.4, y: 1)) item.zIndex = 300 viewport.addItem(item) } } for x in 1...10 { for y in 1...1 { let item = MyItem() item.place(frame: CGRect(x: CGFloat(x) * 110, y: CGFloat(y) * 110, width: 100, height: 100), viewportOffset: CGPoint.zero, parallax: CGPoint(x: 1.5, y: 1.5)) item.zIndex = 100 viewport.addItem(item) } } let item = MyControllerItem() item.place(frame: CGRect(x: 50, y: 200, width: 200, height: 200)) item.zIndex = 200 let leftMC = MCViewport.MovementConstraint() leftMC.place(left: 0) item.addMovementConstraint(leftMC) let rightMC = MCViewport.MovementConstraint() rightMC.place(right: viewport.bounds.width) item.addMovementConstraint(rightMC) let topMC = MCViewport.MovementConstraint() topMC.place(top: 0) item.addMovementConstraint(topMC) let bottomMC = MCViewport.MovementConstraint() bottomMC.place(bottom: viewport.bounds.height) item.addMovementConstraint(bottomMC) let pusherMC = MCViewport.MovementConstraint() pusherMC.place(right: 0, viewportOffset: CGPoint(x: viewport.bounds.width * 2, y: 0), parallax: CGPoint(x: 1, y: 1)) pusherMC.priority = 100 item.addMovementConstraint(pusherMC) viewport.addItem(item) viewport.scrollView.isPagingEnabled = true viewport.scrollView.alternateDirectionalLockEnabled = true viewport.scrollView.frame = viewport.bounds viewport.scrollView.contentSize = CGSize(width: viewport.bounds.width * CGFloat(horizontalPages), height: viewport.bounds.height * CGFloat(verticalPages)) viewport.scrollView.alwaysBounceHorizontal = true viewport.scrollView.alwaysBounceVertical = true viewport.scrollView.setContentOffset(CGPoint(x: viewport.bounds.width, y: 0), animated: true) } } class PageIndicator: MCViewport.ViewItem { let pageNumber: Int init(pageNumber: Int) { self.pageNumber = pageNumber } override func willBecomeVisible() { super.willBecomeVisible() guard let label = view as? UILabel else { return } label.text = "\(pageNumber)" } override func newView() -> UIView { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 40) label.textAlignment = .center label.text = "!" label.layer.borderWidth = 4 label.layer.borderColor = UIColor.black.cgColor label.layer.cornerRadius = 50 return label } } class MyItem: MCViewport.ViewItem { override func willBecomeVisible() { super.willBecomeVisible() if let view = view { view.backgroundColor = UIColor.red } } } class MyViewController: UIViewController { @IBOutlet weak var button: MCButton! override func viewDidLoad() { super.viewDidLoad() button.action = { _ in NSLog("--- tap!") } } } class MyControllerItem: MCViewport.ViewControllerItem { override func newViewController() -> UIViewController? { return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MyViewController") } override func update() { super.update() NSLog("--- distances: left: \(distances.left) top: \(distances.top) bottom: \(distances.bottom) right: \(distances.right) center: \(distances.center)") } }
mit
fb4626d0727ce1b2ba3880a6944814d8
33.151079
274
0.618496
4.491012
false
false
false
false
pascaljette/PokeBattleDemo
PokeBattleDemo/PokeBattleDemo/PokeApi/Connection/PokeApiConnection.swift
1
3853
// The MIT License (MIT) // // Copyright (c) 2015 pascaljette // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import SwiftyJSON /// Status of the connection. enum PokeapiConnectionStatus { /// Connection has completed successfully. case Success /// Connection has failed. case ConnectionError /// There was an error while building the URL. case UrlError } /// Performs a connection to the API provided the request and response type. /// The execute method can be called with an instance of the request type if additional configuration /// is required. class PokeApiConnection<RequestType: PokeApiRequestBase, ResponseType: PokeApiResponseBase> { // // MARK: Nested types // /// Function to call on completion of the connection. typealias OnCompletion = (PokeapiConnectionStatus, NSError?, ResponseType?) -> Void // // MARK: Stored properties // /// Referene on the closure to call on completion. var onCompletion: OnCompletion? /// Reference on the inner task used to perform the connection (url session) private var task: NSURLSessionTask? // // MARK: Initialisation // /// Parameterless initialiser. init() { } } extension PokeApiConnection { // // MARK: Public methods // /// Execute the connection with an external reference on the request. /// Useful when the request requires additional configuration. func execute(request: RequestType) { performCall(request) } } extension PokeApiConnection { // // MARK: Private utility methods // /// Perform the connection. /// /// - parameter request: The configured request used to perform the connection. private func performCall(request: RequestType) { // TODO-pk add log or error handling here guard let requestFullUrl = request.absoluteUrl else { let error: NSError = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil) self.onCompletion?(.UrlError, error, nil) return } self.task = NSURLSession.sharedSession().dataTaskWithURL(requestFullUrl) {(data, response, error) in guard error == nil else { self.onCompletion?(.ConnectionError, error, nil) return } if let dataInstance = data { let json: JSON = JSON(data: dataInstance); let response: ResponseType = ResponseType(json: json); self.onCompletion?(.Success, nil, response) } } task!.resume() } }
mit
faa4073e704770c67f5b1397895924bd
29.824
108
0.646769
5.137333
false
false
false
false
ITzTravelInTime/TINU
TINU/InstallingViewController.swift
1
8482
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Cocoa public class InstallingViewController: GenericViewController, ViewID{ public let id: String = "InstallingViewController" @IBOutlet weak var driveName: NSTextField! @IBOutlet weak var driveImage: NSImageView! @IBOutlet weak var appImage: NSImageView! @IBOutlet weak var appName: NSTextField! //@IBOutlet weak var spinner: NSProgressIndicator! @IBOutlet weak var descriptionField: NSTextField! @IBOutlet weak var activityLabel: NSTextField! @IBOutlet weak var showLogButton: NSButton! @IBOutlet weak var cancelButton: NSButton! //@IBOutlet weak var infoImageView: NSImageView! @IBOutlet weak var progress: NSProgressIndicator! override public func viewWillDisappear() { SPM.shared.cancelSleepPrevention() } deinit{ SPM.shared.cancelSleepPrevention() } public override func viewDidLoad() { super.viewDidLoad() // Do view setup here. //self.setTitleLabel(text: "Bootable macOS installer creation") self.setTitleLabel(text: TextManager.getViewString(context: self, stringID: "title")) self.cancelButton.title = TextManager.getViewString(context: self, stringID: "cancelButton") self.showLogButton.title = TextManager.getViewString(context: self, stringID: "showLogButton") self.descriptionField.stringValue = TextManager.getViewString(context: self, stringID: "descriptionField") self.descriptionField.isHidden = true self.showTitleLabel() //disable the close button of the window if let w = UIManager.shared.window{ w.isMiniaturizeEnaled = true w.isClosingEnabled = false //w.canHide = false } //initialization activityLabel.stringValue = "" //placeholder values self.setProgressMax(1000) self.setProgressValue(0) /*if let a = NSApplication.shared().delegate as? AppDelegate{ a.QuitMenuButton.isEnabled = false }*/ //just prints some separators to allow me to see where this windows opens in the output print("*******************") print("* PROCESS STARTED *") print("*******************") cancelButton.isEnabled = false enableItems(enabled: false) setActivityLabelText("activityLabel1") sharedSetSelectedCreationUI(appName: &appName, appImage: &appImage, driveName: &driveName, driveImage: &driveImage, manager: cvm.shared, useDriveName: cvm.shared.disk.current.isDrive || cvm.shared.disk.shouldErase) print("process window opened") if !SPM.shared.activateSleepPrevention(){ goBack() } DispatchQueue.global(qos: .background).async{ var drive = false if (simulateInstallGetDataFail ? true : cvm.shared.checkProcessReadySate(&drive)){ DispatchQueue.main.async { sharedSetSelectedCreationUI(appName: &self.appName, appImage: &self.appImage, driveName: &self.driveName, driveImage: &self.driveImage, manager: cvm.shared, useDriveName: drive) } log("Everything is ready to start the creation/installation process") //InstallMediaCreationManager.startInstallProcess(ref: &cvm.shared) //DispatchQueue.main.sync { cvm.shared.maker = .init(ref: &cvm.shared, controller: self) //} cvm.shared.maker?.install() }else{ log("Couldn't get valid info about the installer app and/or the drive") DispatchQueue.main.sync { self.setActivityLabelText("activityLabel2") self.goBack() } } } } private func restoreWindow(){ //resets window //spinner.isHidden = true //spinner.stopAnimation(self) if let w = UIManager.shared.window{ w.isMiniaturizeEnaled = true w.isClosingEnabled = true //w.canHide = true } enableItems(enabled: true) } func goToFinalScreen(title: String, success: Bool = false){ //this code opens the final window log("Bootable macOS installer creation process ended") //resets window and auths restoreWindow() MainCreationFinishedViewController.title = title cvm.shared.disk.current = nil cvm.shared.app.current = nil //InstallMediaCreationManager.shared.makeProcessNotInExecution(withResult: success) cvm.shared.maker?.makeProcessNotInExecution(withResult: success) SPM.shared.cancelSleepPrevention() self.swapCurrentViewController("MainDone") } func goToFinalScreen(id: String, success: Bool = false, parseList: [String: String]! = nil){ //this code opens the final window log("Bootable macOS installer creation process ended\n\n Ending messange id: \(id)\n Ending success: \(success ? "Yes" : "No")") var etitle = TextManager.getViewString(context: self, stringID: id)! if let list = parseList{ etitle.parse(usingKeys: list) } goToFinalScreen(title: etitle, success: success) } @objc func goBack(){ //this code opens the previus window if (cvm.shared.process.status.isBusy()){ Notifications.justSendWith(id: "goBack", icon: nil) } //resets window and auths restoreWindow() cvm.shared.process.status = .configuration SPM.shared.cancelSleepPrevention() self.swapCurrentViewController("Confirm") } @IBAction func cancel(_ sender: Any) { //displays a dialog to check if the user is sure that user wants to stop the installer creation /* if cvm.shared.process.status == .creation{ spd = InstallMediaCreationManager.shared.stopWithAsk() }else{ spd = true }*/ //guard let stopped = (cvm.shared.process.status == .creation ? InstallMediaCreationManager.shared.stopWithAsk() : true ) else { return } if cvm.shared.maker == nil{ log("The " + cvm.shared.executableName + " process seems to be already closed") goBack() return } guard let stopped = (cvm.shared.process.status == .creation ? cvm.shared.maker?.stopWithAsk() : true ) else { return } if stopped{ goBack() return } log("Error while trying to close " + cvm.shared.executableName + " try to stop it from the termianl or from Activity monitor") let list = ["{executable}" : cvm.shared.executableName] //msgBoxWarning("Error while trying to exit from the process", "There was an error while trying to close the creation process: \n\nFailed to stop ${executable} process") msgboxWithManager(self, name: "stopError", parseList: list) } //shows the log window @IBAction func showLog(_ sender: Any) { if UIManager.shared.logWC == nil { UIManager.shared.logWC = LogWindowController() } UIManager.shared.logWC?.showWindow(self) } func enableItems(enabled: Bool){ if let apd = NSApplication.shared.delegate as? AppDelegate{ if Recovery.status{ apd.InstallMacOSItem.isEnabled = enabled } apd.verboseItem.isEnabled = enabled apd.verboseItemSudo.isEnabled = enabled apd.toolsMenuItem.isEnabled = enabled } #if !macOnlyMode if let tool = UIManager.shared.EFIPartitionMonuterTool{ tool.close() } #endif } public func setActivityLabelText(_ texta: String){ let text = TextManager.getViewString(context: self, stringID: texta)!.parsed(usingKeys: ["{executable}" : cvm.shared.installerAppProcessExecutableName]) self.activityLabel.stringValue = text print("Set activity label text: \(text)") } func setProgressValue(_ value: Double){ self.progress.doubleValue = value print("Set progress value: \(value)") } func addToProgressValue(_ value: Double){ self.setProgressValue(self.progress.doubleValue + value) } func getProgressBarValue() -> Double{ return self.progress.doubleValue } func setProgressMax(_ max: Double){ self.progress.maxValue = max print("Set progress max: \(max)") } func setProgressBarIndeterminateState(state: Bool){ self.progress.isIndeterminate = state print("Progress bar is now \(state ? "indeterminated" : "linear")") } }
gpl-2.0
3dd213d2346806159f19c9d6111ab350
29.620939
216
0.723178
3.726714
false
false
false
false
mperovic/my41
my41/Classes/SoundOutput.swift
1
9490
// // SoundOutput.swift // my41 // // Created by Miroslav Perovic on 8/11/14. // Copyright (c) 2014 iPera. All rights reserved. // import Foundation enum SoundCmds: Int, Codable { case nullCmd = 0 case quietCmd = 3 case flushCmd = 4 case reInitCmd = 5 case waitCmd = 10 case pauseCmd = 11 case resumeCmd = 12 case callBackCmd = 13 case syncCmd = 14 case availableCmd = 24 case versionCmd = 25 case volumeCmd = 46 /*sound manager 3.0 or later only*/ case getVolumeCmd = 47 /*sound manager 3.0 or later only*/ case clockComponentCmd = 50 /*sound manager 3.2.1 or later only*/ case getClockComponentCmd = 51 /*sound manager 3.2.1 or later only*/ case scheduledSoundCmd = 52 /*sound manager 3.3 or later only*/ case linkSoundComponentsCmd = 53 /*sound manager 3.3 or later only*/ case soundCmd = 80 case bufferCmd = 81 case rateMultiplierCmd = 86 case getRateMultiplierCmd = 87 } // Sample rate is equal to the CPU word execution rate. let SAMPLE_RATE = (1.0 / 155e-6) // SOUND_LATENCY is the delay between the CPU producing sound // samples and sending those samples to the Sound Manager, to // smooth out fluctuations in instruction execution rate by // the emulator. let SOUND_LATENCY = 0.1 // TOTAL_BUFFERS is the total number of sound buffers to allocate. // LATENCY_BUFFERS is the number of buffers that will be filled during // the latency period. // SILENCE_BUFFERS is the number of buffers after which sound sample // processing will be stopped if there is no sound activity. let TOTAL_BUFFERS = 4 // 8 let LATENCY_BUFFERS = 2 let SILENCE_BUFFERS = 2 // Amplitute of the generated square wave let AMPLITUDE = 10 //-------------------------------------------------------------------------------- // Fixed point representation of the sample rate. let SAMPLE_RATE_FIXED: UInt64 = UInt64(44100.0 * SAMPLE_RATE) // We will wait until at least LATENCY_BUFFERS buffers of sound are filled before // starting to send them to the sound channel. The buffer size is // calculated so that LATENCY_BUFFERS buffers equals the specified latency. let SAMPLES_PER_BUFFER: Int = Int(Double(SOUND_LATENCY) * Double(SAMPLE_RATE) / Double(LATENCY_BUFFERS)) // Sample values for high and low levels of the square wave let LOW_SAMPLE: UInt8 = UInt8(0x80 - AMPLITUDE) let HIGH_SAMPLE: UInt8 = UInt8(0x80 + AMPLITUDE) var gDroppedSampleCount: Int = 0 enum SoundMode { case none, speaker, wawe } final class SoundOutput: Codable { typealias SoundSample = UInt8 struct SndCommand: Codable { var cmd: SoundCmds = .nullCmd var param1: Int16 = 0 var param2: SoundHeader? = nil } struct SndChannel: Codable { // var nextChan: SndChannel<T> var firstMod = [String]() /* reserved for the Sound Manager */ // SndCallBackUPP callBack var userInfo: Int32 = 0 var wait: Int32 = 0 /* The following is for internal Sound Manager use only.*/ var cmdInProgress = SndCommand() var flags: Int16 = 0 var qLength: Int16 = 0 var qHead: Int16 = 0 var qTail: Int16 = 0 var queue = [SndCommand]() } struct SoundHeader: Codable { var samplePtr: [SoundSample]? = nil /*if NIL then samples are in sampleArea*/ var length: Int = 0 /*length of sound in bytes*/ var sampleRate: UInt64 = 0 /*sample rate for this sound*/ var loopStart: UInt64 = 0 /*start of looping portion*/ var loopEnd: UInt64 = 0 /*end of looping portion*/ var encode: UInt8 = 0 /*header encoding*/ var baseFrequency: UInt8 = 0 /*baseFrequency value*/ var sampleArea: UInt8 = 0 /*space for when samples follow directly*/ } struct SoundBuffer: Codable { // var next: SoundBuffer? = nil var inUse: Bool = false var header: SoundHeader = SoundHeader() var samples: [SoundSample] = [SoundSample](repeating: 0, count: SAMPLES_PER_BUFFER) } var soundMode = SoundMode.none var gSndChannel: SndChannel? var gBuffers = [SoundBuffer]() var gBufferSendPtr: Int = 0 var gBufferAllocPtr: Int = 0 var gNumPendingBuffers: Int = 0 var gCurrentBuffer: SoundBuffer? var gBufferingSound: Bool = false var gConstantSampleCount: Int = 0 var gLastSample = SoundSample(LOW_SAMPLE) enum CodingKeys: String, CodingKey { case gSndChannel case gBuffers case gBufferSendPtr case gBufferAllocPtr case gNumPendingBuffers case gCurrentBuffer case gBufferingSound case gConstantSampleCount case gLastSample } init() { // var idx: Int // for idx = 0; idx < TOTAL_BUFFERS; idx++ { for _ in 0..<TOTAL_BUFFERS { gBuffers.append(SoundBuffer()) } } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) gSndChannel = try values.decode(SndChannel.self, forKey: .gSndChannel) gBuffers = try values.decode([SoundBuffer].self, forKey: .gBuffers) gBufferSendPtr = try values.decode(Int.self, forKey: .gBufferSendPtr) gBufferAllocPtr = try values.decode(Int.self, forKey: .gBufferAllocPtr) gNumPendingBuffers = try values.decode(Int.self, forKey: .gNumPendingBuffers) gCurrentBuffer = try values.decode(SoundBuffer.self, forKey: .gCurrentBuffer) gBufferingSound = try values.decode(Bool.self, forKey: .gBufferingSound) gConstantSampleCount = try values.decode(Int.self, forKey: .gConstantSampleCount) gLastSample = try values.decode(SoundSample.self, forKey: .gLastSample) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(gSndChannel, forKey: .gSndChannel) try container.encode(gBuffers, forKey: .gBuffers) try container.encode(gBufferSendPtr, forKey: .gBufferSendPtr) try container.encode(gBufferAllocPtr, forKey: .gBufferAllocPtr) try container.encode(gNumPendingBuffers, forKey: .gNumPendingBuffers) try container.encode(gCurrentBuffer, forKey: .gCurrentBuffer) try container.encode(gBufferingSound, forKey: .gBufferingSound) try container.encode(gConstantSampleCount, forKey: .gConstantSampleCount) try container.encode(gLastSample, forKey: .gLastSample) } func soundAvailableBufferSpace() -> Int { var p = gBufferAllocPtr var numFreeBuffers: Int = 0 while numFreeBuffers < TOTAL_BUFFERS && !gBuffers[p].inUse { numFreeBuffers += 1 incBufferPtr(&p) } return numFreeBuffers * SAMPLES_PER_BUFFER } func incBufferPtr(_ ptr: inout Int) { if ptr == TOTAL_BUFFERS { ptr = 0 } } func anyBuffersInUse() -> Bool { // var idx: Int // for idx = 0; idx < TOTAL_BUFFERS; idx++ { for idx in 0..<TOTAL_BUFFERS { if gBuffers[idx].inUse { return true } } return false } func soundTimeslice() { if !gBufferingSound && gSndChannel != nil && !anyBuffersInUse() { shutDownSoundChannel() } } func shutDownSoundChannel() { gSndChannel = nil } func flushAndSuspendSoundOutput() { finishBuffer() sendPendingBuffers() gBufferingSound = false } func finishBuffer() { if gCurrentBuffer != nil { // println("Finished filling buffer \(gCurrentBuffer - gBuffers)") gNumPendingBuffers += 1 gCurrentBuffer = nil } } func sendPendingBuffers() { while gNumPendingBuffers != 0 { startUpSoundChannel() if TRACE != 0 { print("Sending buffer \(gBufferSendPtr)") } let buf: SoundBuffer = gBuffers[gBufferSendPtr] var cmd = SndCommand() cmd.cmd = .bufferCmd cmd.param1 = 0 cmd.param2 = buf.header // SndDoCommand(gSndChannel, &cmd, YES) cmd.cmd = .callBackCmd cmd.param1 = Int16(gBufferSendPtr) cmd.param2 = nil // SndDoCommand(gSndChannel, &cmd, YES) incBufferPtr(&gBufferSendPtr) gNumPendingBuffers -= 1 } } func startUpSoundChannel() { if gSndChannel != nil { if TRACE != 0 { print("Allocating sound channel\n") } // SndNewChannel(&gSndChannel, sampledSynth, 0, (SndCallBackUPP)SoundCallback) } } func getBuffer() -> SoundBuffer? { var buf = gCurrentBuffer if buf == nil { buf = gBuffers[gBufferAllocPtr] if buf?.inUse == true { if gDroppedSampleCount == 0 { if TRACE != 0 { print("Buffer \(gBufferAllocPtr) is in use\n") } } gDroppedSampleCount += 1 return nil } if gDroppedSampleCount != 0 { if TRACE != 0 { print("Buffer \(gBufferAllocPtr) is free after \(gDroppedSampleCount) dropped samples\n") } gDroppedSampleCount = 0 } if TRACE != 0 { print("Starting to fill buffer \(gBufferAllocPtr)\n") } initBuffer(&buf!) buf?.inUse = true incBufferPtr(&gBufferAllocPtr) gCurrentBuffer = buf } return buf! } func soundOutputForWordTime(_ state: Int) { let sample = state != 0 ? HIGH_SAMPLE : LOW_SAMPLE if !gBufferingSound { if sample == gLastSample { return } if TRACE != 0 { print("Starting to buffer sound\n") } gBufferingSound = true } if let aBuf = getBuffer() { var buf: SoundBuffer = aBuf buf.samples[buf.header.length] = sample buf.header.length += 1 } } func initBuffer(_ buf: inout SoundBuffer) { buf.header.sampleRate = SAMPLE_RATE_FIXED buf.header.samplePtr = buf.samples buf.header.length = 0 } }
bsd-3-clause
082a4c835a49f90ecf9e6be9ba64318b
29.22293
105
0.665753
3.251113
false
false
false
false
chinabrant/BProgressHUD
BProgressHUD/LoadingView.swift
1
2457
// // LoadingView.swift // BProgressHUDDemo // // Created by brant on 2017/3/29. // Copyright © 2017年 brant. All rights reserved. // import UIKit import CoreGraphics class LoadingView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear let circle: UIBezierPath = UIBezierPath.init(ovalIn: CGRect(x: 4, y: 4, width: self.frame.size.width - 8, height: self.frame.size.height - 8)) let shapeLayer = CAShapeLayer() shapeLayer.path = circle.cgPath //存入UIBezierPath的路径 shapeLayer.fillColor = UIColor.clear.cgColor //设置填充色 shapeLayer.lineWidth = 10 //设置路径线的宽度 shapeLayer.strokeColor = UIColor.gray.cgColor //路径颜色 self.layer.addSublayer(shapeLayer) let colorLayer = CAGradientLayer() colorLayer.frame = self.bounds colorLayer.colors = [UIColor.red.cgColor, UIColor.orange.cgColor] colorLayer.startPoint = CGPoint(x: 0, y: 0) colorLayer.endPoint = CGPoint(x: 1, y: 0) let maskLayer = CAShapeLayer() maskLayer.frame = self.bounds maskLayer.path = circle.cgPath //存入UIBezierPath的路径 maskLayer.fillColor = UIColor.clear.cgColor //设置填充色 maskLayer.lineWidth = 10 //设置路径线的宽度 maskLayer.strokeColor = UIColor.orange.cgColor //路径颜色 maskLayer.lineCap = kCALineCapRound // CGLineCap.round maskLayer.strokeEnd = 0.8 colorLayer.mask = maskLayer self.layer.addSublayer(colorLayer) let animate = CABasicAnimation(keyPath: "transform.rotation.z") animate.fromValue = 0 animate.toValue = 2 * Double.pi animate.duration = 2 animate.repeatCount = Float.greatestFiniteMagnitude maskLayer.add(animate, forKey: "x") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) // let circle: UIBezierPath = UIBezierPath.init(ovalIn: CGRect(x: 4, y: 4, width: self.frame.size.width - 8, height: self.frame.size.height - 8)) // circle.lineWidth = 4.0 // circle.lineCapStyle = CGLineCap.round // UIColor.red.setStroke() // circle.stroke() } }
mit
313d9a252e84c54e233e1546b4eccb0a
33.289855
152
0.6306
4.301818
false
false
false
false
dzenbot/Iconic
Vendor/SwiftGen/GenumKit/Parsers/ColorsFileParser.swift
1
5282
// // GenumKit // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Foundation import AppKit.NSColor public protocol ColorsFileParser { var colors: [String: UInt32] { get } } // MARK: - Private Helpers private func parseHexString(hexString: String) -> UInt32 { let scanner = NSScanner(string: hexString) let prefixLen: Int if scanner.scanString("#", intoString: nil) { prefixLen = 1 } else if scanner.scanString("0x", intoString: nil) { prefixLen = 2 } else { prefixLen = 0 } var value: UInt32 = 0 scanner.scanHexInt(&value) let len = hexString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) - prefixLen if len == 6 { // There were no alpha component, assume 0xff value = (value << 8) | 0xff } return value } // MARK: - Text File Parser public final class ColorsTextFileParser: ColorsFileParser { public private(set) var colors = [String:UInt32]() public init() {} public func addColorWithName(name: String, value: String) { addColorWithName(name, value: parseHexString(value)) } public func addColorWithName(name: String, value: UInt32) { colors[name] = value } // Text file expected to be: // - One line per entry // - Each line composed by the color name, then ":", then the color hex representation // - Extra spaces will be skipped public func parseFile(path: String, separator: String = ":") throws { let content = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) let lines = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) let ws = NSCharacterSet.whitespaceCharacterSet() for line in lines { let scanner = NSScanner(string: line) scanner.charactersToBeSkipped = ws var key: NSString? if scanner.scanUpToString(":", intoString: &key) { scanner.scanString(":", intoString: nil) var value: NSString? if scanner.scanUpToCharactersFromSet(ws, intoString: &value) { addColorWithName(key! as String, value: value! as String) } } } } } // MARK: - CLR File Parser public final class ColorsCLRFileParser: ColorsFileParser { public private(set) var colors = [String: UInt32]() public init() {} public func parseFile(path: String) { if let colorsList = NSColorList(name: "UserColors", fromFile: path) { for colorName in colorsList.allKeys { colors[colorName] = colorsList.colorWithKey(colorName)?.rgbColor?.hexValue } } } } extension NSColor { private var rgbColor: NSColor? { return colorUsingColorSpaceName(NSCalibratedRGBColorSpace) } private var hexValue: UInt32 { let hexRed = UInt32(redComponent * 0xFF) << 24 let hexGreen = UInt32(greenComponent * 0xFF) << 16 let hexBlue = UInt32(blueComponent * 0xFF) << 8 let hexAlpha = UInt32(alphaComponent * 0xFF) return hexRed | hexGreen | hexBlue | hexAlpha } } // MARK: - Android colors.xml File Parser public final class ColorsXMLFileParser: ColorsFileParser { static let colorTagName = "color" static let colorNameAttribute = "name" public private(set) var colors = [String: UInt32]() public init() {} public func parseFile(path: String) throws { class ParserDelegate: NSObject, NSXMLParserDelegate { var parsedColors = [String: UInt32]() var currentColorName: String? = nil var currentColorValue: String? = nil @objc func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) { guard elementName == ColorsXMLFileParser.colorTagName else { return } currentColorName = attributeDict[ColorsXMLFileParser.colorNameAttribute] currentColorValue = nil } @objc func parser(parser: NSXMLParser, foundCharacters string: String) { currentColorValue = (currentColorValue ?? "") + string } @objc func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { guard elementName == ColorsXMLFileParser.colorTagName else { return } guard let colorName = currentColorName, let colorValue = currentColorValue else { return } parsedColors[colorName] = parseHexString(colorValue) currentColorName = nil currentColorValue = nil } } guard let parser = NSXMLParser(contentsOfURL: NSURL.fileURLWithPath(path)) else { throw NSError(domain: NSXMLParserErrorDomain, code: NSXMLParserError.InternalError.rawValue, userInfo: nil) } let delegate = ParserDelegate() parser.delegate = delegate parser.parse() colors = delegate.parsedColors } } // MARK: - JSON File Parser public final class ColorsJSONFileParser: ColorsFileParser { public private(set) var colors = [String: UInt32]() public init() {} public func parseFile(path: String) throws { if let JSONdata = NSData(contentsOfFile: path), let json = try? NSJSONSerialization.JSONObjectWithData(JSONdata, options: []), let dict = json as? [String: String] { for (key, value) in dict { colors[key] = parseHexString(value) } } } }
mit
6862fba0698e2393ee38d95f98b4c2d1
28.674157
113
0.685346
4.39069
false
false
false
false
whitepixelstudios/Material
Sources/iOS/CollectionViewLayout.swift
2
8910
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit open class CollectionViewLayout: UICollectionViewLayout { /// Used to calculate the dimensions of the cells. public var offset = CGPoint.zero /// The size of items. public var itemSize = CGSize.zero /// A preset wrapper around contentEdgeInsets. public var contentEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset) } } /// A wrapper around grid.contentEdgeInsets. public var contentEdgeInsets = EdgeInsets.zero /// Size of the content. public fileprivate(set) var contentSize = CGSize.zero /// Layout attribute items. public fileprivate(set) lazy var layoutItems = [(UICollectionViewLayoutAttributes, NSIndexPath)]() /// Cell data source items. public fileprivate(set) var dataSourceItems: [DataSourceItem]? /// Scroll direction. public var scrollDirection = UICollectionViewScrollDirection.vertical /// A preset wrapper around interimSpace. public var interimSpacePreset = InterimSpacePreset.none { didSet { interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset) } } /// Spacing between items. public var interimSpace: InterimSpace = 0 open override var collectionViewContentSize: CGSize { return contentSize } } extension CollectionViewLayout { /** Retrieves the index paths for the items within the passed in CGRect. - Parameter rect: A CGRect that acts as the bounds to find the items within. - Returns: An Array of NSIndexPath objects. */ public func indexPathsOfItems(in rect: CGRect) -> [NSIndexPath] { var paths = [NSIndexPath]() for (attribute, indexPath) in layoutItems { guard rect.intersects(attribute.frame) else { continue } paths.append(indexPath) } return paths } } extension CollectionViewLayout { /** Prepares the layout for the given data source items. - Parameter for dataSourceItems: An Array of DataSourceItems. */ fileprivate func prepareLayout(for dataSourceItems: [DataSourceItem]) { self.dataSourceItems = dataSourceItems layoutItems.removeAll() offset.x = contentEdgeInsets.left offset.y = contentEdgeInsets.top for i in 0..<dataSourceItems.count { let item = dataSourceItems[i] let indexPath = IndexPath(item: i, section: 0) layoutItems.append((layoutAttributesForItem(at: indexPath)!, indexPath as NSIndexPath)) offset.x += interimSpace offset.y += interimSpace if nil != item.width { offset.x += item.width! } else if let v = item.data as? UIView, 0 < v.bounds.width { offset.x += v.bounds.width } else { offset.x += itemSize.width } if nil != item.height { offset.y += item.height! } else if let v = item.data as? UIView, 0 < v.bounds.height { offset.y += v.bounds.height } else { offset.y += itemSize.height } } offset.x += contentEdgeInsets.right - interimSpace offset.y += contentEdgeInsets.bottom - interimSpace if 0 < itemSize.width && 0 < itemSize.height { contentSize = CGSize(width: offset.x, height: offset.y) } else if .vertical == scrollDirection { contentSize = CGSize(width: collectionView!.bounds.width, height: offset.y) } else { contentSize = CGSize(width: offset.x, height: collectionView!.bounds.height) } } } extension CollectionViewLayout { open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) let dataSourceItem = dataSourceItems![indexPath.item] if 0 < itemSize.width && 0 < itemSize.height { attributes.frame = CGRect(x: offset.x, y: offset.y, width: itemSize.width - contentEdgeInsets.left - contentEdgeInsets.right, height: itemSize.height - contentEdgeInsets.top - contentEdgeInsets.bottom) } else if .vertical == scrollDirection { if let h = dataSourceItem.height { attributes.frame = CGRect(x: contentEdgeInsets.left, y: offset.y, width: collectionView!.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right, height: h) } else if let v = dataSourceItem.data as? UIView, 0 < v.bounds.height { v.updateConstraints() v.setNeedsLayout() v.layoutIfNeeded() attributes.frame = CGRect(x: contentEdgeInsets.left, y: offset.y, width: collectionView!.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right, height: v.bounds.height) } else { attributes.frame = CGRect(x: contentEdgeInsets.left, y: offset.y, width: collectionView!.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right, height: collectionView!.bounds.height) } } else { if let w = dataSourceItem.width { attributes.frame = CGRect(x: offset.x, y: contentEdgeInsets.top, width: w, height: collectionView!.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom) } else if let v = dataSourceItem.data as? UIView, 0 < v.bounds.width { v.updateConstraints() v.setNeedsLayout() v.layoutIfNeeded() attributes.frame = CGRect(x: offset.x, y: contentEdgeInsets.top, width: v.bounds.width, height: collectionView!.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom) } else { attributes.frame = CGRect(x: offset.x, y: contentEdgeInsets.top, width: collectionView!.bounds.width, height: collectionView!.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom) } } return attributes } open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() for (attribute, _) in layoutItems { if rect.intersects(attribute.frame) { layoutAttributes.append(attribute) } } return layoutAttributes } open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return .vertical == scrollDirection ? newBounds.width != collectionView!.bounds.width : newBounds.height != collectionView!.bounds.height } open override func prepare() { guard let dataSource = collectionView?.dataSource as? CollectionViewDataSource else { return } prepareLayout(for: dataSource.dataSourceItems) } open override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { return proposedContentOffset } }
bsd-3-clause
2d4cc06c6c3578e9157b2ee0c95632e4
40.830986
213
0.659259
5.111876
false
false
false
false
danbennett/DBRepo
DBRepo/Repo/CoreData/NSManagedObjectContext+RepoQueryType.swift
1
1388
// // NSManagedObjectContext+RepoQueryType.swift // DBRepo // // Created by Daniel Bennett on 09/07/2016. // Copyright © 2016 Dan Bennett. All rights reserved. // import Foundation import CoreData extension NSManagedObjectContext : RepoQueryType { public func fetch<T : EntityType>(type : T.Type, predicate : NSPredicate?) throws -> [T] { let className = type.className guard let request = self.fetchRequest(className) else { throw NSError (domain: "com.havaslynx.hlrepo", code: 8001, userInfo: [NSLocalizedDescriptionKey : "No entity matches that name"]) } var results: [T]! var responseError: ErrorType? self.performBlockAndWait { () -> Void in do { results = try self.executeFetchRequest(request) as? [T] } catch { responseError = error } } if responseError != nil { throw responseError! } return results ?? [] } } private extension NSManagedObjectContext { func fetchRequest (className: String) -> NSFetchRequest? { guard let description = NSEntityDescription.entityForName(className, inManagedObjectContext: self) else { return nil } let request = NSFetchRequest(entityName: className) request.entity = description return request } }
mit
54a2c95f86fc679a0449e77c3645049f
29.844444
141
0.62509
4.953571
false
false
false
false
danpratt/Simply-Zen
QuotesAPI Playground.playground/Contents.swift
1
2291
//: Playground - noun: a place where people can play import UIKit import PlaygroundSupport // this line tells the Playground to execute indefinitely PlaygroundPage.current.needsIndefiniteExecution = true // MARK: - QOD let urlString = "http://quotes.rest/qod.json?category=inspire" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "GET" let session = URLSession.shared let task = session.dataTask(with: request) { (data, response, error) in print("making request") guard (error == nil) else { print("error") return } guard let data = data else { print("No data returned") return } let parsedJSONData: [String:AnyObject]! do { parsedJSONData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject] } catch { print("Could not parse the data as JSON: '\(data)'") return } print(parsedJSONData) if let error = parsedJSONData["error"] as? [String:AnyObject], let code = error["code"] as? Int { if code == 429 { print("Too many requests") return } } guard let contentsData = parsedJSONData["contents"] as? [String:AnyObject] else { print("Failed to get contents") return } print(contentsData) guard let quotesArrayData = contentsData["quotes"] as? [[String:AnyObject]] else { print("Failed to get quote data") return } let quotesData = quotesArrayData[0] guard let author = quotesData["author"] as? String else { print("Couldn't get author") return } guard let background = quotesData["background"] as? String else { print("Couldn't get background") return } guard let quote = quotesData["quote"] as? String else { print("Couldn't get quote") return } if let url = URL(string: background) { DispatchQueue.main.async { let imageData = try? Data(contentsOf: url) let image = UIImage(data: imageData!) } } print("Author: \(author)") print("Background URL: \(background)") print("Quote: \(quote)") } task.resume()
apache-2.0
841ca457a88b7a176fd5eb4d1cd90412
24.455556
118
0.60454
4.36381
false
false
false
false
SkyGrass/souyun
souyun/ListViewController.swift
1
2336
// // ListViewController.swift // souyun // // Created by SkyGrass on 16/5/26. // Copyright © 2016年 SkyGrass. All rights reserved. // import UIKit class ListViewController: UIViewController,UITableViewDelegate{ var searchword:String? var apiclient:NewApiClient? var showapirequest:ShowApiRequest? var listView:ListView? var listdata:Viewdatas? var waitView:WaitView? @IBAction func btnBack(sender: AnyObject) { self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.translucent = false listdata = Viewdatas() waitView = WaitView(frame: CGRect(x: 0 , y: 0, width: self.view.frame.width, height: self.view.frame.height)) waitView?.labMsg.text = self.navigationItem.title self.view.addSubview(waitView!) showapirequest = ShowApiRequest(url: SHOWAPI_URL!, appId: SHOWAPI_APPID!, secret: SHOWAPI_SECRET!) apiclient = NewApiClient() apiclient?.search(showapirequest!, _searchword: self.searchword!, _pageindex: 1, _completionHandler: { (data,error) in if error?.code! != 0 { HUD.show(self.view, message:error!.errMsg!) self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil) return } if data!.count > 0 { self.navigationItem.title? = self.searchword! self.listdata = data! self.listView = ListView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height), _data:self.listdata!) self.view.addSubview(self.listView!) self.waitView?.hidden = true self.listView?.list.delegate = self }else{ HUD.show(self.view, message:error!.errMsg!) } }) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let url = listdata![indexPath.row].url! let controller:WebViewController = WebViewController() controller.url = url self.navigationController?.pushViewController(controller, animated: true) } }
apache-2.0
c29ea95381272c2adcfcd22b4bb70402
37.883333
151
0.635662
4.401887
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Services/MercadoPagoServices.swift
1
14308
import Foundation // Se importa MLCardForm para reutilizar la clase de Reachability import MLCardForm class MercadoPagoServices: NSObject { private var processingModes: [String] = PXServicesURLConfigs.MP_DEFAULT_PROCESSING_MODES private var branchId: String? private var baseURL: String! = PXServicesURLConfigs.MP_API_BASE_URL private var gatewayBaseURL: String! private var language: String = NSLocale.preferredLanguages[0] private let customService: CustomService private let remedyService: RemedyService private let gatewayService: TokenService private let checkoutService: CheckoutService // MARK: - Internal properties var reachability: Reachability? var hasInternet: Bool = true // MARK: - Open perperties open var publicKey: String open var privateKey: String? open var checkoutType: String? // MARK: - Initialization init( publicKey: String, privateKey: String? = nil, customService: CustomService = CustomServiceImpl(), remedyService: RemedyService = RemedyServiceImpl(), gatewayService: TokenService = TokenServiceImpl(), checkoutService: CheckoutService = CheckoutServiceImpl(), checkoutType: String? ) { self.publicKey = publicKey self.privateKey = privateKey self.customService = customService self.remedyService = remedyService self.gatewayService = gatewayService self.checkoutService = checkoutService self.checkoutType = checkoutType ?? PXCheckoutType.DEFAULT_REGULAR.getString() super.init() addReachabilityObserver() } deinit { removeReachabilityObserver() } func update(processingModes: [String]?, branchId: String? = nil) { self.processingModes = processingModes ?? PXServicesURLConfigs.MP_DEFAULT_PROCESSING_MODES self.branchId = branchId } func getTimeOut() -> TimeInterval { return 15.0 } func resetESCCap(cardId: String, headers: [String: String]?, onCompletion : @escaping () -> Void) { customService.resetESCCap(cardId: cardId, privateKey: privateKey, headers: headers) { _ in onCompletion() } } func getOpenPrefInitSearch(pref: PXCheckoutPreference, cardsWithEsc: [String], oneTapEnabled: Bool, splitEnabled: Bool, discountParamsConfiguration: PXDiscountParamsConfiguration?, flow: String?, charges: [PXPaymentTypeChargeRule], paymentMethodRules: [String]?, headers: [String: String]?, newCardId: String?, newAccountId: String?, callback : @escaping (PXInitDTO) -> Void, failure: @escaping ((_ error: PXError) -> Void)) { let bodyFeatures = PXInitFeatures(oneTap: oneTapEnabled, split: splitEnabled) let body = PXInitBody(preference: pref, publicKey: publicKey, flow: flow, cardsWithESC: cardsWithEsc, charges: charges, paymentMethodRules: paymentMethodRules, paymentMethodBehaviours: nil, discountConfiguration: discountParamsConfiguration, features: bodyFeatures, newCardId: newCardId, newAccountId: newAccountId, checkoutType: checkoutType) let bodyJSON = try? body.toJSON() checkoutService.getInit(preferenceId: nil, privateKey: privateKey, body: bodyJSON, headers: headers) { apiResponse in switch apiResponse { case .success(let dto): callback(dto) case .failure(let error): failure(error) } } } func getClosedPrefInitSearch(preferenceId: String, cardsWithEsc: [String], oneTapEnabled: Bool, splitEnabled: Bool, discountParamsConfiguration: PXDiscountParamsConfiguration?, flow: String?, charges: [PXPaymentTypeChargeRule], paymentMethodRules: [String]?, paymentMethodBehaviours: [PXPaymentMethodBehaviour]?, headers: [String: String]?, newCardId: String?, newAccountId: String?, callback : @escaping (PXInitDTO) -> Void, failure: @escaping ((_ error: PXError) -> Void)) { let bodyFeatures = PXInitFeatures(oneTap: oneTapEnabled, split: splitEnabled) let body = PXInitBody(preference: nil, publicKey: publicKey, flow: flow, cardsWithESC: cardsWithEsc, charges: charges, paymentMethodRules: paymentMethodRules, paymentMethodBehaviours: paymentMethodBehaviours, discountConfiguration: discountParamsConfiguration, features: bodyFeatures, newCardId: newCardId, newAccountId: newAccountId, checkoutType: checkoutType) let bodyJSON = try? body.toJSON() checkoutService.getInit(preferenceId: preferenceId, privateKey: privateKey, body: bodyJSON, headers: headers) { apiResponse in switch apiResponse { case .success(let dto): callback(dto) case .failure(let error): failure(error) } } } func createPayment(url: String, uri: String, transactionId: String? = nil, paymentDataJSON: Data, query: [String: String]? = nil, headers: [String: String]? = nil, callback : @escaping (PXPayment) -> Void, failure: @escaping ((_ error: PXError) -> Void)) { customService.createPayment(privateKey: privateKey, publicKey: publicKey, data: paymentDataJSON, headers: headers) { apiResponse in switch apiResponse { case .success(let payment): callback(payment) case .failure(let error): failure(error) } } } func getPointsAndDiscounts(url: String, uri: String, paymentIds: [String]? = nil, paymentMethodsIds: [String]? = nil, campaignId: String?, prefId: String?, platform: String, ifpe: Bool, merchantOrderId: Int?, headers: [String: String], paymentTypeId: String?, callback : @escaping (PXPointsAndDiscounts) -> Void, failure: @escaping (() -> Void)) { let parameters = CustomParametersModel(privateKey: privateKey, publicKey: publicKey, paymentMethodIds: getPaymentMethodsIds(paymentMethodsIds), paymentId: getPaymentIds(paymentIds), ifpe: String(ifpe), prefId: prefId, campaignId: campaignId, flowName: MPXTracker.sharedInstance.getFlowName(), merchantOrderId: merchantOrderId != nil ? String(merchantOrderId!) : nil, paymentTypeId: paymentTypeId) customService.getPointsAndDiscounts(data: nil, parameters: parameters, headers: headers) { apiResponse in switch apiResponse { case .success(let pointsAndDiscounts): callback(pointsAndDiscounts) case .failure: failure() } } } func createToken(cardToken: PXCardToken, callback : @escaping (PXToken) -> Void, failure: @escaping ((_ error: PXError) -> Void)) { createToken(cardToken: try? cardToken.toJSON(), callback: callback, failure: failure) } func createToken(savedESCCardToken: PXSavedESCCardToken, callback : @escaping (PXToken) -> Void, failure: @escaping ((_ error: PXError) -> Void)) { createToken(cardToken: try? savedESCCardToken.toJSON(), callback: callback, failure: failure) } func createToken(savedCardToken: PXSavedCardToken, callback : @escaping (PXToken) -> Void, failure: @escaping ((_ error: PXError) -> Void)) { createToken(cardToken: try? savedCardToken.toJSON(), callback: callback, failure: failure) } func createToken(cardToken: Data?, callback : @escaping (PXToken) -> Void, failure: @escaping ((_ error: PXError) -> Void)) { gatewayService.getToken(accessToken: privateKey, publicKey: publicKey, cardTokenJSON: cardToken) { apiResponse in switch apiResponse { case .success(let token): callback(token) case .failure(let error): failure(error) } } } func cloneToken(tokenId: String, securityCode: String, callback : @escaping (PXToken) -> Void, failure: @escaping ((_ error: NSError) -> Void)) { gatewayService.cloneToken(tokenId: tokenId, publicKey: publicKey, securityCode: securityCode) { apiResponse in switch apiResponse { case .success(let token): callback(token) case .failure(let error): failure(error) } } } func getRemedy(for paymentMethodId: String, payerPaymentMethodRejected: PXPayerPaymentMethodRejected, alternativePayerPaymentMethods: [PXRemedyPaymentMethod]?, customStringConfiguration: PXCustomStringConfiguration?, oneTap: Bool, success : @escaping (PXRemedy) -> Void, failure: @escaping ((_ error: PXError) -> Void)) { let remedy = PXRemedyBody(customStringConfiguration: customStringConfiguration, payerPaymentMethodRejected: payerPaymentMethodRejected, alternativePayerPaymentMethods: alternativePayerPaymentMethods) remedyService.getRemedy(paymentMethodId: paymentMethodId, privateKey: privateKey, oneTap: oneTap, remedy: remedy) { apiResponse in switch apiResponse { case .success(let remedy): success(remedy) case .failure(let error): failure(error) } } } // SETS func setBaseURL(_ baseURL: String) { self.baseURL = baseURL } func setGatewayBaseURL(_ gatewayBaseURL: String) { self.gatewayBaseURL = gatewayBaseURL } func getGatewayURL() -> String { if !String.isNullOrEmpty(gatewayBaseURL) { return gatewayBaseURL } return baseURL } class func getParamsPublicKey(_ merchantPublicKey: String) -> String { var params: String = "" params.paramsAppend(key: ApiParam.PUBLIC_KEY, value: merchantPublicKey) return params } class func getParamsAccessToken(_ payerAccessToken: String?) -> String { var params: String = "" params.paramsAppend(key: ApiParam.PAYER_ACCESS_TOKEN, value: payerAccessToken) return params } class func getParamsPublicKeyAndAcessToken(_ merchantPublicKey: String, _ payerAccessToken: String?) -> String { var params: String = "" if !String.isNullOrEmpty(payerAccessToken) { params.paramsAppend(key: ApiParam.PAYER_ACCESS_TOKEN, value: payerAccessToken!) } params.paramsAppend(key: ApiParam.PUBLIC_KEY, value: merchantPublicKey) return params } class func getParamsAccessTokenAndPaymentIdsAndPlatform(_ payerAccessToken: String?, _ paymentIds: [String]?, _ platform: String?) -> String { var params: String = "" if let payerAccessToken = payerAccessToken, !payerAccessToken.isEmpty { params.paramsAppend(key: ApiParam.PAYER_ACCESS_TOKEN, value: payerAccessToken) } if let paymentIds = paymentIds, !paymentIds.isEmpty { var paymentIdsString = "" for (index, paymentId) in paymentIds.enumerated() { if index != 0 { paymentIdsString.append(",") } paymentIdsString.append(paymentId) } params.paramsAppend(key: ApiParam.PAYMENT_IDS, value: paymentIdsString) } if let platform = platform { params.paramsAppend(key: ApiParam.PLATFORM, value: platform) } return params } func getPaymentIds(_ paymentIds: [String]?) -> String { var paymentIdsString = "" if let paymentIds = paymentIds, !paymentIds.isEmpty { for (index, paymentId) in paymentIds.enumerated() { if index != 0 { paymentIdsString.append(",") } paymentIdsString.append(paymentId) } } return paymentIdsString } func getPaymentMethodsIds(_ paymentMethodsIds: [String]?) -> String { var paymentMethodsIdsString = "" if let paymentMethodsIds = paymentMethodsIds { for (index, paymentMethodId) in paymentMethodsIds.enumerated() { if index != 0 { paymentMethodsIdsString.append(",") } if paymentMethodId.isNotEmpty { paymentMethodsIdsString.append(paymentMethodId) } } } return paymentMethodsIdsString } func setLanguage(language: String) { self.language = language } func getLanguage() -> String { return self.language } }
mit
80a123ec3600aaf8aefb02e02f68f5a0
43.434783
430
0.571429
5.358801
false
false
false
false
hacktoolkit/hacktoolkit-ios_lib
Hacktoolkit/lib/Twitter/models/TwitterUser.swift
1
5050
// // TwitterUser.swift // // Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai) // Copyright (c) 2014 Hacktoolkit. All rights reserved. // import Foundation var _currentTwitterUser: TwitterUser? let TWITTER_CURRENT_USER_KEY = "kTwitterCurrentUserKey" let TWITTER_USER_DID_LOGIN_NOTIFICATION = "twitterUserDidLoginNotification" let TWITTER_USER_DID_LOGOUT_NOTIFICATION = "twitterUserDidLogoutNotification" class TwitterUser: NSObject { var userDictionary: NSDictionary var name: String? var screenname: String? var profileImageUrl: String? var tagline: String? var location: String? var numTweets: Int? var friendsCount: Int? var followersCount: Int? init(userDictionary: NSDictionary) { self.userDictionary = userDictionary name = userDictionary["name"] as? String screenname = userDictionary["screen_name"] as? String profileImageUrl = userDictionary["profile_image_url"] as? String tagline = userDictionary["description"] as? String location = userDictionary["location"] as? String numTweets = userDictionary["statusesCount"] as? Int friendsCount = userDictionary["friendsCount"] as? Int followersCount = userDictionary["followersCount"] as? Int } class var currentUser: TwitterUser? { get { if _currentTwitterUser == nil { var data = HTKUtils.getDefaults(TWITTER_CURRENT_USER_KEY) as? NSData if data != nil { var userDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary _currentTwitterUser = TwitterUser(userDictionary: userDictionary) } } return _currentTwitterUser } set (user) { _currentTwitterUser = user if _currentTwitterUser != nil { var data = NSJSONSerialization.dataWithJSONObject(user!.userDictionary, options: nil, error: nil) HTKUtils.setDefaults(TWITTER_CURRENT_USER_KEY, withValue: data) } else { HTKUtils.setDefaults(TWITTER_CURRENT_USER_KEY, withValue: nil) } } } func logout() { TwitterUser.currentUser = nil TwitterClient.sharedInstance.logout() NSNotificationCenter.defaultCenter().postNotificationName(TWITTER_USER_DID_LOGOUT_NOTIFICATION, object: nil) } } // user = { // "contributors_enabled" = 0; // "created_at" = "Wed Apr 02 01:07:12 +0000 2008"; // "default_profile" = 0; // "default_profile_image" = 0; // description = "CrunchBase is the world\U2019s most comprehensive dataset of startup activity and it\U2019s accessible to everyone."; // entities = { // description = { // urls = ( // ); // }; // url = { // urls = ( // { // "display_url" = "crunchbase.com"; // "expanded_url" = "http://www.crunchbase.com"; // indices = ( // 0, // 22 // ); // url = "http://t.co/2sOf3bjuA7"; // } // ); // }; // }; // "favourites_count" = 159; // "follow_request_sent" = 0; // "followers_count" = 31183; // following = 1; // "friends_count" = 22424; // "geo_enabled" = 1; // id = 14279577; // "id_str" = 14279577; // "is_translation_enabled" = 0; // "is_translator" = 0; // lang = en; // "listed_count" = 1083; // location = "San Francisco"; // name = CrunchBase; // notifications = 0; // "profile_background_color" = C0DEED; // "profile_background_image_url" = "http://abs.twimg.com/images/themes/theme1/bg.png"; // "profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme1/bg.png"; // "profile_background_tile" = 0; // "profile_banner_url" = "https://pbs.twimg.com/profile_banners/14279577/1398278857"; // "profile_image_url" = "http://pbs.twimg.com/profile_images/458740928761446401/O2mWKocb_normal.png"; // "profile_image_url_https" = "https://pbs.twimg.com/profile_images/458740928761446401/O2mWKocb_normal.png"; // "profile_link_color" = 2992A7; // "profile_sidebar_border_color" = C0DEED; // "profile_sidebar_fill_color" = DDEEF6; // "profile_text_color" = 333333; // "profile_use_background_image" = 1; // protected = 0; // "screen_name" = crunchbase; // "statuses_count" = 2171; // "time_zone" = "Pacific Time (US & Canada)"; // url = "http://t.co/2sOf3bjuA7"; // "utc_offset" = "-25200"; // verified = 0; // };
mit
865eff88fad52aea1bbe1ec79956b09a
37.257576
142
0.55604
3.854962
false
false
false
false
fancymax/12306ForMac
12306ForMac/TicketViewControllers/PassengerViewController.swift
1
750
// // HorizontalListObjectViewController.swift // // // Created by fancymax on 15/10/5. // // import Cocoa class PassengerViewController: NSViewController { var passenger:PassengerDTO? @IBOutlet weak var passengerCheckBox: NSButton! override func viewDidLoad() { super.viewDidLoad() passengerCheckBox.title = passenger!.passenger_name } @IBAction func unSelectPassenger(_ sender: NSButton) { passenger?.isChecked = false sender.state = NSOnState self.view.isHidden = true } func select(){ if passenger!.isChecked { self.view.isHidden = false } else{ self.view.isHidden = true } } }
mit
faa26518c233c808c9ba76a96b6f41ff
19.27027
59
0.594667
4.518072
false
false
false
false
yourtion/Demo_SwiftFaceDetection
SwiftFaceDetection/SwiftFaceDetection/ViewController.swift
1
5149
// // ViewController.swift // SwiftFaceDetection // // Created by YourtionGuo on 11/11/15. // Copyright © 2015 Yourtion. All rights reserved. // import UIKit import AVFoundation class FaceViewController: UIViewController { var previewLayer:AVCaptureVideoPreviewLayer! var faceRectCALayer:CALayer! private var currentCameraDevice:AVCaptureDevice? private var sessionQueue:dispatch_queue_t = dispatch_queue_create("com.yourtion.SwiftFaceDetection.session_access_queue", DISPATCH_QUEUE_SERIAL) private var session:AVCaptureSession! private var backCameraDevice:AVCaptureDevice? private var frontCameraDevice:AVCaptureDevice? private var metadataOutput:AVCaptureMetadataOutput! override func viewDidLoad() { super.viewDidLoad() self.session = AVCaptureSession() self.session.sessionPreset = AVCaptureSessionPreset640x480 let availableCameraDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in availableCameraDevices as! [AVCaptureDevice] { if device.position == .Back { backCameraDevice = device } else if device.position == .Front { frontCameraDevice = device } } let possibleCameraInput: AnyObject? do { possibleCameraInput = try AVCaptureDeviceInput(device: frontCameraDevice) } catch _ { possibleCameraInput = nil return } if let backCameraInput = possibleCameraInput as? AVCaptureDeviceInput { if self.session.canAddInput(backCameraInput) { self.session.addInput(backCameraInput) } else { return } } previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.frame = view.bounds previewLayer.frame = self.view.bounds; previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; view.layer.addSublayer(previewLayer) let metadataOutput = AVCaptureMetadataOutput() metadataOutput.setMetadataObjectsDelegate(self, queue: self.sessionQueue) if session.canAddOutput(metadataOutput) { session.addOutput(metadataOutput) } metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeFace] if session.canAddOutput(metadataOutput) { session.addOutput(metadataOutput) } //初始化人脸框 faceRectCALayer = CALayer() faceRectCALayer.zPosition = 1 faceRectCALayer.borderColor = UIColor.redColor().CGColor faceRectCALayer.borderWidth = 3.0 faceRectCALayer.zPosition = 20 self.faceRectCALayer.hidden = true self.previewLayer.addSublayer(faceRectCALayer) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { if (!session.running) { self.session.startRunning() } } } extension FaceViewController: AVCaptureMetadataOutputObjectsDelegate { func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { var faces = Array<(id:Int,frame:CGRect)>() for metadataObject in metadataObjects as! [AVMetadataObject] { if metadataObject.type == AVMetadataObjectTypeFace { if let faceObject = metadataObject as? AVMetadataFaceObject { let transformedMetadataObject = previewLayer.transformedMetadataObjectForMetadataObject(metadataObject) let face:(id: Int, frame: CGRect) = (faceObject.faceID, transformedMetadataObject.bounds) faces.append(face) } } } print("FACE",faces) if (faces.count>0){ self.setLayerHidden(false) dispatch_async(dispatch_get_main_queue(), {() -> Void in self.faceRectCALayer.frame = self.findMaxFaceRect(faces) }); } else { self.setLayerHidden(true) } } func setLayerHidden(hidden:Bool) { if (self.faceRectCALayer.hidden != hidden){ print("hidden: ", hidden) dispatch_async(dispatch_get_main_queue(), {() -> Void in self.faceRectCALayer.hidden = hidden }); } } func findMaxFaceRect(faces:Array<(id:Int,frame:CGRect)>) -> CGRect { if (faces.count == 1) { return faces[0].frame } var maxFace = CGRect.zero var maxFace_size = maxFace.size.width + maxFace.size.height for face in faces { let face_size = face.frame.size.width + face.frame.size.height if (face_size > maxFace_size) { maxFace = face.frame maxFace_size = face_size } } return maxFace } }
apache-2.0
af7039de2e788445502b930f37b16319
34.42069
162
0.626947
5.327801
false
false
false
false
XVimProject/XVim2
XVim2/XVim/XVimHistoryHandler.swift
1
736
// // XVimHistoryHandler.swift // XVim2 // // Created by pebble8888 on 2020/05/24. // Copyright © 2020 Shuichiro Suzuki. All rights reserved. // import Foundation @objc class XVimHistoryHandler: NSObject { private var history: [String] = [] @objc public func addEntry(_ entry: String) { history.insert(entry, at: 0) } @objc public func entry(_ number: Int, prefix: String) -> String? { if number == 0 { return nil } var count: Int = 0 for obj in history { if obj.hasPrefix(prefix) { count += 1 if number == count { return obj } } } return nil } }
mit
62acb4af57e37f0e5fe51c960f5922cb
21.272727
71
0.514286
4.129213
false
false
false
false
nanthi1990/LocationPicker
LocationPicker/Location.swift
1
1291
// // Location.swift // LocationPicker // // Created by Almas Sapargali on 7/29/15. // Copyright (c) 2015 almassapargali. All rights reserved. // import Foundation import CoreLocation import AddressBookUI // class because protocol public class Location: NSObject { public let name: String? // difference from placemark location is that if location was reverse geocoded, // then location point to user selected location public let location: CLLocation public let placemark: CLPlacemark var address: String { // try to build full address first if let addressDic = placemark.addressDictionary { if let lines = addressDic["FormattedAddressLines"] as? [String] { return lines.joinWithSeparator(", ") } else { // fallback return ABCreateStringWithAddressDictionary(addressDic, true) } } else { return "\(coordinate.latitude), \(coordinate.longitude)" } } public init(name: String?, location: CLLocation? = nil, placemark: CLPlacemark) { self.name = name self.location = location ?? placemark.location! self.placemark = placemark } } import MapKit extension Location: MKAnnotation { @objc public var coordinate: CLLocationCoordinate2D { return location.coordinate } public var title: String? { return name ?? address } }
mit
c7f3e4e19689de6884469fbafe14505d
22.925926
82
0.72347
3.924012
false
false
false
false
jkolb/Lilliput
Sources/Lilliput/MemoryBuffer.swift
1
1688
/* The MIT License (MIT) Copyright (c) 2018 Justin Kolb 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. */ public final class MemoryBuffer : ByteBuffer { public let bytes: UnsafeMutableRawPointer public let count: Int public init(copyBytes: UnsafeMutableRawPointer? = nil, count: Int) { precondition(count >= 0) self.bytes = UnsafeMutableRawPointer.allocate(byteCount: count * MemoryLayout<UInt8>.stride, alignment: MemoryLayout<UInt8>.alignment) self.count = count if let copyBytes = copyBytes { bytes.copyMemory(from: copyBytes, byteCount: count) } } deinit { bytes.deallocate() } }
mit
2e935dc3080f55513bc62cc37b11da27
39.190476
142
0.73519
4.921283
false
false
false
false
cocoaswifty/V2EX
V2EX/Connect.swift
1
3296
// // Connect.swift // V2EX // // Created by jianhao on 2016/9/18. // Copyright © 2016年 cocoaswifty. All rights reserved. // import Foundation import Alamofire enum ConnectError: Error { case BadURL(message: String) // case missAccessToken(name: ApiName, message: String) case Failure } enum ApiType { case Hot case Latest case Leplies } class Connect { func requestGET(apiType: ApiType, parameters: Parameters = [:], completion: @escaping (Data) -> (), completedProgress: @escaping (Double) -> ()) { var url = "" switch apiType { case .Hot: url = API.HotTopics case .Latest: url = API.LatestTopics case .Leplies: url = API.LepliesTopics } Alamofire.request(url, parameters: parameters).response { response in guard let data = response.data else { return } completion(data) }.downloadProgress { progress in completedProgress(progress.fractionCompleted) // print("Progress: \(progress.fractionCompleted)") } } // let json = try? JSONSerialization.jsonObject(with: data, options: []) // print(json) // // func postNewScore(name: String, moves: Int) { // // // let parameters : [String : AnyObject] = [ // "Moves": moves, // "UserName" : name // ] // // Alamofire.request(.POST, "https://...", parameters: parameters, encoding: .JSON).responseString { response in // print("Response String: \(response.result.value)") // } // } // // func requestGET(_ section: ApiName, id: Int = 0, completion: (JSON?, NSError?) -> ()) throws { // // var url = "" // switch section { // case .user: // url = Config.QC_SERVER + "/user" // default: // break // } // // guard Config.ACCESS_TOKEN != "access_token" else { throw ConnectError.missAccessToken(name: section, message: "\(section.hashValue) token is nil") } // // Alamofire.request(.GET, url, headers: Config.HEADERS) // .responseJSON { response in // // print("status \(response.response)") // // switch response.result { // case .Success(let value): // let json = JSON(value) // if let statusCode = (response.response?.statusCode) , statusCode == 401 { // let error = NSError(domain: "domain", code: 401, userInfo: ["error": "invalid_token", // "error_description": "Invalid access token: \(Config.ACCESS_TOKEN)"]) // completion(nil, error) // }else { // completion(json, nil) // } // // case .Failure(let error): // debugPrint(error) // completion(nil, error) // } // } // } }
apache-2.0
513f66ab18101bfc2590829e50bbffb2
29.775701
162
0.47768
4.492497
false
false
false
false
dalequi/yelpitoff
Demo/OAuthSwift/OAuthSwift/OAuthSwiftCredential.swift
1
6530
// // OAuthSwiftCredential.swift // OAuthSwift // // Created by Dongri Jin on 6/22/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation public class OAuthSwiftCredential: NSObject, NSCoding { public enum Version { case OAuth1, OAuth2 public var shortVersion : String { switch self { case .OAuth1: return "1.0" case .OAuth2: return "2.0" } } public var signatureMethod: String { return "HMAC-SHA1" } } var consumer_key: String = String() var consumer_secret: String = String() public var oauth_token: String = String() public var oauth_token_secret: String = String() var oauth_verifier: String = String() public var version: Version = .OAuth1 override init(){ } public init(consumer_key: String, consumer_secret: String){ self.consumer_key = consumer_key self.consumer_secret = consumer_secret } public init(oauth_token: String, oauth_token_secret: String){ self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret } private struct CodingKeys { static let base = NSBundle.mainBundle().bundleIdentifier! + "." static let consumerKey = base + "comsumer_key" static let consumerSecret = base + "consumer_secret" static let oauthToken = base + "oauth_token" static let oauthTokenSecret = base + "oauth_token_secret" static let oauthVerifier = base + "oauth_verifier" } // Cannot declare a required initializer within an extension. // extension OAuthSwiftCredential: NSCoding { public required convenience init?(coder decoder: NSCoder) { self.init() self.consumer_key = (decoder.decodeObjectForKey(CodingKeys.consumerKey) as? String) ?? String() self.consumer_secret = (decoder.decodeObjectForKey(CodingKeys.consumerSecret) as? String) ?? String() self.oauth_token = (decoder.decodeObjectForKey(CodingKeys.oauthToken) as? String) ?? String() self.oauth_token_secret = (decoder.decodeObjectForKey(CodingKeys.oauthTokenSecret) as? String) ?? String() self.oauth_verifier = (decoder.decodeObjectForKey(CodingKeys.oauthVerifier) as? String) ?? String() } public func encodeWithCoder(coder: NSCoder) { coder.encodeObject(self.consumer_key, forKey: CodingKeys.consumerKey) coder.encodeObject(self.consumer_secret, forKey: CodingKeys.consumerSecret) coder.encodeObject(self.oauth_token, forKey: CodingKeys.oauthToken) coder.encodeObject(self.oauth_token_secret, forKey: CodingKeys.oauthTokenSecret) coder.encodeObject(self.oauth_verifier, forKey: CodingKeys.oauthVerifier) } // } // End NSCoding extension public func makeHeaders(url:NSURL, method: OAuthSwiftHTTPRequest.Method, parameters: Dictionary<String, AnyObject>) -> Dictionary<String, String> { switch self.version { case .OAuth1: return ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters)] case .OAuth2: return ["Authorization": "Bearer \(self.oauth_token)"] } } public func authorizationHeaderForMethod(method: OAuthSwiftHTTPRequest.Method, url: NSURL, parameters: Dictionary<String, AnyObject>) -> String { assert(self.version == .OAuth1) var authorizationParameters = Dictionary<String, AnyObject>() authorizationParameters["oauth_version"] = self.version.shortVersion authorizationParameters["oauth_signature_method"] = self.version.signatureMethod authorizationParameters["oauth_consumer_key"] = self.consumer_key authorizationParameters["oauth_timestamp"] = String(Int64(NSDate().timeIntervalSince1970)) authorizationParameters["oauth_nonce"] = (NSUUID().UUIDString as NSString).substringToIndex(8) if (self.oauth_token != ""){ authorizationParameters["oauth_token"] = self.oauth_token } for (key, value) in parameters { if key.hasPrefix("oauth_") { authorizationParameters.updateValue(value, forKey: key) } } let combinedParameters = authorizationParameters.join(parameters) let finalParameters = combinedParameters authorizationParameters["oauth_signature"] = self.signatureForMethod(method, url: url, parameters: finalParameters) var parameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(dataEncoding).componentsSeparatedByString("&") as [String] parameterComponents.sortInPlace { $0 < $1 } var headerComponents = [String]() for component in parameterComponents { let subcomponent = component.componentsSeparatedByString("=") as [String] if subcomponent.count == 2 { headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"") } } return "OAuth " + headerComponents.joinWithSeparator(", ") } public func signatureForMethod(method: OAuthSwiftHTTPRequest.Method, url: NSURL, parameters: Dictionary<String, AnyObject>) -> String { var tokenSecret: NSString = "" tokenSecret = self.oauth_token_secret.urlEncodedStringWithEncoding(dataEncoding) let encodedConsumerSecret = self.consumer_secret.urlEncodedStringWithEncoding(dataEncoding) let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)" var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(dataEncoding).componentsSeparatedByString("&") as [String] parameterComponents.sortInPlace { $0 < $1 } let parameterString = parameterComponents.joinWithSeparator("&") let encodedParameterString = parameterString.urlEncodedStringWithEncoding(dataEncoding) let encodedURL = url.absoluteString.urlEncodedStringWithEncoding(dataEncoding) let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)" let key = signingKey.dataUsingEncoding(NSUTF8StringEncoding)! let msg = signatureBaseString.dataUsingEncoding(NSUTF8StringEncoding)! let sha1 = HMAC.sha1(key: key, message: msg)! return sha1.base64EncodedStringWithOptions([]) } }
mit
22df12433dd72e2a3db72d7e6722f758
43.121622
151
0.665237
5.24498
false
false
false
false
tensorflow/swift-models
Examples/GPT2-WikiText2/main.swift
1
2374
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Datasets import TensorFlow import TextModels import TensorBoard import TrainingLoop // Avoid the eager mode runtime from taking all memory // and leaving none to X10 when run on the GPU. _ = _ExecutionContext.global // Until https://github.com/tensorflow/swift-apis/issues/993 is fixed, default to the eager-mode // device on macOS instead of X10. #if os(macOS) let device = Device.defaultTFEager #else let device = Device.defaultXLA #endif var gpt = try GPT2() let sequenceLength = gpt.contextSize let trainingBatchSize = 2 let validationBatchSize = 2 let dataset = TextUnsupervised(bpe: gpt.bpe, variant: .wikiText2, trainingBatchSize: trainingBatchSize, validationBatchSize: validationBatchSize, sequenceLength: sequenceLength, on: device) print("Dataset acquired.") /// Reshape the `logits` and `labels` to required shape before calling /// standard softmaxCrossEntropy API. /// /// - Note: This can potentially be added to standard softmaxCrossEntropy API. @differentiable public func softmaxCrossEntropyReshaped<Scalar>(logits: Tensor<Scalar>, labels: Tensor<Int32>) -> Tensor< Scalar > where Scalar: TensorFlowFloatingPoint { return softmaxCrossEntropy( logits: logits.reshaped(to: [logits.shape.dropLast().reduce(1, *), logits.shape.last!]), labels: labels.reshaped(to: [labels.shape.reduce(1, *)]), reduction: _mean) } var trainingLoop: TrainingLoop = TrainingLoop( training: dataset.training, validation: dataset.validation, optimizer: Adam(for: gpt.model, learningRate: 0.001), lossFunction: softmaxCrossEntropyReshaped, metrics: [.accuracy, .perplexity], callbacks: [tensorBoardStatisticsLogger()]) print("Starting training...") try! trainingLoop.fit(&gpt.model, epochs: 10, on: device)
apache-2.0
ddfdfeaf2ff105f5598e8090b5ecf1c5
35.523077
105
0.758214
3.885434
false
false
false
false
mzp/OctoEye
Sources/GithubAPI/FetchRepositories.swift
1
2718
// // FetchRepositories.swift // OctoEye // // Created by mzp on 2017/08/01. // Copyright © 2017 mzp. All rights reserved. // import BrightFutures import GraphQLicious import Result internal class InputObject: ArgumentValue { private let values: [String:String] init(_ values: [String:String]) { self.values = values } public var asGraphQLArgument: String { let fields = values.map { (key, value) in "\(key): \(value)" } return "{\(fields.joined(separator: ","))}" } } internal class FetchRepositories { typealias Cursor = String struct Repositories: Codable { let nodes: [RepositoryObject] let pageInfo: PageInfoObject } struct Viewer: Codable { let repositories: Repositories } struct Response: Codable { let viewer: Viewer } private let github: GithubClient init(github: GithubClient) { self.github = github } func call(after: Cursor? = nil) -> Future<([RepositoryObject], Cursor?), AnyError> { return github.query(query(after: after)).map { (response: Response) in var cursor: Cursor? = nil if response.viewer.repositories.pageInfo.hasNextPage { cursor = response.viewer.repositories.pageInfo.endCursor } return (response.viewer.repositories.nodes, cursor) } } private func query(after: Cursor? = nil) -> Query { return Query( request: Request( name: "viewer", arguments: [], fields: [ Request(name: "repositories", arguments: [ Argument(key: "first", value: 10), Argument(key: "orderBy", value: InputObject([ "field": "PUSHED_AT", "direction": "DESC" ])) ] + pagingQuery(after: after), fields: [ Request(name: "nodes", fields: [ RepositoryObject.fragment ]), Request(name: "pageInfo", fields: [ PageInfoObject.fragment ]) ]) ]), fragments: [ PageInfoObject.fragment, RepositoryObject.fragment ]) } private func pagingQuery(after: Cursor?) -> [Argument] { return after.map { [Argument(key: "after", value: $0)] } ?? [] } }
mit
d9785f72cbd4dc1791f887f8cbfc90f5
30.229885
88
0.48767
5.155598
false
false
false
false
cuappdev/podcast-ios
old/Podcast/EpisodeDetailHeaderView.swift
1
7061
// // EpisodeDetailHeaderView.swift // Podcast // // Created by Mark Bryan on 4/11/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit protocol EpisodeDetailHeaderViewDelegate: class { func episodeDetailHeaderDidPressPlayButton(view: EpisodeDetailHeaderView) func episodeDetailHeaderDidPressMoreButton(view: EpisodeDetailHeaderView) func episodeDetailHeaderDidPressRecommendButton(view: EpisodeDetailHeaderView) func episodeDetailHeaderDidPressBookmarkButton(view: EpisodeDetailHeaderView) func episodeDetailHeaderDidPressSeriesTitleLabel(view: EpisodeDetailHeaderView) } class EpisodeDetailHeaderView: UIView { static let marginSpacing: CGFloat = 18 //used in EpisodeDetailViewController to set content insets var episodeArtworkImageView: ImageView! var seriesTitleLabel: UIButton! var publisherLabel: UILabel! var episodeTitleLabel: UILabel! var dateLabel: UILabel! var descriptionTextView: UITextView! var episodeUtilityButtonBarView: EpisodeUtilityButtonBarView! weak var delegate: EpisodeDetailHeaderViewDelegate? let marginSpacing: CGFloat = EpisodeDetailHeaderView.marginSpacing let smallPadding: CGFloat = 5 let artworkDimension: CGFloat = 79 let bottomViewYSpacing: CGFloat = 9 init() { super.init(frame: .zero) backgroundColor = UIColor.colorFromCode(0xfcfcfe) episodeArtworkImageView = ImageView(frame: CGRect(x: 0, y: 0, width: artworkDimension, height: artworkDimension)) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didPressSeriesTitleLabel)) episodeArtworkImageView.isUserInteractionEnabled = true episodeArtworkImageView.addGestureRecognizer(tapGestureRecognizer) addSubview(episodeArtworkImageView) seriesTitleLabel = UIButton() seriesTitleLabel.showsTouchWhenHighlighted = true seriesTitleLabel.setTitle("", for: .normal) seriesTitleLabel.setTitleColor(.offBlack, for: .normal) seriesTitleLabel.titleLabel!.font = ._20SemiboldFont() seriesTitleLabel.titleLabel!.textAlignment = .left seriesTitleLabel.titleLabel!.lineBreakMode = .byWordWrapping seriesTitleLabel.contentHorizontalAlignment = .left seriesTitleLabel.titleLabel!.numberOfLines = 2 seriesTitleLabel.addTarget(self, action: #selector(didPressSeriesTitleLabel), for: .touchUpInside) addSubview(seriesTitleLabel) episodeTitleLabel = UILabel() episodeTitleLabel.font = ._20SemiboldFont() episodeTitleLabel.lineBreakMode = .byWordWrapping episodeTitleLabel.numberOfLines = 3 addSubview(episodeTitleLabel) dateLabel = UILabel() dateLabel.font = ._12RegularFont() dateLabel.numberOfLines = 1 dateLabel.textColor = .slateGrey addSubview(dateLabel) episodeUtilityButtonBarView = EpisodeUtilityButtonBarView(frame: .zero) episodeUtilityButtonBarView.hasBottomLineSeparator = true addSubview(episodeUtilityButtonBarView) episodeUtilityButtonBarView.playButton.addTarget(self, action: #selector(playButtonTapped), for: .touchUpInside) episodeUtilityButtonBarView.moreButton.addTarget(self, action: #selector(moreButtonTapped), for: .touchUpInside) episodeUtilityButtonBarView.bookmarkButton.addTarget(self, action: #selector(bookmarkButtonTapped), for: .touchUpInside) episodeUtilityButtonBarView.recommendedButton.addTarget(self, action: #selector(recommendButtonTapped), for: .touchUpInside) episodeArtworkImageView.snp.makeConstraints { make in make.size.equalTo(artworkDimension) make.top.equalToSuperview().inset(marginSpacing) make.leading.equalToSuperview().inset(marginSpacing) } seriesTitleLabel.snp.makeConstraints { make in make.leading.equalTo(episodeArtworkImageView.snp.trailing).offset(marginSpacing) make.top.equalTo(episodeArtworkImageView.snp.top) make.trailing.equalToSuperview().inset(marginSpacing) } episodeTitleLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(marginSpacing) make.top.equalTo(episodeArtworkImageView.snp.bottom).offset(marginSpacing) } dateLabel.snp.makeConstraints { make in make.top.equalTo(episodeTitleLabel.snp.bottom).offset(smallPadding) make.leading.equalTo(episodeTitleLabel.snp.leading) make.trailing.equalTo(episodeTitleLabel.snp.trailing) } episodeUtilityButtonBarView.snp.makeConstraints { make in make.top.equalTo(dateLabel.snp.bottom).offset(bottomViewYSpacing) make.leading.trailing.equalToSuperview() make.height.equalTo(EpisodeUtilityButtonBarView.height) make.bottom.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() episodeArtworkImageView.addCornerRadius(height: artworkDimension) } func setup(for episode: Episode, downloadStatus: DownloadStatus) { episodeArtworkImageView.setImageAsynchronouslyWithDefaultImage(url: episode.smallArtworkImageURL) seriesTitleLabel.setTitle(episode.seriesTitle, for: .normal) episodeTitleLabel.text = episode.title episodeUtilityButtonBarView.setup(with: episode, downloadStatus) episodeUtilityButtonBarView.greyedOutLabel.isHidden = true // because the header view looks weird with it greyed out dateLabel.text = episode.getDateTimeLabelString(includeSeriesTitle: false) } // // Delegate Methods // func updateWithPlayButtonPress(episode: Episode) { episodeUtilityButtonBarView.playButton.configure(for: episode) } func setBookmarkButtonToState(isBookmarked: Bool) { episodeUtilityButtonBarView.bookmarkButton.isSelected = isBookmarked } func setRecommendedButtonToState(isRecommended: Bool, numberOfRecommendations: Int) { episodeUtilityButtonBarView.recommendedButton.setupWithNumber(isSelected: isRecommended, numberOf: numberOfRecommendations) } @objc func playButtonTapped() { delegate?.episodeDetailHeaderDidPressPlayButton(view: self) } @objc func bookmarkButtonTapped() { delegate?.episodeDetailHeaderDidPressBookmarkButton(view: self) } @objc func moreButtonTapped() { delegate?.episodeDetailHeaderDidPressMoreButton(view: self) } @objc func recommendButtonTapped() { delegate?.episodeDetailHeaderDidPressRecommendButton(view: self) } @objc func didPressSeriesTitleLabel() { delegate?.episodeDetailHeaderDidPressSeriesTitleLabel(view: self) } }
mit
3f1ebf98bd0c84ccdbe913ecdaecb142
42.04878
132
0.725921
5.43495
false
false
false
false
Pradeepkn/Mysore_App
MysoreApp/Network/TTNetwork/Managers/APIManager/APIManager.swift
1
6413
// // APIManager.swift // APIManager-Alamofire // // Created by Pradeep on 2/8/16. // Copyright © 2016 Pradeep. All rights reserved. // import Foundation import Alamofire typealias ResponseHandler = (AnyObject?, NSError?) -> Void class APIManager { // Class Stored Properties static let sharedInstance = APIManager() // Avoid initialization fileprivate init() { } static let rootKey = "Root"; static let expireKey = "Expires" // MARK : Initialize API Request func initiateRequest(_ apiObject: APIBase, apiRequestCompletionHandler:@escaping ResponseHandler) { var urlString = apiObject.urlForRequest() urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! if apiObject.isMultipartRequest() == true { var urlString = apiObject.urlForRequest() urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! Alamofire.upload(multipartFormData: { (multipartFormData) -> Void in apiObject.multipartData(multipartData: multipartFormData) }, to: urlString, encodingCompletion: { (encodingResult) -> Void in switch encodingResult { case .success(let upload, _, _): upload.responseData(){ [unowned self] response in if let data = response.result.value { self.serializeAPIResponse(apiObject, response: data as Data?, apiRequestCompletionHandler: apiRequestCompletionHandler, serializerCompletionHandler: nil) } else { apiRequestCompletionHandler(nil,nil) } } case .failure(_): let error = NSError(domain: apiObject.urlForRequest(), code: 404, userInfo: nil) apiRequestCompletionHandler(nil,error) } }) } else { var urlString = apiObject.urlForRequest() urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! let request = Alamofire.request(urlString, method: apiObject.requestType(), parameters: apiObject.requestParameter(), encoding: ((apiObject.isJSONRequest() == true) ? JSONEncoding.default : URLEncoding.default), headers: apiObject.customHTTPHeaders()) self.requestCompleted(request, apiObject: apiObject,apiRequestCompletionHandler: apiRequestCompletionHandler) } } // MARK: Request Completion Logic func requestCompleted(_ request: DataRequest?, apiObject: APIBase, apiRequestCompletionHandler:@escaping ResponseHandler) { if let request = request { // Mannual parsing request.responseData { [unowned self] response in if let data = response.result.value { self.serializeAPIResponse(apiObject, response: data as Data?, apiRequestCompletionHandler: apiRequestCompletionHandler) { [unowned self, request, apiObject] responseDictionary in self.cacheResponse(request, apiObject: apiObject, resposneDictionary: responseDictionary) } } else { apiRequestCompletionHandler(nil,nil) } } } else { let error = NSError(domain: apiObject.urlForRequest(), code: 404, userInfo: nil) apiRequestCompletionHandler(nil,error) } } // MARK: Cache API Response func cacheResponse(_ requestObject: DataRequest, apiObject: APIBase, resposneDictionary: Dictionary<String, AnyObject>) { guard apiObject.enableCacheControl() == true else { return } requestObject.response { responseStruct in if let _ = responseStruct.data { // Cache Control if let ttl = responseStruct.response?.allHeaderFields[APIManager.expireKey] as? String{ let resposneData = NSKeyedArchiver.archivedData(withRootObject: resposneDictionary) APICache.saveResponse(uniqueKey: apiObject.cacheKey(), apiObject: apiObject, cacheData: resposneData as Data as NSData, ttl: ttl) } } } } // MARK: Response serializer func serializeAPIResponse(_ apiObject: APIBase, response: Data?, apiRequestCompletionHandler:ResponseHandler, serializerCompletionHandler: ((Dictionary<String, AnyObject>) -> Void)?) { if let data = response { do { // Check if it is Dictionary if let jsonDictionary = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? Dictionary<String, AnyObject> { apiObject.parseAPIResponse(response: jsonDictionary) apiRequestCompletionHandler(jsonDictionary as AnyObject?, nil) if let _ = serializerCompletionHandler { serializerCompletionHandler!(jsonDictionary) } } else if let jsonArray = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? Array<AnyObject> { // Check if it is Array of Dictionary/String let jsonDictionary = [APIManager.rootKey : jsonArray] apiObject.parseAPIResponse(response: jsonDictionary as Dictionary<String, AnyObject>?) apiRequestCompletionHandler(jsonDictionary as AnyObject?, nil) if let _ = serializerCompletionHandler { serializerCompletionHandler!(jsonDictionary as Dictionary<String, AnyObject>) } } else { apiRequestCompletionHandler(nil, nil) } } catch let error as NSError { apiRequestCompletionHandler(nil, error) } } } }
mit
7edff2d6b2af6898d5a4ab79eb2a6c75
44.475177
263
0.595446
6.249513
false
false
false
false
danielsawin/cordova-plugin-novelty-watchface
src/ios/Watchface.swift
1
7226
// // Watchface.swift // // // Created by Daniel Sawin on 10/19/17. // import Photos @objc(Watchface) class Watchface : CDVPlugin { class CustomPhotoAlbum { var albumName = "Album Name" var assetCollection: PHAssetCollection! func load() { if let assetCollection = fetchAssetCollectionForAlbum() { self.assetCollection = assetCollection return } if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.authorized { PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) -> Void in () }) } if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized { self.createAlbum() } else { PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler) } } func requestAuthorizationHandler(status: PHAuthorizationStatus) { if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized { // ideally this ensures the creation of the photo album even if authorization wasn't prompted till after init was done print("trying again to create the album") self.createAlbum() } else { print("should really prompt the user to let them know it's failed") } } func createAlbum() { PHPhotoLibrary.shared().performChanges({ PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: self.albumName) // create an asset collection with the album name }) { success, error in if success { self.assetCollection = self.fetchAssetCollectionForAlbum() } else { print("error \(String(describing: error))") } } } func fetchAssetCollectionForAlbum() -> PHAssetCollection? { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "title = %@", self.albumName) let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) if let _: AnyObject = collection.firstObject { return collection.firstObject } return nil } func save(image: UIImage) { if self.assetCollection == nil { print("error") return // if there was an error upstream, skip the save } PHPhotoLibrary.shared().performChanges({ let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image) let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection) let enumeration: NSArray = [assetPlaceHolder!] albumChangeRequest!.addAssets(enumeration) }, completionHandler: nil) } func reMoveImages(oldAlbum:PHAssetCollection) { let oldFace = PHAsset.fetchKeyAssets(in: self.assetCollection, options: nil)! if(oldFace.firstObject != nil){ PHPhotoLibrary.shared().performChanges({ let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection) albumChangeRequest!.removeAssets(oldFace) }, completionHandler: nil) PHPhotoLibrary.shared().performChanges({ let albumChangeRequest = PHAssetCollectionChangeRequest(for: oldAlbum) albumChangeRequest!.addAssets(oldFace) }, completionHandler: nil) }else{ NSLog("no images to remove...") } } } func getAssetThumbnail(asset: PHAsset) -> UIImage { let manager = PHImageManager.default() let option = PHImageRequestOptions() var thumbnail = UIImage() option.isSynchronous = true manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in thumbnail = result! }) return thumbnail } @objc(update:) func update(command: CDVInvokedUrlCommand) { //Fetch and Create Albums let mainAlbum = CustomPhotoAlbum() mainAlbum.albumName = "oneWatch" mainAlbum.load() let oldAlbum = CustomPhotoAlbum() oldAlbum.albumName = "oneWatch Archive" oldAlbum.load() var pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR ) var dataURL: String dataURL = command.arguments[0] as! String //Create image with DataURL var newFace: UIImage if let decodedData = Data(base64Encoded: dataURL, options: .ignoreUnknownCharacters) { let image = UIImage(data: decodedData) newFace = image! //Check if folders exist if(mainAlbum.fetchAssetCollectionForAlbum() == nil){ NSLog("creating albums...") mainAlbum.createAlbum() oldAlbum.createAlbum() mainAlbum.save(image: newFace) pluginResult = CDVPluginResult( status: CDVCommandStatus_OK ) }else{ NSLog("removing images...") mainAlbum.reMoveImages(oldAlbum: oldAlbum.assetCollection) } if(oldAlbum.fetchAssetCollectionForAlbum() == nil){ oldAlbum.createAlbum() }else{ NSLog("saving new face...") mainAlbum.save(image: newFace) pluginResult = CDVPluginResult( status: CDVCommandStatus_OK ) } } //Send pluginResult self.commandDelegate!.send( pluginResult, callbackId: command.callbackId ) } /*@objc(getCurrentFace:) func getCurrentFace(command: CDVInvokedUrlCommand) { let mainAlbum = CustomPhotoAlbum() mainAlbum.albumName = "oneWatch" mainAlbum.load() let currentFace = PHAsset.fetchKeyAssets(in: mainAlbum.assetCollection, options: nil)! let img = getAssetThumbnail(asset: currentFace.firstObject!) let imageData = UIImageJPEGRepresentation(img, 0.5) let strBase64 = imageData?.base64EncodedString(options: .lineLength64Characters) print(strBase64 ?? "encoding failed...") let pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR, messageAs: strBase64 ) self.commandDelegate!.send( pluginResult, callbackId: command.callbackId ) }*/ }
mit
dc39a59aaf438abeff097616fcce2ed0
36.832461
167
0.571409
5.937551
false
false
false
false
tryswift/trySwiftData
Example/Tests/NYC-2017/TKO2017ConferenceDays.swift
1
1092
// // NYC2016ConferenceDays.swift // TrySwiftData // // Created by Tim Oliver on 1/29/17. // Copyright © 2017 NatashaTheRobot. All rights reserved. // import UIKit import Foundation import RealmSwift import TrySwiftData public let tko2017ConferenceDays: [ConferenceDay] = [ { let day1 = ConferenceDay() day1.date = Date.date(year: 2017, month: 3, day: 2, hour: 16, minute: 0, second: 0) for index in 0...21 { day1.sessionBlocks.append(tko2017SessionBlocks[index]) } return day1 }(), { let day2 = ConferenceDay() day2.date = Date.date(year: 2017, month: 3, day: 3, hour: 16, minute: 0, second: 0) for index in 22...45 { day2.sessionBlocks.append(tko2017SessionBlocks[index]) } return day2 }(), { let day3 = ConferenceDay() day3.date = Date.date(year: 2017, month: 3, day: 4, hour: 16, minute: 0, second: 0) for index in 46...55 { day3.sessionBlocks.append(tko2017SessionBlocks[index]) } return day3 }() ]
mit
2b6b5c670f6de3a457e639f701863622
26.275
91
0.594867
3.519355
false
false
false
false
realm/SwiftLint
Tests/SwiftLintFrameworkTests/SourceKitCrashTests.swift
1
2498
@testable import SwiftLintFramework import XCTest class SourceKitCrashTests: XCTestCase { func testAssertHandlerIsNotCalledOnNormalFile() { let file = SwiftLintFile(contents: "A file didn't crash SourceKitService") file.sourcekitdFailed = false var assertHandlerCalled = false file.assertHandler = { assertHandlerCalled = true } _ = file.syntaxMap XCTAssertFalse(assertHandlerCalled, "Expects assert handler was not called on accessing SwiftLintFile.syntaxMap") assertHandlerCalled = false _ = file.syntaxKindsByLines XCTAssertFalse(assertHandlerCalled, "Expects assert handler was not called on accessing SwiftLintFile.syntaxKindsByLines") assertHandlerCalled = false _ = file.syntaxTokensByLines XCTAssertFalse(assertHandlerCalled, "Expects assert handler was not called on accessing SwiftLintFile.syntaxTokensByLines") } func testAssertHandlerIsCalledOnFileThatCrashedSourceKitService() { let file = SwiftLintFile(contents: "A file crashed SourceKitService") file.sourcekitdFailed = true var assertHandlerCalled = false file.assertHandler = { assertHandlerCalled = true } _ = file.syntaxMap XCTAssertTrue(assertHandlerCalled, "Expects assert handler was called on accessing SwiftLintFile.syntaxMap") assertHandlerCalled = false _ = file.syntaxKindsByLines XCTAssertTrue(assertHandlerCalled, "Expects assert handler was called on accessing SwiftLintFile.syntaxKindsByLines") assertHandlerCalled = false _ = file.syntaxTokensByLines XCTAssertTrue(assertHandlerCalled, "Expects assert handler was not called on accessing SwiftLintFile.syntaxTokensByLines") } func testRulesWithFileThatCrashedSourceKitService() { let file = SwiftLintFile(path: #file)! file.sourcekitdFailed = true file.assertHandler = { XCTFail("If this called, rule's SourceKitFreeRule is not properly configured") } let configuration = Configuration(rulesMode: .only(allRuleIdentifiers)) let storage = RuleStorage() _ = Linter(file: file, configuration: configuration).collect(into: storage).styleViolations(using: storage) file.sourcekitdFailed = false file.assertHandler = nil } }
mit
3c8f054995b4bb8646db76234295a884
39.95082
115
0.681745
5.349036
false
true
false
false
jellybeansoup/ios-melissa
Shared/CollectionViewCell.swift
2
2514
import UIKit class CollectionViewCell: UICollectionViewCell { var text: String? { get { return self.textLabel.text } set(text) { self.textLabel.text = text } } override func layoutSubviews() { super.layoutSubviews() self.updateGradient() } func updateGradient() { guard let collectionView = self.superview as? UICollectionView else { return } let collectionViewOffset = collectionView.contentOffset.y - collectionView.contentInset.top let collectionViewHeight = collectionView.bounds.height let factor: CGFloat = 2 // Adjusts the "strength" of the generated gradient let cellFrame = self.convert(self.contentView.frame, to: collectionView) let cellTop = factor - (factor * ((cellFrame.origin.y - collectionViewOffset) / collectionViewHeight)) let cellBottom = cellTop - (factor * (cellFrame.size.height / collectionViewHeight)) let gradientColor = PreferencesManager.tintColor.withAlphaComponent(0.8) let gradientSize = CGSize(width: 20, height: cellFrame.size.height) let gradient = UIImage.imageWithGradient(gradientColor, size: gradientSize, top: cellTop, bottom: cellBottom) (self.backgroundView as? UIImageView)?.image = gradient (self.selectedBackgroundView as? UIImageView)?.image = gradient } fileprivate let textLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } func initialize() { self.clipsToBounds = true self.layer.cornerRadius = 10.0 self.textLabel.font = UIFont.systemFont(ofSize: 30) self.textLabel.numberOfLines = 0 self.textLabel.textAlignment = .center self.textLabel.textColor = PreferencesManager.backgroundColor self.contentView.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) self.contentView.layoutMarginsDidChange() self.contentView.addSubview(self.textLabel) self.textLabel.anchor(to: self.contentView.layoutMarginsGuide) self.backgroundView = UIImageView() self.selectedBackgroundView = UIImageView() } override func prepareForReuse() { self.textLabel.text = nil } }
bsd-2-clause
8573685150ddfdcec67f6dc2f2e368fc
32.078947
117
0.648767
5.099391
false
false
false
false
eugenegolovanov/SocketChat
SocketChat/UsersViewController.swift
1
5782
// // UsersViewController.swift // SocketChat // // Created by Gabriel Theodoropoulos on 1/31/16. // Copyright © 2016 AppCoda. All rights reserved. // import UIKit class UsersViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tblUserList: UITableView! var users = [[String: AnyObject]]() var nickname: String! var configurationOK = false //-------------------------------------------------------------------------------------------------------------------------- //MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if !configurationOK { configureNavigationBar() configureTableView() configurationOK = true } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if nickname == nil { askForNickname() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //-------------------------------------------------------------------------------------------------------------------------- //MARK: - Users func askForNickname() { let alertController = UIAlertController(title: "SocketChat", message: "Please enter a nickname:", preferredStyle: UIAlertControllerStyle.Alert) alertController.addTextFieldWithConfigurationHandler(nil) let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (action) -> Void in let textfield = alertController.textFields![0] if textfield.text?.characters.count == 0 { self.askForNickname() } else { self.nickname = textfield.text SocketIOManager.sharedInstance.connectToServerWithNickname(self.nickname, completionHandler: { (userList) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in if userList != nil { self.users = userList self.tblUserList.reloadData() self.tblUserList.hidden = false } }) }) } } alertController.addAction(OKAction) presentViewController(alertController, animated: true, completion: nil) } //-------------------------------------------------------------------------------------------------------------------------- // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "idSegueJoinChat" { let chatViewController = segue.destinationViewController as! ChatViewController chatViewController.nickname = nickname } } } //-------------------------------------------------------------------------------------------------------------------------- // MARK: - IBAction Methods @IBAction func exitChat(sender: AnyObject) { SocketIOManager.sharedInstance.exitChatWithNickname(self.nickname) { () -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.nickname = nil self.users.removeAll() self.tblUserList.hidden = true self.askForNickname() }) } } //-------------------------------------------------------------------------------------------------------------------------- // MARK: - Custom Methods func configureNavigationBar() { navigationItem.title = "SocketChat" } func configureTableView() { tblUserList.delegate = self tblUserList.dataSource = self tblUserList.registerNib(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "idCellUser") tblUserList.hidden = true tblUserList.tableFooterView = UIView(frame: CGRectZero) } //-------------------------------------------------------------------------------------------------------------------------- // MARK: - UITableView Delegate and Datasource methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("idCellUser", forIndexPath: indexPath) as! UserCell cell.textLabel?.text = users[indexPath.row]["nickname"] as? String cell.detailTextLabel?.text = (users[indexPath.row]["isConnected"] as! Bool) ? "Online" : "Offline" cell.detailTextLabel?.textColor = (users[indexPath.row]["isConnected"] as! Bool) ? UIColor.greenColor() : UIColor.redColor() return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44.0 } }
unlicense
79e0d48ab287aaa6dfd9032fad43520c
31.661017
151
0.512195
6.401993
false
false
false
false
Urinx/SublimeCode
Sublime/Sublime/GithubAccountTableViewController.swift
1
5111
// // GithubAccountTableViewController.swift // Sublime // // Created by Eular on 2/24/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit import AASquaresLoading class GithubAccountTableViewController: UITableViewController, GithubAPIManagerDelegate { @IBOutlet weak var avatarView: UIImageView! @IBOutlet weak var nameLB: UILabel! @IBOutlet weak var idLB: UILabel! @IBOutlet weak var companyLB: UILabel! @IBOutlet weak var locationLB: UILabel! @IBOutlet weak var emailLB: UILabel! @IBOutlet weak var blogLB: UILabel! @IBOutlet weak var usageLB: UILabel! @IBOutlet weak var followerLB: UILabel! @IBOutlet weak var repoLB: UILabel! @IBOutlet weak var followingLB: UILabel! let github = GitHubAPIManager() var loadingSquare: AASquaresLoading? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Constant.CapeCod title = "Github" if GitHubAPIManager.isLogin { updateUserInfo() } else { loadingSquare = AASquaresLoading(target: self.view, size: 40) loadingSquare?.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3) loadingSquare?.color = UIColor.whiteColor() showLoginView() } navigationController?.navigationBar.translucent = false } func updateUserInfo() { nameLB.text = github.user["name"].string idLB.text = github.user["login"].string companyLB.text = github.user["company"].string locationLB.text = github.user["location"].string emailLB.text = github.user["email"].string blogLB.text = github.user["blog"].string if let avatar_url = github.user["avatar_url"].string { avatarView.imageFromUrl(avatar_url) } followerLB.text = "\(github.user["followers"].int ?? 0)" repoLB.text = "\(github.user["public_repos"].int ?? 0)" followingLB.text = "\(github.user["following"].int ?? 0)" let used = (github.user["disk_usage"].double ?? 0) * 1024 let total = (github.user["plan"]["space"].double ?? 0) * 1024 usageLB.text = "\(used.GB.afterPoint(2))GB / \(total.GB.afterPoint(2))GB" } func showLoginView() { tableView.separatorColor = UIColor.blackColor().colorWithAlphaComponent(0) let loginView = UIView() loginView.tag = 1008611 loginView.frame = view.frame loginView.y = view.height loginView.backgroundColor = Constant.CapeCod let img = UIImageView() let imgH: CGFloat = 290 let imgW: CGFloat = 300 let imgOffsetH: CGFloat = (view.height - imgH - Constant.NavigationBarOffset) / 2 let imgOffsetW: CGFloat = (view.width - imgW) / 2 img.frame = CGRectMake(imgOffsetW, imgOffsetH, imgW, imgH) img.image = UIImage(named: "github_login") let btn = UIButton() btn.frame = CGRectMake(imgOffsetW + 105, imgOffsetH + 165, 100, 50) //btn.layer.borderWidth = 1 btn.addTarget(self, action: #selector(self.githubLogin), forControlEvents: .TouchUpInside) loginView.addSubview(img) loginView.addSubview(btn) view.addSubview(loginView) UIView.animateWithDuration(1) { loginView.y = 0 } } func githubLogin() { github.delegate = self github.OAuth2() } func githubOAuthCode(notification: NSNotification) { github.handleOAuthCode(notification) loadingSquare?.start() } func githubGetUserInfoCompleted() { loadingSquare?.stop() updateUserInfo() tableView.reloadData() tableView.separatorColor = Constant.CapeCod if let loginView = view.viewWithTag(1008611) { UIView.animateWithDuration(1, animations: { loginView.alpha = 0 }) { (_) -> Void in loginView.removeFromSuperview() } } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return GitHubAPIManager.isLogin ? 3 : 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 6 : 1 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 2 { github.logout() showLoginView() } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return Constant.FilesTableSectionHight } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = Constant.CapeCod return headerView } }
gpl-3.0
61fcef6e164bba494ae61ea742e77371
33.295302
103
0.62407
4.718375
false
false
false
false
lkzhao/YetAnotherAnimationLibrary
Sources/YetAnotherAnimationLibrary/Animatables/CurveAnimatable.swift
2
1912
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public protocol CurveAnimatable: SolverAnimatable { var defaultCurve: Curve { get set } var target: AnimationProperty<Value> { get } } extension CurveAnimatable { public func setDefaultCurve(_ curve: Curve) { defaultCurve = curve } public func animateTo(_ targetValue: Value, duration: TimeInterval, curve: Curve? = nil, completionHandler: ((Bool) -> Void)? = nil) { target.value = targetValue solver = CurveSolver(duration: duration, curve: curve ?? defaultCurve, current: value, target: target, velocity: velocity) start(completionHandler) } }
mit
53e54554b406066f4d325a33b37f4dbf
40.565217
80
0.683577
4.816121
false
false
false
false
Mozharovsky/XMLParser
XMLParser/Tree.swift
2
3633
// // Tree.swift // XMLParser // // Created by Eugene Mozharovsky on 8/29/15. // Copyright © 2015 DotMyWay LCC. All rights reserved. // import Foundation /// A generic data structure for chaining parsed values. public class Tree<T> { // MARK: - Properties /// The previous tree if any. It should be weak since it's an optional /// and besides we don't want to face cycled referencing. public weak var previous: Tree<T>? /// Self node with values *name* and *value*. public let node: (tag: XMLTag, value: T) /// The next tree if any. public var next: [Tree<T>]? /// Defines the indentation level. private let multiplier = 3 /// A tmp counter for steps. private lazy var _steps = 0 /// Steps for reaching the very first tree. public var steps: Int { get { if let previous = previous { previous._steps = ++_steps return previous.steps } else { let copy = self._steps self._steps = 0 return copy } } } // MARK: - Initialization /// A general initializer. public init(previous: Tree<T>?, node: (XMLTag, T), next: [Tree<T>]?) { self.previous = previous self.node = node self.next = next } // MARK: - Convenience stuff public convenience init(node: (XMLTag, T)) { self.init(previous: nil, node: node, next: nil) } public convenience init(previous: Tree<T>, node: (XMLTag, T)) { self.init(previous: previous, node: node, next: nil) } public convenience init(node: (XMLTag, T), next: [Tree<T>]) { self.init(previous: nil, node: node, next: next) } // MARK: - Utils /// Returns the very first tree. public func first() -> Tree<T> { if let previous = previous { return previous.first() } else { return self } } } // MARK: - Parsing utils extension Tree { /// A util function that parsed the current tree structure into /// an XML string. public func parsedRequestBody() -> String { var body = "" func spaces(count: Int) -> String { var string = "" for _ in 0..<count { string += " " } return string } func process(tree: Tree<T>) { let spaces = spaces(tree.steps * multiplier) if body.characters.count > 0 && body.characters.last != "\n" { body += "\n" } body += spaces let tag = tree.node.tag body += (tag.header + (tag.name != nil ? " " + tag.name! : "") + (tag.value != nil ? "=\'\(tag.value!)\'" : "")).startHeader() if ((tree.next == nil) || (tree.next?.count == 0)) && ((tree.node.value as? NSDictionary) == nil) { body += "\(tree.node.value)" } if let tries = tree.next { for tree in tries { process(tree) } } if body.characters.last == "\n" { body += spaces } body += tag.header.endHeader() body += "\n" } process(self) return body } } // MARK: - Equatable public func ==<T>(lhs: Tree<T>, rhs: Tree<T>) -> Bool { return lhs === rhs }
mit
eca1c2f9ad30ab45f625e16ab81932c3
24.942857
138
0.478524
4.349701
false
false
false
false
ayoubkhayatti/FlickrSearch
Flicker Search/FlickrPhoto.swift
1
1837
// // FlickrPhoto.swift // Flicker Search // // Created by Ayoub Khayatti on 28/03/16. // Copyright © 2016 Ayoub Khayati. All rights reserved. // import UIKit class FlickrPhoto: NSObject { var id :String = "" var owner :String = "" var secret:String = "" var server:String = "" var farm :Int = 0 var title :String = "" var ispublic :Int = 0 var isfriend :Int = 0 var isfamily :Int = 0 var photoUrl: String { let url = "https://farm\(farm).staticflickr.com/\(server)/\(id)_\(secret)_n.jpg" return url } var photoLargeUrl: String { let url = "https://farm\(farm).staticflickr.com/\(server)/\(id)_\(secret)_b.jpg" return url } init(dictionary: NSDictionary) { super.init() id = dictionary["id"] as? String ?? id owner = dictionary["owner"] as? String ?? owner secret = dictionary["secret"] as? String ?? secret server = dictionary["server"] as? String ?? server farm = dictionary["farm"] as? Int ?? farm title = dictionary["title"] as? String ?? title ispublic = dictionary["ispublic"] as? Int ?? ispublic isfriend = dictionary["isfriend"] as? Int ?? isfriend isfamily = dictionary["isfamily"] as? Int ?? isfamily } class func parseResponse(response: AnyObject?) -> [FlickrPhoto]{ var photosArray = [FlickrPhoto]() if let dictionary = response as? NSDictionary { if let photos = dictionary["photos"]!["photo"] as? [AnyObject]{ for photoData in photos { let photo = FlickrPhoto(dictionary:(photoData as! NSDictionary)) photosArray.append(photo) } } } return photosArray } }
mit
f8cbca5baea9b49648c40b3bf55b21b7
30.655172
88
0.560458
4.22069
false
false
false
false
brenogazzola/CabCentral
CabCentral/MapControllerAnnotations.swift
1
6377
// // MapControllerAnnotations.swift // CabCentral // // Created by Breno Gazzola on 8/30/15. // Copyright (c) 2015 Breno Gazzola. All rights reserved. // import Foundation import MapKit extension MapController : MKMapViewDelegate { // MARK: - CRUD /** Removes all annotations for drivers near the user and inserts new ones :param: Drivers The collection of drivers to display in the map */ func updateDrivers(drivers: [Driver]){ // Date objects are expensive, create only once and pass it forward let currentDate = NSDate() drivers .filter{ $0.isAvailable } .forEach{ if let val = self.knownDrivers[$0.id] { val.lastSeem = currentDate self.updateDriver(val, coordinate:$0.coordinate) } else { $0.lastSeem = currentDate // Don't add the marker for this driver yet, let displayDrivers show it self.knownDrivers[$0.id] = $0 } } displayDrivers() } /** Updates the position of a driver we are already tracking on the map :param: driver The driver to update :param: coordinate The coordinate that the driver moved to */ func updateDriver(driver:Driver, coordinate:CLLocationCoordinate2D){ UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: { driver.coordinate = coordinate }, completion: { _ in Log.DLog("Cab \(driver.id) moved from \(driver.coordinate) to \(coordinate)") }) } /** Adds a new driver to the map and starts tracking it */ func insertDriver(driver: Driver){ self.knownDrivers[driver.id] = driver self.mapView.addAnnotation(driver) } /** Removes a given driver from the map and the tracking pool :param: driver The driver to remove */ func removeDriver(driver:Driver){ knownDrivers.removeValueForKey(driver.id) mapView.removeAnnotation(driver) } /* Handles displaying on the map drivers in the known driver pool This method will group together drivers that are too close and remove drivers that are too old if the pool limit has ben reached */ func displayDrivers(){ removeOldDrivers() // First we have to figure out how many degrees in the shown region a pin takes... let verticalAnnotations = Double(mapView.frame.height) / (pinHeight / 2) let horizontalAnnotations = Double(mapView.frame.width) / (pinWidth / 2) var latitudeDelta = mapView.region.span.latitudeDelta / horizontalAnnotations let longitudeDelta = mapView.region.span.longitudeDelta / verticalAnnotations // ... so we can loop over the drivers that we want to show and the ones that have already been shown ... var driversShown = [Driver]() for driverToShow in knownDrivers.values { var found = false for driverShown in driversShown { var latitudinalSpace = fabs(driverShown.coordinate.latitude - driverToShow.coordinate.latitude) var longitudinalSpace = fabs(driverShown.coordinate.longitude - driverToShow.coordinate.longitude) // ... to find out if the distance in degrees between then is smaller than to delta we calculated ... if latitudinalSpace < latitudeDelta && longitudinalSpace < longitudeDelta { /// ... so we can remove them if it is ... mapView.removeAnnotation(driverToShow) found = true } } if !found { // ... or add them if it isn't driversShown.append(driverToShow) if mapView.viewForAnnotation(driverToShow) == nil{ mapView.addAnnotation(driverToShow) } } } } /** Removes from the map old drivers if pool size limit has been reached. Only invoke this method after all drivers have been updated */ func removeOldDrivers(){ var drivers = Array(self.knownDrivers.values) // Such a beauty... drivers.sort(>) let overflow = knownDrivers.count - knownDriversPoolSize if overflow > 0 { for _ in 0 ..< overflow { var driverToRemove = drivers.removeLast() removeDriver(driverToRemove) } } } // MARK: - Layout & animation /** Defines how each annotation will be displayed */ func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if let annotation = annotation as? Driver { let identifier = "Driver" var view: DriverAnnotationView if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? DriverAnnotationView { dequeuedView.annotation = annotation view = dequeuedView } else { view = DriverAnnotationView(annotation: annotation, reuseIdentifier: identifier) } return view } return nil } /** Animates the pin drop */ func mapView(mapView: MKMapView!, didAddAnnotationViews views: [AnyObject]!) { for view in views { // Don't animate anything that isn't a driver annotation if !view.isKindOfClass(DriverAnnotationView){ continue; } let driverAnnotationView = view as! DriverAnnotationView // Don't waste CPU cycles on annotations outside the view scope let point = MKMapPointForCoordinate(driverAnnotationView.annotation.coordinate); if (!MKMapRectContainsPoint(self.mapView.visibleMapRect, point)) { continue; } driverAnnotationView.phaseIn() } } }
mit
27622a6785d920d4f01aab5c91861df6
33.657609
117
0.574565
5.239934
false
false
false
false
TomHarte/CLK
OSBindings/Mac/Clock Signal/Documents/AppleIIController.swift
1
1028
// // AppleIIOptionsPanel.swift // Clock Signal // // Created by Thomas Harte on 07/06/2021. // Copyright 2021 Thomas Harte. All rights reserved. // class AppleIIController: MachineController { var appleII: CSAppleII! { get { return self.machine.appleII } } var squarePixelsUserDefaultsKey: String { return prefixedUserDefaultsKey("useSquarePixels") } @IBOutlet var squarePixelButton: NSButton! @IBAction func optionDidChange(_ sender: AnyObject!) { let useSquarePixels = squarePixelButton.state == .on appleII.useSquarePixels = useSquarePixels let standardUserDefaults = UserDefaults.standard standardUserDefaults.set(useSquarePixels, forKey: squarePixelsUserDefaultsKey) } override func establishStoredOptions() { super.establishStoredOptions() let standardUserDefaults = UserDefaults.standard let useSquarePixels = standardUserDefaults.bool(forKey: squarePixelsUserDefaultsKey) appleII.useSquarePixels = useSquarePixels squarePixelButton.state = useSquarePixels ? .on : .off } }
mit
1d241ddab38f4c8f10d66c4bdb221648
26.783784
86
0.77821
3.893939
false
false
false
false
JuanjoArreola/YouTubePlayer
YouTubePlayer/Log.swift
1
2304
// // Log.swift // YouTubePlayer // // Created by Juan Jose Arreola Simon on 4/30/16. // Copyright © 2016 juanjo. All rights reserved. // import Foundation enum LogLevel: Int { case debug = 1, warning, error, severe } class Log { static var logLevel = LogLevel.debug static var showDate = true static var showFile = true static var showFunc = true static var showLine = true static var formatter: DateFormatter = { let f = DateFormatter() f.dateFormat = "MM-dd HH:mm:ss.SSS" return f }() class func debug(_ message: @autoclosure () -> Any, file: String = #file, function: StaticString = #function, line: Int = #line) { if LogLevel.debug.rawValue >= logLevel.rawValue { log("Debug", message: String(describing: message()), file: file, function: function, line: line) } } class func warn(_ message: @autoclosure () -> Any, file: String = #file, function: StaticString = #function, line: Int = #line) { if LogLevel.warning.rawValue >= logLevel.rawValue { log("Warning", message: String(describing: message()), file: file, function: function, line: line) } } class func error(_ message: @autoclosure () -> Any, file: String = #file, function: StaticString = #function, line: Int = #line) { if LogLevel.error.rawValue >= logLevel.rawValue { log("Error", message: String(describing: message()), file: file, function: function, line: line) } } class func severe(_ message: @autoclosure () -> Any, file: String = #file, function: StaticString = #function, line: Int = #line) { if LogLevel.severe.rawValue >= logLevel.rawValue { log("Severe", message: String(describing: message()), file: file, function: function, line: line) } } fileprivate class func log(_ level: String, message: String, file: String, function: StaticString, line: Int) { var s = "" s += showDate ? formatter.string(from: Date()) + " " : "" s += showFile ? file.components(separatedBy: "/").last ?? "" : "" s += showFunc ? " \(function)" : "" s += showLine ? " [\(line)] " : "" s += level + ": " s += message print(s) } }
mit
af574ce296f1bd63431009d456b05345
34.984375
135
0.588363
4.068905
false
false
false
false
per-dalsgaard/20-apps-in-20-weeks
App 11 - TacoPOP/TacoPOP/Taco.swift
1
1628
// // Taco.swift // TacoPOP // // Created by Per Kristensen on 17/04/2017. // Copyright © 2017 Per Dalsgaard. All rights reserved. // import Foundation enum TacoShell: Int { case Flour = 1 case Corn = 2 } enum TacoProtein: String { case Beef = "Beef" case Chicken = "Chicken" case Brisket = "Brisket" case Fish = "Fish" } enum TacoCondiment: Int { case Loaded = 1 case Plain = 2 } struct Taco { private var _id: Int! private var _productName: String! private var _shellId: TacoShell! private var _proteinId: TacoProtein! private var _condimentId: TacoCondiment! var id: Int { return _id } var productName: String { return _productName } var shellId: TacoShell { return _shellId } var proteinId: TacoProtein { return _proteinId } var condimentId: TacoCondiment { return _condimentId } init(id: Int, productName: String, shellId: Int, proteinId: Int, condimentId: Int) { _id = id _productName = productName switch shellId { case 2: _shellId = .Corn default: _shellId = .Flour } switch proteinId { case 2: _proteinId = .Chicken case 3: _proteinId = .Brisket case 4: _proteinId = .Fish default: _proteinId = .Beef } switch condimentId { case 2: _condimentId = .Plain default: _condimentId = .Loaded } } }
mit
7f9668fcd3c5ca03b644a77381b4917b
18.369048
88
0.531653
3.819249
false
false
false
false
domenicosolazzo/practice-swift
Views/TableViews/Providing basic content to a CollectionView/Providing basic content to a CollectionView/ViewController.swift
1
2009
// // ViewController.swift // Providing basic content to a CollectionView // // Created by Domenico Solazzo on 10/05/15. // License MIT // import UIKit class ViewController: UICollectionViewController { // Section colors let allSectionColors = [ UIColor.red, UIColor.green, UIColor.blue ] override init(collectionViewLayout layout: UICollectionViewLayout) { super.init(collectionViewLayout: layout) collectionView!.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "cell") collectionView!.backgroundColor = UIColor.white } convenience required init?(coder aDecoder: NSCoder) { let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumLineSpacing = 20 flowLayout.minimumInteritemSpacing = 10 flowLayout.itemSize = CGSize(width: 80, height: 120); flowLayout.scrollDirection = .vertical flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20) self.init(collectionViewLayout: flowLayout) } // Number of sections in the collection view override func numberOfSections(in collectionView: UICollectionView) -> Int { return allSectionColors.count } // Number of items in each section override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { /* Generate between 20 to 40 cells for each section */ return Int(arc4random_uniform(21)) + 20 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "cell", for: indexPath) cell.backgroundColor = allSectionColors[(indexPath as NSIndexPath).section] return cell } }
mit
213bac4268a1abdc5ecac2644f9a75f2
30.390625
130
0.660528
5.74
false
false
false
false
VolodymyrShlikhta/InstaClone
InstaClone/Utilities.swift
1
3790
// // Utilities.swift // InstaClone // // Created by Relorie on 6/6/17. // Copyright © 2017 Relorie. All rights reserved. // import Foundation import UIKit import SVProgressHUD import FirebaseAuth import FirebaseDatabase import Kingfisher class Utilities { class func configureTextFieldsAppearence(_ textFields: [UITextField]) { for textField in textFields { textField.backgroundColor = UIColor.clear textField.tintColor = UIColor.white textField.textColor = UIColor.white textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor(white :1.0, alpha: 0.6)]) let bottomLayer: CALayer = CALayer() bottomLayer.frame = CGRect(x:0 ,y:29, width:1000, height: 5) bottomLayer.backgroundColor = UIColor(red: 50/255, green: 50/255, blue: 50/255, alpha: 1).cgColor textField.layer.addSublayer(bottomLayer) } } class func configureSVProgressHUDDefaultValues() { SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.light) SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.black) SVProgressHUD.setFadeInAnimationDuration(0.5) SVProgressHUD.setFadeOutAnimationDuration(0.5) SVProgressHUD.setMinimumDismissTimeInterval(1.5) SVProgressHUD.setMaximumDismissTimeInterval(2) } class func setNewCurrentUserInfo(newProfilePicture: UIImage, newProfileName: String) { CurrentUser.sharedInstance.profileName = newProfileName CurrentUser.sharedInstance.uid = (Auth.auth().currentUser?.uid)! // ImageCache.default.store(newProfilePicture, forKey: CurrentUser.sharedInstance.profilePictureURL ?? "") } class func getFromDatabaseUserInfo(forUser user: User, withUid uid: String) { let ref = Database.database().reference() user.uid = uid ref.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in if let value = snapshot.value as? NSDictionary { let username = value["username"] as? String ?? "" user.profileName = username user.postCount = value["postCount"] as? Int user.followers = value["followers"] as! [String:Bool] user.following = value["following"] as! [String:Bool] user.profilePictureURL = URL(string: value["profileImageURL"] as! String) } }) { (error) in print(error.localizedDescription) } } class func follow(user userToFollow: User) { let databaseRef = Database.database().reference() databaseRef.child("users/\(userToFollow.uid!)/followers").child(CurrentUser.sharedInstance.uid!).setValue(true) databaseRef.child("users/\(CurrentUser.sharedInstance.uid!)/following/").child(userToFollow.uid!).setValue(true) userToFollow.followers[CurrentUser.sharedInstance.uid!] = true userToFollow.followedByCurrentUser = true CurrentUser.sharedInstance.following[userToFollow.uid!] = true SVProgressHUD.showSuccess(withStatus: "User followed!") } class func unfollow(user : User) { let databaseRef = Database.database().reference() databaseRef.child("users/\(user.uid!)/followers/").child(CurrentUser.sharedInstance.uid!).removeValue() databaseRef.child("users/\(CurrentUser.sharedInstance.uid!)/following/").child(user.uid!).removeValue() user.followers.removeValue(forKey: CurrentUser.sharedInstance.uid!) user.followedByCurrentUser = false CurrentUser.sharedInstance.following.removeValue(forKey: user.uid!) SVProgressHUD.showSuccess(withStatus: "User unfollowed!") } }
mit
77980ff3fcc78878173932b93310d6e8
45.207317
183
0.68778
4.87018
false
false
false
false
hjw6160602/JourneyNotes
Pods/Kingfisher/Sources/Filter.swift
7
4889
// // Filter.swift // Kingfisher // // Created by Wei Wang on 2016/08/31. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreImage import Accelerate // Reuse the same CI Context for all CI drawing. private let ciContext = CIContext(options: nil) /// Transformer method which will be used in to provide a `Filter`. public typealias Transformer = (CIImage) -> CIImage? /// Supply a filter to create an `ImageProcessor`. public protocol CIImageProcessor: ImageProcessor { var filter: Filter { get } } extension CIImageProcessor { public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.apply(filter) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Wrapper for a `Transformer` of CIImage filters. public struct Filter { let transform: Transformer public init(tranform: @escaping Transformer) { self.transform = tranform } /// Tint filter which will apply a tint color to images. public static var tint: (Color) -> Filter = { color in Filter { input in let colorFilter = CIFilter(name: "CIConstantColorGenerator")! colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) let colorImage = colorFilter.outputImage let filter = CIFilter(name: "CISourceOverCompositing")! filter.setValue(colorImage, forKey: kCIInputImageKey) filter.setValue(input, forKey: kCIInputBackgroundImageKey) return filter.outputImage?.cropped(to: input.extent) } } public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) /// Color control filter which will apply color control change to images. public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in let (brightness, contrast, saturation, inputEV) = arg return Filter { input in let paramsColor = [kCIInputBrightnessKey: brightness, kCIInputContrastKey: contrast, kCIInputSaturationKey: saturation] let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor) let paramsExposure = [kCIInputEVKey: inputEV] return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure) } } } extension Kingfisher where Base: Image { /// Apply a `Filter` containing `CIImage` transformer to `self`. /// /// - parameter filter: The filter used to transform `self`. /// /// - returns: A transformed image by input `Filter`. /// /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. public func apply(_ filter: Filter) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Tint image only works for CG-based image.") return base } let inputImage = CIImage(cgImage: cgImage) guard let outputImage = filter.transform(inputImage) else { return base } guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { assertionFailure("[Kingfisher] Can not make an tint image within context.") return base } #if os(macOS) return fixedForRetinaPixel(cgImage: result, to: size) #else return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation) #endif } }
mit
028c1dcdc7ef80f0a0e41f6bdc2f8ef6
37.195313
118
0.660667
4.831028
false
false
false
false
QuarkX/Quark
Sources/Quark/Venice/Venice/Coroutine/Coroutine.swift
1
2482
import CLibvenice public typealias PID = pid_t public extension Double { public var int64milliseconds: Int64 { return Int64(self * 1000) } } /// Runs the expression in a lightweight coroutine. public func coroutine(_ routine: @escaping (Void) -> Void) { var _routine = routine CLibvenice.co(&_routine, { routinePointer in routinePointer!.assumingMemoryBound(to: ((Void) -> Void).self).pointee() }, "co") } /// Runs the expression in a lightweight coroutine. public func coroutine(_ routine: @autoclosure @escaping (Void) -> Void) { var _routine: (Void) -> Void = routine CLibvenice.co(&_routine, { routinePointer in routinePointer!.assumingMemoryBound(to: ((Void) -> Void).self).pointee() }, "co") } /// Runs the expression in a lightweight coroutine. public func co(_ routine: @escaping (Void) -> Void) { coroutine(routine) } /// Runs the expression in a lightweight coroutine. public func co(_ routine: @autoclosure @escaping (Void) -> Void) { var _routine: (Void) -> Void = routine CLibvenice.co(&_routine, { routinePointer in routinePointer!.assumingMemoryBound(to: ((Void) -> Void).self).pointee() }, "co") } /// Runs the expression in a lightweight coroutine after the given duration. public func after(_ napDuration: Double, routine: @escaping (Void) -> Void) { co { nap(for: napDuration) routine() } } /// Runs the expression in a lightweight coroutine periodically. Call done() to leave the loop. public func every(_ napDuration: Double, routine: @escaping (_ done: (Void) -> Void) -> Void) { co { var done = false while !done { nap(for: napDuration) routine { done = true } } } } /// Sleeps for duration. public func nap(for duration: Double) { mill_msleep(duration.fromNow().int64milliseconds, "nap") } /// Wakes up at deadline. public func wake(at deadline: Double) { mill_msleep(deadline.int64milliseconds, "wakeUp") } /// Passes control to other coroutines. public var yield: Void { mill_yield("yield") } /// Fork the current process. public func fork() -> PID { return mfork() } /// Get the number of logical CPU cores available. This might return a bigger number than the physical CPU Core number if the CPU supports hyper-threading. public var logicalCPUCount: Int { return Int(mill_number_of_cores()) } public func dump() { goredump() }
mit
ba64b5422627b043cca6b36bdb271bc7
27.204545
155
0.654714
3.866044
false
false
false
false
beeth0ven/CKSIncrementalStore
CKSIncrementalStore/CKSIncrementalStoreSyncOperation.swift
1
31913
// CKSIncrementalStoreSyncOperation.swift // // The MIT License (MIT) // // Copyright (c) 2015 Nofel Mahmood (https://twitter.com/NofelMahmood) // // 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 CloudKit import CoreData let CKSIncrementalStoreSyncOperationErrorDomain = "CKSIncrementalStoreSyncOperationErrorDomain" let CKSSyncConflictedResolvedRecordsKey = "CKSSyncConflictedResolvedRecordsKey" let CKSIncrementalStoreSyncOperationFetchChangeTokenKey = "CKSIncrementalStoreSyncOperationFetchChangeTokenKey" enum CKSStoresSyncConflictPolicy: Int16 { case ClientTellsWhichWins = 0 case ServerRecordWins = 1 case ClientRecordWins = 2 case GreaterModifiedDateWins = 3 case KeepBoth = 4 } enum CKSStoresSyncError: ErrorType { case LocalChangesFetchError case ConflictsDetected } class CKSIncrementalStoreSyncOperation: NSOperation { private var operationQueue:NSOperationQueue? private var localStoreMOC:NSManagedObjectContext? private var persistentStoreCoordinator:NSPersistentStoreCoordinator? private var entities: Array<NSEntityDescription>? var syncConflictPolicy:CKSStoresSyncConflictPolicy? var syncCompletionBlock:((syncError:NSError?) -> ())? var syncConflictResolutionBlock:((clientRecord:CKRecord,serverRecord:CKRecord)->CKRecord)? init(persistentStoreCoordinator:NSPersistentStoreCoordinator?,entitiesToSync entities:[NSEntityDescription], conflictPolicy:CKSStoresSyncConflictPolicy?) { self.persistentStoreCoordinator = persistentStoreCoordinator self.entities = entities self.syncConflictPolicy = conflictPolicy super.init() } // MARK: Sync override func main() { self.operationQueue = NSOperationQueue() self.operationQueue?.maxConcurrentOperationCount = 1 self.localStoreMOC = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType) self.localStoreMOC?.persistentStoreCoordinator = self.persistentStoreCoordinator if self.syncCompletionBlock != nil { do { try self.performSync() self.syncCompletionBlock!(syncError: nil) } catch let error as NSError? { self.syncCompletionBlock!(syncError: error) } } } func performSync() throws { let localChangesInServerRepresentation = try self.localChangesInServerRepresentation() var insertedOrUpdatedCKRecords:Array<CKRecord> = localChangesInServerRepresentation.insertedOrUpdatedCKRecords let deletedCKRecordIDs:Array<CKRecordID> = localChangesInServerRepresentation.deletedCKRecordIDs do { try self.applyLocalChangesToServer(insertedOrUpdatedCKRecords: insertedOrUpdatedCKRecords, deletedCKRecordIDs: deletedCKRecordIDs) do { try self.fetchAndApplyServerChangesToLocalDatabase() } catch let error as NSError? { throw error! } } catch let error as NSError? { let conflictedRecords = error!.userInfo[CKSSyncConflictedResolvedRecordsKey] as! Array<CKRecord> self.resolveConflicts(conflictedRecords: conflictedRecords) var insertedOrUpdatedCKRecordsWithRecordIDStrings:Dictionary<String,CKRecord> = Dictionary<String,CKRecord>() for record in insertedOrUpdatedCKRecords { let ckRecord:CKRecord = record as CKRecord insertedOrUpdatedCKRecordsWithRecordIDStrings[ckRecord.recordID.recordName] = ckRecord } for record in conflictedRecords { insertedOrUpdatedCKRecordsWithRecordIDStrings[record.recordID.recordName] = record } insertedOrUpdatedCKRecords = insertedOrUpdatedCKRecordsWithRecordIDStrings.values.array try self.applyLocalChangesToServer(insertedOrUpdatedCKRecords: insertedOrUpdatedCKRecords, deletedCKRecordIDs: deletedCKRecordIDs) do { try self.fetchAndApplyServerChangesToLocalDatabase() } catch let error as NSError? { throw error! } } } func fetchAndApplyServerChangesToLocalDatabase() throws { var moreComing = true var insertedOrUpdatedCKRecordsFromServer = Array<CKRecord>() var deletedCKRecordIDsFromServer = Array<CKRecordID>() while moreComing { let returnValue = self.fetchRecordChangesFromServer() insertedOrUpdatedCKRecordsFromServer += returnValue.insertedOrUpdatedCKRecords deletedCKRecordIDsFromServer += returnValue.deletedRecordIDs moreComing = returnValue.moreComing } try self.applyServerChangesToLocalDatabase(insertedOrUpdatedCKRecordsFromServer, deletedCKRecordIDs: deletedCKRecordIDsFromServer) } // MARK: Local Changes func applyServerChangesToLocalDatabase(insertedOrUpdatedCKRecords:Array<CKRecord>,deletedCKRecordIDs:Array<CKRecordID>) throws { try self.deleteManagedObjects(fromCKRecordIDs: deletedCKRecordIDs) try self.insertOrUpdateManagedObjects(fromCKRecords: insertedOrUpdatedCKRecords) } func applyLocalChangesToServer(insertedOrUpdatedCKRecords insertedOrUpdatedCKRecords: Array<CKRecord> , deletedCKRecordIDs: Array<CKRecordID>) throws { let ckModifyRecordsOperation = CKModifyRecordsOperation(recordsToSave: insertedOrUpdatedCKRecords, recordIDsToDelete: deletedCKRecordIDs) let savedRecords:[CKRecord] = [CKRecord]() var conflictedRecords:[CKRecord] = [CKRecord]() ckModifyRecordsOperation.modifyRecordsCompletionBlock = ({(savedRecords,deletedRecordIDs,operationError)->Void in }) ckModifyRecordsOperation.perRecordCompletionBlock = ({(ckRecord,operationError)->Void in let error:NSError? = operationError if error != nil && error!.code == CKErrorCode.ServerRecordChanged.rawValue { conflictedRecords.append(ckRecord!) } }) self.operationQueue?.addOperation(ckModifyRecordsOperation) self.operationQueue?.waitUntilAllOperationsAreFinished() if conflictedRecords.count > 0 { throw NSError(domain: CKSIncrementalStoreSyncOperationErrorDomain, code: CKSStoresSyncError.ConflictsDetected._code, userInfo: [CKSSyncConflictedResolvedRecordsKey:conflictedRecords]) } if savedRecords.count > 0 { var savedRecordsWithType:Dictionary<String,Dictionary<String,CKRecord>> = Dictionary<String,Dictionary<String,CKRecord>>() for record in savedRecords { if savedRecordsWithType[record.recordType] != nil { savedRecordsWithType[record.recordType]![record.recordID.recordName] = record continue } let recordWithRecordIDString:Dictionary<String,CKRecord> = Dictionary<String,CKRecord>() savedRecordsWithType[record.recordType] = recordWithRecordIDString } let predicate = NSPredicate(format: "%K IN $recordIDStrings",CKSIncrementalStoreLocalStoreRecordIDAttributeName) let types = savedRecordsWithType.keys.array for type in types { let fetchRequest = NSFetchRequest(entityName: type) let ckRecordsForType = savedRecordsWithType[type] let ckRecordIDStrings = ckRecordsForType!.keys.array fetchRequest.predicate = predicate.predicateWithSubstitutionVariables(["recordIDStrings":ckRecordIDStrings]) var results = try self.localStoreMOC!.executeFetchRequest(fetchRequest) if results.count > 0 { for managedObject in results as! [NSManagedObject] { let ckRecord = ckRecordsForType![managedObject.valueForKey(CKSIncrementalStoreLocalStoreRecordIDAttributeName) as! String] let encodedSystemFields = ckRecord?.encodedSystemFields() managedObject.setValue(encodedSystemFields, forKey: CKSIncrementalStoreLocalStoreRecordEncodedValuesAttributeName) } } } try self.localStoreMOC!.save() } } func resolveConflicts(conflictedRecords conflictedRecords: Array<CKRecord>) { if conflictedRecords.count > 0 { var conflictedRecordsWithStringRecordIDs: Dictionary<String,(clientRecord:CKRecord?,serverRecord:CKRecord?)> = Dictionary<String,(clientRecord:CKRecord?,serverRecord:CKRecord?)>() for record in conflictedRecords { conflictedRecordsWithStringRecordIDs[record.recordID.recordName] = (record,nil) } let ckFetchRecordsOperation:CKFetchRecordsOperation = CKFetchRecordsOperation(recordIDs: conflictedRecords.map({(object)-> CKRecordID in let ckRecord:CKRecord = object as CKRecord return ckRecord.recordID })) ckFetchRecordsOperation.perRecordCompletionBlock = ({(record,recordID,error)->Void in if error == nil { let ckRecord: CKRecord? = record let ckRecordID: CKRecordID? = recordID if conflictedRecordsWithStringRecordIDs[ckRecordID!.recordName] != nil { conflictedRecordsWithStringRecordIDs[ckRecordID!.recordName] = (conflictedRecordsWithStringRecordIDs[ckRecordID!.recordName]!.clientRecord,ckRecord) } } }) self.operationQueue?.addOperation(ckFetchRecordsOperation) self.operationQueue?.waitUntilAllOperationsAreFinished() var finalCKRecords:[CKRecord] = [CKRecord]() for key in conflictedRecordsWithStringRecordIDs.keys.array { let value = conflictedRecordsWithStringRecordIDs[key]! var clientServerCKRecord = value as (clientRecord:CKRecord?,serverRecord:CKRecord?) if self.syncConflictPolicy == CKSStoresSyncConflictPolicy.ClientTellsWhichWins { if self.syncConflictResolutionBlock != nil { clientServerCKRecord.serverRecord = self.syncConflictResolutionBlock!(clientRecord: clientServerCKRecord.clientRecord!,serverRecord: clientServerCKRecord.serverRecord!) } } else if (self.syncConflictPolicy == CKSStoresSyncConflictPolicy.ClientRecordWins || (self.syncConflictPolicy == CKSStoresSyncConflictPolicy.GreaterModifiedDateWins && clientServerCKRecord.clientRecord!.modificationDate!.compare(clientServerCKRecord.serverRecord!.modificationDate!) == NSComparisonResult.OrderedDescending)) { let keys = clientServerCKRecord.serverRecord!.allKeys() let values = clientServerCKRecord.clientRecord!.dictionaryWithValuesForKeys(keys) clientServerCKRecord.serverRecord!.setValuesForKeysWithDictionary(values) } finalCKRecords.append(clientServerCKRecord.serverRecord!) } // let userInfo:Dictionary<String,Array<CKRecord>> = [CKSSyncConflictedResolvedRecordsKey:finalCKRecords] // throw NSError(domain: CKSIncrementalStoreSyncOperationErrorDomain, code: CKSStoresSyncError.ConflictsDetected._code, userInfo: userInfo) } } func localChangesInServerRepresentation() throws -> (insertedOrUpdatedCKRecords:Array<CKRecord>,deletedCKRecordIDs:Array<CKRecordID>) { let localChanges = try self.localChanges() return (self.insertedOrUpdatedCKRecords(fromManagedObjects: localChanges.insertedOrUpdatedManagedObjects),self.deletedCKRecordIDs(fromManagedObjects: localChanges.deletedManagedObjects)) } func localChanges() throws -> (insertedOrUpdatedManagedObjects:Array<AnyObject>,deletedManagedObjects:Array<AnyObject>) { let entityNames = self.entities!.map( { (entity) -> String in return entity.name! }) var deletedManagedObjects: Array<AnyObject> = Array<AnyObject>() var insertedOrUpdatedManagedObjects: Array<AnyObject> = Array<AnyObject>() let predicate = NSPredicate(format: "%K != %@", CKSIncrementalStoreLocalStoreChangeTypeAttributeName, NSNumber(short: CKSLocalStoreRecordChangeType.RecordNoChange.rawValue)) for name in entityNames { let fetchRequest = NSFetchRequest(entityName: name) fetchRequest.predicate = predicate var results: Array<AnyObject>? do { results = try self.localStoreMOC!.executeFetchRequest(fetchRequest) if results!.count > 0 { insertedOrUpdatedManagedObjects += (results!.filter({(object)->Bool in let managedObject:NSManagedObject = object as! NSManagedObject if (managedObject.valueForKey(CKSIncrementalStoreLocalStoreChangeTypeAttributeName)) as! NSNumber == NSNumber(short: CKSLocalStoreRecordChangeType.RecordUpdated.rawValue) { return true } return false })) } } catch { throw CKSStoresSyncError.LocalChangesFetchError } } do { let fetchRequest = NSFetchRequest(entityName: CKSDeletedObjectsEntityName) deletedManagedObjects = try self.localStoreMOC!.executeFetchRequest(fetchRequest) } catch { throw CKSStoresSyncError.LocalChangesFetchError } return (insertedOrUpdatedManagedObjects,deletedManagedObjects) } func insertedOrUpdatedCKRecords(fromManagedObjects managedObjects:Array<AnyObject>) -> Array<CKRecord> { return managedObjects.map({(object)->CKRecord in let managedObject:NSManagedObject = object as! NSManagedObject let ckRecordID = CKRecordID(recordName: (managedObject.valueForKey(CKSIncrementalStoreLocalStoreRecordIDAttributeName) as! String), zoneID: CKRecordZoneID(zoneName: CKSIncrementalStoreCloudDatabaseCustomZoneName, ownerName: CKOwnerDefaultName)) var ckRecord:CKRecord if managedObject.valueForKey(CKSIncrementalStoreLocalStoreRecordEncodedValuesAttributeName) != nil { let encodedSystemFields = managedObject.valueForKey(CKSIncrementalStoreLocalStoreRecordEncodedValuesAttributeName) as! NSData ckRecord = CKRecord.recordWithEncodedFields(encodedSystemFields) } else { ckRecord = CKRecord(recordType: (managedObject.entity.name)!, recordID: ckRecordID) } let entityAttributes = managedObject.entity.attributesByName.values.array.filter({(object) -> Bool in let attribute: NSAttributeDescription = object as NSAttributeDescription if attribute.name == CKSIncrementalStoreLocalStoreRecordIDAttributeName || attribute.name == CKSIncrementalStoreLocalStoreChangeTypeAttributeName || attribute.name == CKSIncrementalStoreLocalStoreRecordEncodedValuesAttributeName { return false } return true }) let entityRelationships = managedObject.entity.relationshipsByName.values.array.filter({(object) -> Bool in let relationship: NSRelationshipDescription = object as NSRelationshipDescription return relationship.toMany == false }) for attributeDescription in entityAttributes { if managedObject.valueForKey(attributeDescription.name) != nil { switch attributeDescription.attributeType { case .StringAttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! String, forKey: attributeDescription.name) case .DateAttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSDate, forKey: attributeDescription.name) case .BinaryDataAttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSData, forKey: attributeDescription.name) case .BooleanAttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSNumber, forKey: attributeDescription.name) case .DecimalAttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSNumber, forKey: attributeDescription.name) case .DoubleAttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSNumber, forKey: attributeDescription.name) case .FloatAttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSNumber, forKey: attributeDescription.name) case .Integer16AttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSNumber, forKey: attributeDescription.name) case .Integer32AttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSNumber, forKey: attributeDescription.name) case .Integer64AttributeType: ckRecord.setObject(managedObject.valueForKey(attributeDescription.name) as! NSNumber, forKey: attributeDescription.name) default: break } } } for relationshipDescription in entityRelationships as [NSRelationshipDescription] { if managedObject.valueForKey(relationshipDescription.name) == nil { continue } let relationshipManagedObject: NSManagedObject = managedObject.valueForKey(relationshipDescription.name) as! NSManagedObject let ckRecordZoneID = CKRecordZoneID(zoneName: CKSIncrementalStoreCloudDatabaseCustomZoneName, ownerName: CKOwnerDefaultName) let relationshipCKRecordID = CKRecordID(recordName: relationshipManagedObject.valueForKey(CKSIncrementalStoreLocalStoreRecordIDAttributeName) as! String, zoneID: ckRecordZoneID) let ckReference = CKReference(recordID: relationshipCKRecordID, action: CKReferenceAction.DeleteSelf) ckRecord.setObject(ckReference, forKey: relationshipDescription.name) } return ckRecord }) } func deletedCKRecordIDs(fromManagedObjects managedObjects:Array<AnyObject>)->Array<CKRecordID> { return managedObjects.map({(object)->CKRecordID in let managedObject:NSManagedObject = object as! NSManagedObject let ckRecordID = CKRecordID(recordName: managedObject.valueForKey(CKSIncrementalStoreLocalStoreRecordIDAttributeName) as! String, zoneID: CKRecordZoneID(zoneName: CKSIncrementalStoreCloudDatabaseCustomZoneName, ownerName: CKOwnerDefaultName)) return ckRecordID }) } func fetchRecordChangesFromServer() -> (insertedOrUpdatedCKRecords:Array<CKRecord>,deletedRecordIDs:Array<CKRecordID>,moreComing:Bool) { let token = CKSIncrementalStoreSyncOperationTokenHandler.defaultHandler.token() let recordZoneID = CKRecordZoneID(zoneName: CKSIncrementalStoreCloudDatabaseCustomZoneName, ownerName: CKOwnerDefaultName) let fetchRecordChangesOperation = CKFetchRecordChangesOperation(recordZoneID: recordZoneID, previousServerChangeToken: token) var insertedOrUpdatedCKRecords: Array<CKRecord> = Array<CKRecord>() var deletedCKRecordIDs: Array<CKRecordID> = Array<CKRecordID>() fetchRecordChangesOperation.fetchRecordChangesCompletionBlock = ({(serverChangeToken,clientChangeToken,operationError)->Void in if operationError == nil { CKSIncrementalStoreSyncOperationTokenHandler.defaultHandler.save(serverChangeToken: serverChangeToken!) CKSIncrementalStoreSyncOperationTokenHandler.defaultHandler.commit() } }) fetchRecordChangesOperation.recordChangedBlock = ({(record)->Void in let ckRecord:CKRecord = record as CKRecord insertedOrUpdatedCKRecords.append(ckRecord) }) fetchRecordChangesOperation.recordWithIDWasDeletedBlock = ({(recordID)->Void in deletedCKRecordIDs.append(recordID as CKRecordID) }) self.operationQueue?.addOperation(fetchRecordChangesOperation) self.operationQueue?.waitUntilAllOperationsAreFinished() return (insertedOrUpdatedCKRecords,deletedCKRecordIDs,fetchRecordChangesOperation.moreComing) } func insertOrUpdateManagedObjects(fromCKRecords ckRecords:Array<CKRecord>) throws { let predicate = NSPredicate(format: "%K == $ckRecordIDString",CKSIncrementalStoreLocalStoreRecordIDAttributeName) for object in ckRecords { let ckRecord:CKRecord = object let fetchRequest = NSFetchRequest(entityName: ckRecord.recordType) fetchRequest.predicate = predicate.predicateWithSubstitutionVariables(["ckRecordIDString":ckRecord.recordID.recordName]) fetchRequest.fetchLimit = 1 var results = try self.localStoreMOC!.executeFetchRequest(fetchRequest) if results.count > 0 { let managedObject = results.first as! NSManagedObject let keys = ckRecord.allKeys().filter({(obj)->Bool in if ckRecord.objectForKey(obj as String) is CKReference { return false } return true }) let values = ckRecord.dictionaryWithValuesForKeys(keys) managedObject.setValuesForKeysWithDictionary(values) managedObject.setValue(NSNumber(short: CKSLocalStoreRecordChangeType.RecordNoChange.rawValue), forKey: CKSIncrementalStoreLocalStoreChangeTypeAttributeName) managedObject.setValue(ckRecord.encodedSystemFields(), forKey: CKSIncrementalStoreLocalStoreRecordEncodedValuesAttributeName) let changedCKReferenceRecordIDStringsWithKeys = ckRecord.allKeys().filter({(obj)->Bool in if ckRecord.objectForKey(obj as String) is CKReference { return true } return false }).map({(obj)->(key:String,recordIDString:String) in let key:String = obj as String return (key,(ckRecord.objectForKey(key) as! CKReference).recordID.recordName) }) for object in changedCKReferenceRecordIDStringsWithKeys { let key = object.key let relationship: NSRelationshipDescription? = managedObject.entity.relationshipsByName[key] let attributeEntityName = relationship!.destinationEntity!.name let fetchRequest = NSFetchRequest(entityName: attributeEntityName!) fetchRequest.predicate = NSPredicate(format: "%K == %@", CKSIncrementalStoreLocalStoreRecordIDAttributeName,object.recordIDString) var results = try self.localStoreMOC!.executeFetchRequest(fetchRequest) if results.count > 0 { managedObject.setValue(results.first, forKey: object.key) break } } } else { let managedObject:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName(ckRecord.recordType, inManagedObjectContext: self.localStoreMOC!) as NSManagedObject let keys = ckRecord.allKeys().filter({(object)->Bool in let key:String = object as String if ckRecord.objectForKey(key) is CKReference { return false } return true }) managedObject.setValue(ckRecord.encodedSystemFields(), forKey: CKSIncrementalStoreLocalStoreRecordEncodedValuesAttributeName) let changedCKReferencesRecordIDsWithKeys = ckRecord.allKeys().filter({(object)->Bool in let key:String = object as String if ckRecord.objectForKey(key) is CKReference { return true } return false }).map({(object)->(key:String,recordIDString:String) in let key:String = object as String return (key,(ckRecord.objectForKey(key) as! CKReference).recordID.recordName) }) let values = ckRecord.dictionaryWithValuesForKeys(keys) managedObject.setValuesForKeysWithDictionary(values) managedObject.setValue(NSNumber(short: CKSLocalStoreRecordChangeType.RecordNoChange.rawValue), forKey: CKSIncrementalStoreLocalStoreChangeTypeAttributeName) managedObject.setValue(ckRecord.recordID.recordName, forKey: CKSIncrementalStoreLocalStoreRecordIDAttributeName) for object in changedCKReferencesRecordIDsWithKeys { let ckReferenceRecordIDString:String = object.recordIDString let referenceManagedObject = Array(self.localStoreMOC!.registeredObjects).filter({(object)->Bool in let managedObject:NSManagedObject = object as NSManagedObject if (managedObject.valueForKey(CKSIncrementalStoreLocalStoreRecordIDAttributeName) as! String) == ckReferenceRecordIDString { return true } return false }).first if referenceManagedObject != nil { managedObject.setValue(referenceManagedObject, forKey: object.key) } else { let relationshipDescription: NSRelationshipDescription? = managedObject.entity.relationshipsByName[object.key] let destinationRelationshipDescription: NSEntityDescription? = relationshipDescription?.destinationEntity let entityName: String? = destinationRelationshipDescription!.name let fetchRequest = NSFetchRequest(entityName: entityName!) fetchRequest.predicate = NSPredicate(format: "%K == %@", CKSIncrementalStoreLocalStoreRecordIDAttributeName,ckReferenceRecordIDString) fetchRequest.fetchLimit = 1 var results = try self.localStoreMOC!.executeFetchRequest(fetchRequest) if results.count > 0 { managedObject.setValue(results.first as! NSManagedObject, forKey: object.key) break } } } } } if self.localStoreMOC!.hasChanges { try self.localStoreMOC!.save() } } func deleteManagedObjects(fromCKRecordIDs ckRecordIDs:Array<CKRecordID>) throws { let predicate = NSPredicate(format: "%K IN $ckRecordIDs",CKSIncrementalStoreLocalStoreRecordIDAttributeName) let ckRecordIDStrings = ckRecordIDs.map({(object)->String in let ckRecordID:CKRecordID = object return ckRecordID.recordName }) let entityNames = self.entities!.map { (entity) -> String in return entity.name! } for name in entityNames { let fetchRequest = NSFetchRequest(entityName: name as String) fetchRequest.predicate = predicate.predicateWithSubstitutionVariables(["ckRecordIDs":ckRecordIDStrings]) var results = try self.localStoreMOC!.executeFetchRequest(fetchRequest) if results.count > 0 { for object in results as! [NSManagedObject] { self.localStoreMOC?.deleteObject(object) } } } try self.localStoreMOC?.save() } }
mit
04e225ab60e9051a22dc99ea83e74c09
47.281392
339
0.625952
6.063652
false
false
false
false
Legoless/iOS-Course
2015-1/Lesson11/Stopwatch/Stopwatch/ViewController.swift
1
3654
// // ViewController.swift // Stopwatch // // Created by Dal Rupnik on 15/11/15. // Copyright © 2015 Unified Sense. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var startButton: UIButton! var currentTime = 0.0 var timer : NSTimer? var appeared = false override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "didDeactivate", name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didActivate", name: UIApplicationDidBecomeActiveNotification, object: nil) } func didDeactivate () { appeared = false } func didActivate () { appeared = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) appeared = true } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) appeared = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } deinit { // Clean-up cleanUpTimer() NSNotificationCenter.defaultCenter().removeObserver(self) } @IBAction func startButtonTap(sender: UIButton) { if timer != nil { // Stop the timer cleanUpTimer() sender.setTitle("Start", forState: .Normal) } else { // Start the timer sender.setTitle("Stop", forState: .Normal) currentTime = 30.0 timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateTimer", userInfo: nil, repeats: true) updateTimer() } } @IBAction func addButtonTap(sender: UIButton) { currentTime += 10.0 updateTimer() } func updateTimer () { if !appeared { return } currentTime = currentTime - 1.0 // Counting down if currentTime < 0 { currentTime = 0 } print (currentTime) // Calculate minutes and seconds let minutes = UInt(floor(currentTime / 60.0)) let seconds = UInt(currentTime - (Double(minutes) * 60.0)) timerLabel.text = NSString(format: "%02d:%02d", minutes, seconds) as String if currentTime < 10.0 { timerLabel.textColor = UIColor.orangeColor() } else { timerLabel.textColor = UIColor.blackColor() } // Check timer stop if currentTime == 0.0 { startButton.setTitle("Start", forState: .Normal) timerLabel.textColor = UIColor.redColor() cleanUpTimer() UIView.animateWithDuration(0.33, animations: { self.timerLabel.transform = CGAffineTransformMakeScale(1.2, 1.2) }, completion: { success in UIView.animateWithDuration(0.33, animations: { self.timerLabel.transform = CGAffineTransformIdentity }, completion: nil) }) } } func cleanUpTimer () { if let timer = timer { timer.invalidate() self.timer = nil } } }
mit
cf9fb973f4e3eb6a9bda5cd9cc5f827f
24.725352
151
0.539557
5.628659
false
false
false
false
peterlafferty/LuasLife
Carthage/Checkouts/Decodable/Tests/MissingKeyOperatorTests.swift
1
1270
// // missingKeyOperatorTests.swift // Decodable // // Created by Johannes Lund on 2015-12-20. // Copyright © 2015 anviking. All rights reserved. // import XCTest import Decodable class missingKeyOperatorTests: XCTestCase { func testMissingKey() { // Should return nil let dictionary: NSDictionary = ["key": 3] let result: Int? = try! dictionary =>? "missingKeyError" XCTAssertEqual(result, nil) } func testNSNull() { // Should return nil let dictionary: NSDictionary = ["key": NSNull()] let result: Int? = try! dictionary =>? "key" XCTAssertEqual(result, nil) } func testSuccess() { let dictionary: NSDictionary = ["key": 3] let result: Int? = try! dictionary =>? "key" XCTAssertEqual(result, 3) } func testTypeMismatch() { // Should throw let dictionary: NSDictionary = ["key": "3"] do { let _: Int? = try dictionary =>? "key" XCTFail("should throw") } catch let DecodingError.typeMismatch(expected, _, _) { XCTAssert(expected == Int.self, "\(expected) != Int.self") } catch { XCTFail("Should not throw \(error)") } } }
mit
0d88d9062fbadfe2c60f986413d3b644
26
70
0.564224
4.46831
false
true
false
false
Piwigo/Piwigo-Mobile
piwigoKit/Upload/UploadVars.swift
1
10694
// // UploadVars.swift // piwigoKit // // Created by Eddy Lelièvre-Berna on 01/06/2021. // Copyright © 2021 Piwigo.org. All rights reserved. // import Foundation // MARK: - Privacy Levels public enum kPiwigoPrivacy : Int16 { case everybody = 0 case adminsFamilyFriendsContacts = 1 case adminsFamilyFriends = 2 case adminsFamily = 4 case admins = 8 case count = 5 case unknown = -1 } extension kPiwigoPrivacy { public var name: String { switch self { case .everybody: return NSLocalizedString("privacyLevel_everybody", comment: "Everybody") case .adminsFamilyFriendsContacts: return NSLocalizedString("privacyLevel_adminsFamilyFriendsContacts", comment: "Admins, Family, Friends, Contacts") case .adminsFamilyFriends: return NSLocalizedString("privacyLevel_adminsFamilyFriends", comment: "Admins, Family, Friends") case .adminsFamily: return NSLocalizedString("privacyLevel_adminFamily", comment: "Admins, Family") case .admins: return NSLocalizedString("privacyLevel_admin", comment: "Admins") default: return "" } } } // MARK: - Max Photo Sizes public enum pwgPhotoMaxSizes: Int16, CaseIterable { case fullResolution = 0, Retina5K, UHD4K, DCI2K, FullHD, HD, qHD, nHD } extension pwgPhotoMaxSizes { public var pixels: Int { switch self { case .fullResolution: return Int.max case .Retina5K: return 5120 case .UHD4K: return 3840 case .DCI2K: return 2048 case .FullHD: return 1920 case .HD: return 1280 case .qHD: return 960 case .nHD: return 640 } } public var name: String { switch self { case .fullResolution: return NSLocalizedString("UploadPhotoSize_original", comment: "No Downsizing") case .Retina5K: return "5K | 14.7 Mpx" case .UHD4K: return "4K | 8.29 Mpx" case .DCI2K: return "2K | 2.21 Mpx" case .FullHD: return "Full HD | 2.07 Mpx" case .HD: return "HD | 0.92 Mpx" case .qHD: return "qHD | 0.52 Mpx" case .nHD: return "nHD | 0.23 Mpx" } } } // MARK: - Max Video Sizes public enum pwgVideoMaxSizes: Int16, CaseIterable { case fullResolution = 0, UHD4K, FullHD, HD, qHD, nHD } extension pwgVideoMaxSizes { public var pixels: Int { switch self { case .fullResolution: return Int.max case .UHD4K: return 3840 case .FullHD: return 1920 case .HD: return 1280 case .qHD: return 960 case .nHD: return 640 } } public var name: String { switch self { case .fullResolution: return NSLocalizedString("UploadPhotoSize_original", comment: "No Downsizing") case .UHD4K: return "4K | ≈26.7 Mbit/s" case .FullHD: return "Full HD | ≈15.6 Mbit/s" case .HD: return "HD | ≈11.3 Mbit/s" case .qHD: return "qHD | ≈5.8 Mbit/s" case .nHD: return "nHD | ≈2.8 Mbit/s" } } } // MARK: - Photo Sort Options public enum kPiwigoSort : Int16 { case nameAscending = 0 // Photo title, A → Z case nameDescending // Photo title, Z → A case dateCreatedDescending // Date created, new → old case dateCreatedAscending // Date created, old → new case datePostedDescending // Date posted, new → old case datePostedAscending // Date posted, old → new case fileNameAscending // File name, A → Z case fileNameDescending // File name, Z → A case ratingScoreDescending // Rating score, high → low case ratingScoreAscending // Rating score, low → high case visitsDescending // Visits, high → low case visitsAscending // Visits, low → high case manual // Manual order case random // Random order // case kPiwigoSortVideoOnly // case kPiwigoSortImageOnly case count } public class UploadVars: NSObject { // Remove deprecated stored objects if needed override init() { // Deprecated data? if let _ = UserDefaults.dataSuite.object(forKey: "photoResize") { UserDefaults.dataSuite.removeObject(forKey: "photoResize") } } // MARK: - Vars in UserDefaults / Standard // Upload variables stored in UserDefaults / Standard /// - None // MARK: - Vars in UserDefaults / App Group // Upload variables stored in UserDefaults / App Group /// - Default image sort option @UserDefault("localImagesSort", defaultValue: kPiwigoSort.dateCreatedDescending.rawValue, userDefaults: UserDefaults.dataSuite) public static var localImagesSort: Int16 /// - Default author name @UserDefault("defaultAuthor", defaultValue: "", userDefaults: UserDefaults.dataSuite) public static var defaultAuthor: String /// - Default privacy level @UserDefault("defaultPrivacyLevel", defaultValue: kPiwigoPrivacy.everybody.rawValue, userDefaults: UserDefaults.dataSuite) public static var defaultPrivacyLevel: Int16 /// - Strip GPS metadata before uploading @UserDefault("stripGPSdataOnUpload", defaultValue: false, userDefaults: UserDefaults.dataSuite) public static var stripGPSdataOnUpload: Bool /// - Resize photo before uploading @UserDefault("resizeImageOnUpload", defaultValue: false, userDefaults: UserDefaults.dataSuite) public static var resizeImageOnUpload: Bool /// - Max photo size to apply when downsizing /// - before version 2.7, we stored in 'photoResize' the fraction of the photo size to apply when resizing. @UserDefault("photoMaxSize", defaultValue: 0, userDefaults: UserDefaults.dataSuite) public static var photoMaxSize: Int16 public class func selectedPhotoSizeFromSize(_ size:Int16) -> Int16 { for index in (0...pwgPhotoMaxSizes.allCases.count-1).reversed() { if size < pwgPhotoMaxSizes(rawValue: Int16(index))?.pixels ?? 0 { return Int16(index) } } return 0 } /// - Max video size to apply when downsizing /// - before version 2.7, we stored in 'photoResize' the fraction of the photo or video size to apply when resizing. @UserDefault("videoMaxSize", defaultValue: 0, userDefaults: UserDefaults.dataSuite) public static var videoMaxSize: Int16 public class func selectedVideoSizeFromSize(_ size:Int16) -> Int16 { for index in (0...pwgVideoMaxSizes.allCases.count-1).reversed() { if size < pwgVideoMaxSizes(rawValue: Int16(index))?.pixels ?? 0 { return Int16(index) } } return 0 } /// - Compress photo before uploading @UserDefault("compressImageOnUpload", defaultValue: false, userDefaults: UserDefaults.dataSuite) public static var compressImageOnUpload: Bool /// - Quality factor to adopt when compressing @UserDefault("photoQuality", defaultValue: 98, userDefaults: UserDefaults.dataSuite) public static var photoQuality: Int16 /// - Delete photo after upload @UserDefault("deleteImageAfterUpload", defaultValue: false, userDefaults: UserDefaults.dataSuite) public static var deleteImageAfterUpload: Bool /// - Prefix file name before uploading @UserDefault("prefixFileNameBeforeUpload", defaultValue: false, userDefaults: UserDefaults.dataSuite) public static var prefixFileNameBeforeUpload: Bool /// - Prefix added to file name before uploading @UserDefault("defaultPrefix", defaultValue: "", userDefaults: UserDefaults.dataSuite) public static var defaultPrefix: String /// - File types accepted by the Piwigo server @UserDefault("serverFileTypes", defaultValue: "jpg,jpeg,png,gif", userDefaults: UserDefaults.dataSuite) public static var serverFileTypes: String /// - Chunk size wanted by the Piwigo server (500 KB by default) @UserDefault("uploadChunkSize", defaultValue: 500, userDefaults: UserDefaults.dataSuite) public static var uploadChunkSize: Int /// - Only upload photos when a Wi-Fi network is available @UserDefault("wifiOnlyUploading", defaultValue: false, userDefaults: UserDefaults.dataSuite) public static var wifiOnlyUploading: Bool /// - Is auto-upload mode active? @UserDefault("isAutoUploadActive", defaultValue: false, userDefaults: UserDefaults.dataSuite) public static var isAutoUploadActive: Bool /// - Local identifier of the Photo Library album containing photos to upload (i.e. source album) @UserDefault("autoUploadAlbumId", defaultValue: "", userDefaults: UserDefaults.dataSuite) public static var autoUploadAlbumId: String /// - Category ID of the Piwigo album to upload photos into (i.e. destination album) @UserDefault("autoUploadCategoryId", defaultValue: NSNotFound, userDefaults: UserDefaults.dataSuite) public static var autoUploadCategoryId: Int /// - IDs of the tags applied to the photos to auto-upload @UserDefault("autoUploadTagIds", defaultValue: "", userDefaults: UserDefaults.dataSuite) public static var autoUploadTagIds: String /// - Comments to add to the photos to auto-upload @UserDefault("autoUploadComments", defaultValue: "", userDefaults: UserDefaults.dataSuite) public static var autoUploadComments: String /// - When the latest deletion of Photo Library images was accomplished static let kPiwigoOneDay = (TimeInterval)(24 * 60 * 60) // i.e. 1 day @UserDefault("dateOfLastPhotoLibraryDeletion", defaultValue: Date.distantPast.timeIntervalSinceReferenceDate, userDefaults: UserDefaults.dataSuite) public static var dateOfLastPhotoLibraryDeletion: TimeInterval // MARK: - Vars in Memory // Upload variables kept in memory /// - Custom HTTP header field names static let HTTPuploadID = "X-PWG-UploadID" static let HTTPimageID = "X-PWG-localIdentifier" static let HTTPchunk = "X-PWG-chunk" static let HTTPchunks = "X-PWG-chunks" static let HTTPmd5sum = "X-PWG-md5sum" static let HTTPfileSize = "X-PWG-fileSize" }
mit
00fbef2d806db30c69c1c55694b5b899
39.679389
151
0.647213
4.493255
false
false
false
false
huonw/swift
benchmark/single-source/Substring.swift
6
8162
//===--- Substring.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let SubstringTest = [ BenchmarkInfo(name: "EqualStringSubstring", runFunction: run_EqualStringSubstring, tags: [.validation, .api, .String]), BenchmarkInfo(name: "EqualSubstringString", runFunction: run_EqualSubstringString, tags: [.validation, .api, .String]), BenchmarkInfo(name: "EqualSubstringSubstring", runFunction: run_EqualSubstringSubstring, tags: [.validation, .api, .String]), BenchmarkInfo(name: "EqualSubstringSubstringGenericEquatable", runFunction: run_EqualSubstringSubstringGenericEquatable, tags: [.validation, .api, .String]), BenchmarkInfo(name: "LessSubstringSubstring", runFunction: run_LessSubstringSubstring, tags: [.validation, .api, .String]), BenchmarkInfo(name: "LessSubstringSubstringGenericComparable", runFunction: run_LessSubstringSubstringGenericComparable, tags: [.validation, .api, .String]), BenchmarkInfo(name: "StringFromLongWholeSubstring", runFunction: run_StringFromLongWholeSubstring, tags: [.validation, .api, .String]), BenchmarkInfo(name: "StringFromLongWholeSubstringGeneric", runFunction: run_StringFromLongWholeSubstringGeneric, tags: [.validation, .api, .String]), BenchmarkInfo(name: "SubstringComparable", runFunction: run_SubstringComparable, tags: [.validation, .api, .String]), BenchmarkInfo(name: "SubstringEqualString", runFunction: run_SubstringEqualString, tags: [.validation, .api, .String]), BenchmarkInfo(name: "SubstringEquatable", runFunction: run_SubstringEquatable, tags: [.validation, .api, .String]), BenchmarkInfo(name: "SubstringFromLongString", runFunction: run_SubstringFromLongString, tags: [.validation, .api, .String]), BenchmarkInfo(name: "SubstringFromLongStringGeneric", runFunction: run_SubstringFromLongStringGeneric, tags: [.validation, .api, .String]), ] // A string that doesn't fit in small string storage and doesn't fit in Latin-1 let longWide = "fὢasὢodὢijὢadὢolὢsjὢalὢsdὢjlὢasὢdfὢijὢliὢsdὢjøὢslὢdiὢalὢiὢ" @inline(never) public func run_SubstringFromLongString(_ N: Int) { var s = longWide s += "!" // ensure the string has a real buffer for _ in 1...N*500 { blackHole(Substring(s)) } } func create<T : RangeReplaceableCollection, U : Collection>( _: T.Type, from source: U ) where T.Iterator.Element == U.Iterator.Element { blackHole(T(source)) } @inline(never) public func run_SubstringFromLongStringGeneric(_ N: Int) { var s = longWide s += "!" // ensure the string has a real buffer for _ in 1...N*500 { create(Substring.self, from: s) } } @inline(never) public func run_StringFromLongWholeSubstring(_ N: Int) { var s0 = longWide s0 += "!" // ensure the string has a real buffer let s = Substring(s0) for _ in 1...N*500 { blackHole(String(s)) } } @inline(never) public func run_StringFromLongWholeSubstringGeneric(_ N: Int) { var s0 = longWide s0 += "!" // ensure the string has a real buffer let s = Substring(s0) for _ in 1...N*500 { create(String.self, from: s) } } private func equivalentWithDistinctBuffers() -> (String, Substring) { var s0 = longWide withUnsafeMutablePointer(to: &s0) { blackHole($0) } s0 += "!" // These two should be equal but with distinct buffers, both refcounted. let a = Substring(s0).dropFirst() let b = String(a) return (b, a) } @inline(never) public func run_EqualStringSubstring(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(a == b) } } @inline(never) public func run_EqualSubstringString(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(b == a) } } @inline(never) public func run_EqualSubstringSubstring(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(a == b) } } @inline(never) public func run_EqualSubstringSubstringGenericEquatable(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() func check<T>(_ x: T, _ y: T) where T : Equatable { blackHole(x == y) } for _ in 1...N*500 { check(a, b) } } /* func checkEqual<T, U>(_ x: T, _ y: U) where T : StringProtocol, U : StringProtocol { blackHole(x == y) } @inline(never) public func run _EqualStringSubstringGenericStringProtocol(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkEqual(a, b) } } @inline(never) public func run _EqualSubstringStringGenericStringProtocol(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkEqual(b, a) } } @inline(never) public func run _EqualSubstringSubstringGenericStringProtocol(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkEqual(a, b) } } */ //===----------------------------------------------------------------------===// /* @inline(never) public func run _LessStringSubstring(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(a < b) } } @inline(never) public func run _LessSubstringString(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(b < a) } } */ @inline(never) public func run_LessSubstringSubstring(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(a < b) } } @inline(never) public func run_LessSubstringSubstringGenericComparable(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() func check<T>(_ x: T, _ y: T) where T : Comparable { blackHole(x < y) } for _ in 1...N*500 { check(a, b) } } @inline(never) public func run_SubstringEquatable(_ N: Int) { var string = "pen,pineapple,apple,pen" string += ",✒️,🍍,🍏,✒️" let substrings = string.split(separator: ",") var count = 0 for _ in 1...N*500 { for s in substrings { if substrings.contains(s) { count = count &+ 1 } } } CheckResults(count == 8*N*500) } @inline(never) public func run_SubstringEqualString(_ N: Int) { var string = "pen,pineapple,apple,pen" string += ",✒️,🍍,🍏,✒️" let substrings = string.split(separator: ",") let pineapple = "pineapple" let apple = "🍏" var count = 0 for _ in 1...N*500 { for s in substrings { if s == pineapple || s == apple { count = count &+ 1 } } } CheckResults(count == 2*N*500) } @inline(never) public func run_SubstringComparable(_ N: Int) { var string = "pen,pineapple,apple,pen" string += ",✒️,🍍,🍏,✒️" let substrings = string.split(separator: ",") let comparison = substrings + ["PPAP"] var count = 0 for _ in 1...N*500 { if substrings.lexicographicallyPrecedes(comparison) { count = count &+ 1 } } CheckResults(count == N*500) } /* func checkLess<T, U>(_ x: T, _ y: U) where T : StringProtocol, U : StringProtocol { blackHole(x < y) } @inline(never) public func run _LessStringSubstringGenericStringProtocol(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkLess(a, b) } } @inline(never) public func run _LessSubstringStringGenericStringProtocol(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkLess(b, a) } } @inline(never) public func run _LessSubstringSubstringGenericStringProtocol(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkLess(a, b) } } */
apache-2.0
01d882094d4f7435664d92cbc7b5f145
28.474453
159
0.666295
3.348259
false
false
false
false
abiaoLHB/LHBWeiBo-Swift
LHBWeibo/LHBWeibo/MainWibo/Compose/ComposeTitleView.swift
1
1428
// // ComposeTitleView.swift // LHBWeibo // // Created by LHB on 16/8/24. // Copyright © 2016年 LHB. All rights reserved. // import UIKit import SnapKit class ComposeTitleView: UIView { private lazy var titleLabel : UILabel = UILabel() private lazy var screenNameLabel : UILabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupTitleView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ComposeTitleView{ private func setupTitleView(){ //1、将子控件添加到view中 addSubview(titleLabel) addSubview(screenNameLabel) //2、设置frame titleLabel.snp_makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(self) } screenNameLabel.snp_makeConstraints { (make) in make.centerX.equalTo(titleLabel.snp_centerX) make.top.equalTo(titleLabel.snp_bottom).offset(5) } //3、设置属性 titleLabel.font = UIFont.systemFontOfSize(16) screenNameLabel.font = UIFont.systemFontOfSize(13) screenNameLabel.textColor = UIColor.lightGrayColor() //4、文字内容 titleLabel.text = "发微博" screenNameLabel.text = UserAccountViewMdoel.shareInstance.account?.screen_name } }
apache-2.0
ef95608e9e5969e63d37003136fad4d8
25.461538
86
0.633455
4.435484
false
false
false
false
yanif/circator
MetabolicCompassKit/PreviewManager.swift
1
14295
// // PreviewManager.swift // MetabolicCompass // // Created by Sihao Lu on 11/22/15. // Copyright © 2015 Yanif Ahmad, Tom Woolf. All rights reserved. // import HealthKit import SwiftyUserDefaults private let PMSampleTypesKey = DefaultsKey<[NSData]?>("previewSampleTypes") private let PMManageSampleTypesKey = DefaultsKey<[NSData]?>("manageSampleTypesKey") private let PMChartsSampleTypesKey = DefaultsKey<[NSData]?>("chartsSampleTypes") private let PMManageChartsSampleTypesKey = DefaultsKey<[NSData]?>("manageChartsSampleTypes") private let PMBalanceSampleTypesKey = DefaultsKey<[NSData]?>("balanceSampleTypes") public let PMDidUpdateBalanceSampleTypesNotification = "PMDidUpdateBalanceSampleTypesNotification" /** Controls the HealthKit metrics that will be displayed on picker wheels, tableviews, and radar charts - Parameters: - previewChoices: array of seven sub-arrays for metrics that can be displayed - rowIcons: images for each of the metrics - previewSampleTypes: current set of seven active metrics for display */ public class PreviewManager: NSObject { public static let previewSampleMeals = [ "Breakfast", "Lunch", "Dinner", "Snack" ] public static let previewSampleTimes = [ NSDate() ] static func setupTypes() -> [HKSampleType] { return [ HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBasalEnergyBurned)!, HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierUVExposure)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFiber)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySodium)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCaffeine)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatPolyunsaturated)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatSaturated)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatMonounsaturated)!,// HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryWater)!,// HKObjectType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierBloodPressure)!, ] } public static let supportedTypes:[HKSampleType] = PreviewManager.setupTypes() public static let previewChoices: [[HKSampleType]] = [ [ HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)! ], [ HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)! ], [ HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierUVExposure)! ], [ HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates)! ], [ HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySodium)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCaffeine)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol)! ], [ HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatPolyunsaturated)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatSaturated)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatMonounsaturated)! ], [ HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryWater)!, HKObjectType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierBloodPressure)! ], ] public static let rowIcons: [HKSampleType: UIImage] = { _ in let previewIcons : [HKSampleType: String] = [ HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis)! : "icon_sleep", HKObjectType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierBloodPressure)! : "icon_blood_pressure", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)! : "icon_run", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)! : "icon_scale", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)! : "scale_white_for_BMI", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCaffeine)! : "icon_coffee_for_caffeine", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates)! : "icon_jelly_donut_for_carbs", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol)! : "icon_egg_shell", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)! : "icon_eating_at_table", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatMonounsaturated)! : "icon_olive_oil_jug_for_monounsaturated_fat", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatPolyunsaturated)! : "icon_corn_for_polyunsaturated_fat", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatSaturated)! : "icon_cocunut_for_saturated_fat", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal)! : "icon_for_fat_using_mayannoise", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)! : "icon_steak_for_protein", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySodium)! : "icon_salt_for_sodium_entry", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)! : "icon_sugar_cubes_three", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryWater)! : "icon_water_droplet", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)! : "icon_heart_rate", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)! : "icon_steps_white", HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierUVExposure)! : "icon_sun", ] return Dictionary(pairs: previewIcons.map { (k,v) in return (k, UIImage(named: v)!) }) }() public static func resetPreviewTypes() { Defaults.remove(PMSampleTypesKey) Defaults.remove(PMManageSampleTypesKey) Defaults.remove(PMChartsSampleTypesKey) Defaults.remove(PMManageChartsSampleTypesKey) Defaults.remove(PMBalanceSampleTypesKey) } //MARK: Preview Sample Types public static var previewSampleTypes: [HKSampleType] { if let rawTypes = Defaults[PMSampleTypesKey] { return rawTypes.map { (data) -> HKSampleType in return NSKeyedUnarchiver.unarchiveObjectWithData(data) as! HKSampleType } } else { let defaultTypes = self.supportedTypes self.updatePreviewSampleTypes(defaultTypes) return defaultTypes } } public static func updatePreviewSampleTypes (types: [HKSampleType]) { let rawTypes = types.map { (sampleType) -> NSData in return NSKeyedArchiver.archivedDataWithRootObject(sampleType) } Defaults[PMSampleTypesKey] = rawTypes } public static var managePreviewSampleTypes: [HKSampleType] { if let rawTypes = Defaults[PMManageSampleTypesKey] { return rawTypes.map { (data) -> HKSampleType in return NSKeyedUnarchiver.unarchiveObjectWithData(data) as! HKSampleType } } else { let defaultTypes = self.supportedTypes self.updateManagePreviewSampleTypes(defaultTypes) return defaultTypes } } public static func updateManagePreviewSampleTypes (types: [HKSampleType]) { let rawTypes = types.map { (sampleType) -> NSData in return NSKeyedArchiver.archivedDataWithRootObject(sampleType) } Defaults[PMManageSampleTypesKey] = rawTypes } //MARK: Balance Sample Types public static var balanceSampleTypes: [HKSampleType] { if let rawTypes = Defaults[PMBalanceSampleTypesKey] { return rawTypes.map { (data) -> HKSampleType in return NSKeyedUnarchiver.unarchiveObjectWithData(data) as! HKSampleType } } else { let defaultTypes = [HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!, HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatPolyunsaturated)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryWater)!] self.updateBalanceSampleTypes(defaultTypes) return defaultTypes } } public static func updateBalanceSampleTypes (types: [HKSampleType]) { let rawTypes = types.map { (sampleType) -> NSData in return NSKeyedArchiver.archivedDataWithRootObject(sampleType) } Defaults[PMBalanceSampleTypesKey] = rawTypes NSNotificationCenter.defaultCenter().postNotificationName(PMDidUpdateBalanceSampleTypesNotification, object: nil) } //MARK: Charts Sample Types public static var chartsSampleTypes: [HKSampleType] { if let rawTypes = Defaults[PMChartsSampleTypesKey] { return rawTypes.map { (data) -> HKSampleType in return NSKeyedUnarchiver.unarchiveObjectWithData(data) as! HKSampleType } } else { let defaultTypes = self.supportedTypes self.updateChartsSampleTypes(defaultTypes) return defaultTypes } } public static func updateChartsSampleTypes (types: [HKSampleType]) { let rawTypes = types.map { (sampleType) -> NSData in return NSKeyedArchiver.archivedDataWithRootObject(sampleType) } Defaults[PMChartsSampleTypesKey] = rawTypes } public static var manageChartsSampleTypes: [HKSampleType] { if let rawTypes = Defaults[PMManageChartsSampleTypesKey] { return rawTypes.map { (data) -> HKSampleType in return NSKeyedUnarchiver.unarchiveObjectWithData(data) as! HKSampleType } } else { let defaultTypes = self.supportedTypes self.updateManageChartsSampleTypes(defaultTypes) return defaultTypes } } public static func updateManageChartsSampleTypes (types: [HKSampleType]) { let rawTypes = types.map { (sampleType) -> NSData in return NSKeyedArchiver.archivedDataWithRootObject(sampleType) } Defaults[PMManageChartsSampleTypesKey] = rawTypes } /// associates icon with sample type public static func iconForSampleType(sampleType: HKSampleType) -> UIImage { return rowIcons[sampleType] ?? UIImage() } /// with RowSettingViewController enables new association for selected row public static func reselectSampleType(sampleType: HKSampleType, forPreviewRow row: Int) { guard row >= 0 && row < previewChoices.count else { return } var types = previewSampleTypes types.removeAtIndex(row) types.insert(sampleType, atIndex: row) let rawTypes = types.map { (sampleType) -> NSData in return NSKeyedArchiver.archivedDataWithRootObject(sampleType) } Defaults[PMSampleTypesKey] = rawTypes } }
apache-2.0
a7989eec11fa132fc90f3123c6b43efa
50.602888
150
0.70687
6.25558
false
false
false
false
UberJason/PlaidClient
PlaidClient/PlaidAccount.swift
1
3210
// // PlaidAccount.swift // InTheBlack // // Created by Nathan Mann on 12/5/15. // Copyright © 2015 Nathan Mann. All rights reserved. // import UIKit public struct PlaidAccount { ///The name of the account. public let name: String? ///The official name of the account. public let officialName: String? ///The account sub-type. public let subType: String? ///The account type. public let type: String? ///The account number. public let number: String? ///The Plaid ID of the account. public let id: String? ///The item string of the account. Currently not sure what this is used for. public let item: String? ///The user ID of the account. public let user: String? ///The current account balance. This balance only includes cleared transactions. public let currentBalance: NSDecimalNumber? ///The available account balance. The balance includes any pending transactions. public let availableBalance: NSDecimalNumber? ///The type of the account. public let institutionType: String? //The account limit. I believe this is only relevent to credit accounts. public let limit: NSDecimalNumber? ///- institution: JSON formatted data of the account fetched from *Plaid* ///- source: Specifies whether the account was pulled directed from *Plaid* or *Intuit* public init?(account: [String : AnyObject]) { guard let meta = account["meta"] as? [String: AnyObject], let balance = account["balance"] as? [String: AnyObject] else { return nil } self.name = meta["name"] as? String self.officialName = account["official_name"] as? String self.type = account["type"] as? String self.number = meta["number"] as? String self.id = account["_id"] as? String self.item = account["_item"] as? String self.user = account["_user"] as? String self.institutionType = account["institution_type"] as? String self.subType = account["subType"] as? String if let current = balance["current"] as? Double { self.currentBalance = type == "credit" ? NSDecimalNumber(double: current).decimalNumberByMultiplyingBy(NSDecimalNumber(double: -1.0)) : NSDecimalNumber(double: current) } else { self.currentBalance = nil } if let available = balance["availabe"] as? Double { self.availableBalance = type == "credit" ? NSDecimalNumber(double: available).decimalNumberByMultiplyingBy(NSDecimalNumber(double: -1.0)) : NSDecimalNumber(double: available) } else { self.availableBalance = nil } if let limit = meta["limit"] as? Double { self.limit = NSDecimalNumber(double: limit) } else { self.limit = nil } } } extension PlaidAccount: Equatable {} public func ==(lhs: PlaidAccount, rhs: PlaidAccount) -> Bool { return lhs.id == lhs.id }
mit
6ee2e70018f5831661081a8c3996c2ed
32.082474
187
0.600187
4.551773
false
false
false
false
YQqiang/Nunchakus
Nunchakus/Nunchakus/Base/ViewController/BaseViewController.swift
1
1550
// // BaseViewController.swift // Nunchakus // // Created by kjlink on 2017/3/21. // Copyright © 2017年 sungrow. All rights reserved. // import UIKit import SnapKit class BaseViewController: UIViewController { lazy var emptyDataView: EmptyDataView = { let emptyDataV = EmptyDataView(frame: CGRect.zero) emptyDataV.clickAction = { [weak self] () -> () in self?.loadRequestData() } self.view.addSubview(emptyDataV) emptyDataV.snp.makeConstraints { (make) in make.edges.equalTo(self.view) } return emptyDataV }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.bgColor() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if !emptyDataView.isHidden { view.bringSubview(toFront: emptyDataView) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() if view.window == nil { view = nil } } /* // 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. } */ } extension BaseViewController { @objc func loadRequestData() { } }
mit
e1ac7eff1d3a8461333f6dcc4dcf2f2b
24.783333
107
0.621202
4.789474
false
false
false
false
pikachu987/PKCAlertView
PKCAlertView/Classes/PKCAlertView.swift
1
11973
//Copyright (c) 2017 pikachu987 <[email protected]> // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import UIKit public enum PKCAlertButtonType { case left, center, right, `default` } public enum PKCAlertAnimationType { case alpha, modal, `default` } public class PKCAlertView: UIView { public var containerView: PKCContainerView public var animationTime: TimeInterval = 0.5 public var animationType: PKCAlertAnimationType = .default var topConst: NSLayoutConstraint? var bottomConst: NSLayoutConstraint? var leadingConst: NSLayoutConstraint? var trailingConst: NSLayoutConstraint? fileprivate var centerConst: NSLayoutConstraint? fileprivate var defaultTopConst: NSLayoutConstraint? public init(_ title: String, message: String, bgColor: UIColor = UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 0.8), padding: CGFloat = 32) { self.containerView = PKCContainerView(title, message: message) super.init(frame: .zero) self.backgroundColor = bgColor self.initVars(padding) } public init(_ title: String, message: String, bgColor: UIColor = UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 0.8), width: CGFloat) { self.containerView = PKCContainerView(title, message: message) super.init(frame: .zero) self.backgroundColor = bgColor let padding = (UIScreen.main.bounds.width - width)/2 self.initVars(padding) } private override init(frame: CGRect) { self.containerView = PKCContainerView("", message: "") super.init(frame: frame) self.initVars(32) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { print("deinit") } private func initVars(_ padding: CGFloat){ self.alpha = 0 self.isHidden = true self.translatesAutoresizingMaskIntoConstraints = false self.clipsToBounds = true self.addSubview(self.containerView) self.addConstraints(self.containerView.horizontalLayout(left: padding, right: padding)) let centerConst = NSLayoutConstraint( item: self, attribute: .centerY, relatedBy: .equal, toItem: self.containerView, attribute: .centerY, multiplier: 1, constant: 0) self.addConstraint(centerConst) self.centerConst = centerConst } // MARK: AddView public func addAlertView(_ text: String, textColor: UIColor = .alertDefault, handler: ((PKCAlertButtonType, String) -> Void)? = nil){ let groupButtonView = self.containerView.buttonView.addButtonGroupView(text, textColor: textColor, handler: handler) groupButtonView.delegate = self } public func addAlertView(_ leftText: String, leftColor: UIColor = .alertCancel, rightText: String, rightColor: UIColor = .alertDefault, handler: ((PKCAlertButtonType, String) -> Void)? = nil){ let groupButtonView = self.containerView.buttonView.addButtonGroupView(leftText, leftColor: leftColor, rightText: rightText, rightColor: rightColor, handler: handler) groupButtonView.delegate = self } public func addAlertView(_ leftText: String, leftColor: UIColor = .alertCancel, centerText: String, centerColor: UIColor = .alertDefault, rightText: String, rightColor: UIColor = .alertDefault, handler: ((PKCAlertButtonType, String) -> Void)? = nil){ let groupButtonView = self.containerView.buttonView.addButtonGroupView(leftText, leftColor: leftColor, centerText: centerText, centerColor: centerColor, rightText: rightText, rightColor: rightColor, handler: handler) groupButtonView.delegate = self } // MARK: AddButton public func addAlertButton(_ defaultButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil){ let groupButtonView = self.containerView.buttonView.addButtonGroupView(defaultButton, handler: handler) groupButtonView.delegate = self } public func addAlertButton(_ leftButton: PKCAlertButton, rightButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil){ let groupButtonView = self.containerView.buttonView.addButtonGroupView(leftButton, rightButton: rightButton, handler: handler) groupButtonView.delegate = self } public func addAlertButton(_ leftButton: PKCAlertButton, centerButton: PKCAlertButton, rightButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil){ let groupButtonView = self.containerView.buttonView.addButtonGroupView(leftButton, centerButton: centerButton, rightButton: rightButton, handler: handler) groupButtonView.delegate = self } private func topWindow() -> UIWindow?{ for window in UIApplication.shared.windows.reversed(){ if window.windowLevel == UIWindowLevelNormal && window.isKeyWindow && window.frame != CGRect.zero{ return window } } return nil } // MARK: Animation public func show(){ guard let window = self.topWindow() else { return } window.addSubview(self) let leadingConst = NSLayoutConstraint(item: window, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) let trailingConst = NSLayoutConstraint(item: window, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) let topConst = NSLayoutConstraint(item: window, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) let bottomConst = NSLayoutConstraint(item: window, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0) leadingConst.priority = UILayoutPriority(999) trailingConst.priority = UILayoutPriority(999) topConst.priority = UILayoutPriority(999) bottomConst.priority = UILayoutPriority(999) window.addConstraints([leadingConst, trailingConst, topConst, bottomConst]) self.leadingConst = leadingConst self.trailingConst = trailingConst self.topConst = topConst self.bottomConst = bottomConst self.containerView.sizeToFit() DispatchQueue.main.async{ self.alpha = 0 self.isHidden = true if self.animationType == .alpha{ self.isHidden = false UIView.animate(withDuration: self.animationTime) { self.alpha = 1 } }else if self.animationType == .modal{ self.alpha = 1 self.isHidden = false self.centerConst?.isActive = false let topConst = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: self.containerView, attribute: .top, multiplier: 1, constant: -(self.bounds.height - self.containerView.bounds.height)/2) self.addConstraint(topConst) let bottomConst = NSLayoutConstraint( item: window, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) self.superview?.addConstraint(bottomConst) DispatchQueue.main.async{ bottomConst.isActive = false UIView.animate(withDuration: self.animationTime) { self.superview?.layoutIfNeeded() } } }else if self.animationType == .default{ self.isHidden = false self.centerConst?.isActive = false let defaultTopConst = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: self.containerView, attribute: .top, multiplier: 1, constant: self.containerView.bounds.height) self.addConstraint(defaultTopConst) self.defaultTopConst = defaultTopConst UIView.animate(withDuration: self.animationTime/3, animations: { self.alpha = 1 }, completion: { (_) in self.defaultTopConst?.constant = -(self.bounds.height - self.containerView.bounds.height)/2 UIView.animate(withDuration: self.animationTime/3*2, animations: { self.layoutIfNeeded() }) }) } } } public func hide(){ guard let superview = self.superview else{ return } if self.animationType == .alpha{ UIView.animate(withDuration: self.animationTime, animations: { self.alpha = 0 }, completion: { (_) in self.isHidden = true self.removeFromSuperview() }) }else if self.animationType == .modal{ let bottomConst = NSLayoutConstraint( item: superview, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) self.superview?.addConstraints([bottomConst]) UIView.animate(withDuration: self.animationTime, animations: { self.superview?.layoutIfNeeded() }, completion: { (_) in self.alpha = 0 self.isHidden = true self.removeFromSuperview() }) }else if self.animationType == .default{ self.defaultTopConst?.constant = self.containerView.bounds.height UIView.animate(withDuration: self.animationTime/3*2, animations: { self.layoutIfNeeded() }, completion: { (_) in UIView.animate(withDuration: self.animationTime/3, animations: { self.alpha = 0 }, completion: { (_) in self.isHidden = true self.removeFromSuperview() }) }) } } } extension PKCAlertView: PKCButtonDelegate{ func pkcButtonAction() { self.hide() } }
mit
362c2d162566dc498ed0f2fe28ea74f4
39.449324
254
0.608369
5.064721
false
false
false
false
hshidara/iOS
A~Maze/A~Maze/GameViewController.swift
1
2154
// // GameViewController.swift // A~Maze // // Created by Hidekazu Shidara on 5/23/15. // Copyright (c) 2015 Hidekazu Shidara. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
mit
70a593347ddba4d1d15f81bb9e0aec0a
30.217391
104
0.625348
5.480916
false
false
false
false
dzenbot/Iconic
Vendor/SwiftGen/Pods/Commander/Sources/ArgumentDescription.swift
1
8816
public enum ArgumentType { case Argument case Option } public protocol ArgumentDescriptor { typealias ValueType /// The arguments name var name:String { get } /// The arguments description var description:String? { get } var type:ArgumentType { get } /// Parse the argument func parse(parser:ArgumentParser) throws -> ValueType } extension ArgumentConvertible { init(string: String) throws { try self.init(parser: ArgumentParser(arguments: [string])) } } public class VaradicArgument<T : ArgumentConvertible> : ArgumentDescriptor { public typealias ValueType = [T] public let name: String public let description: String? public var type: ArgumentType { return .Argument } public init(_ name: String, description: String? = nil) { self.name = name self.description = description } public func parse(parser: ArgumentParser) throws -> ValueType { return try Array<T>(parser: parser) } } public class Argument<T : ArgumentConvertible> : ArgumentDescriptor { public typealias ValueType = T public typealias Validator = ValueType throws -> ValueType public let name:String public let description:String? public let validator:Validator? public var type:ArgumentType { return .Argument } public init(_ name:String, description:String? = nil, validator: Validator? = nil) { self.name = name self.description = description self.validator = validator } public func parse(parser:ArgumentParser) throws -> ValueType { let value: T do { value = try T(parser: parser) } catch ArgumentError.MissingValue { throw ArgumentError.MissingValue(argument: name) } catch { throw error } if let validator = validator { return try validator(value) } return value } } public class Option<T : ArgumentConvertible> : ArgumentDescriptor { public typealias ValueType = T public typealias Validator = ValueType throws -> ValueType public let name:String public let flag:Character? public let description:String? public let `default`:ValueType public var type:ArgumentType { return .Option } public let validator:Validator? public init(_ name:String, _ `default`:ValueType, flag:Character? = nil, description:String? = nil, validator: Validator? = nil) { self.name = name self.flag = flag self.description = description self.`default` = `default` self.validator = validator } public func parse(parser:ArgumentParser) throws -> ValueType { if let value = try parser.shiftValueForOption(name) { let value = try T(string: value) if let validator = validator { return try validator(value) } return value } if let flag = flag { if let value = try parser.shiftValueForFlag(flag) { let value = try T(string: value) if let validator = validator { return try validator(value) } return value } } return `default` } } public class Options<T : ArgumentConvertible> : ArgumentDescriptor { public typealias ValueType = [T] public let name:String public let description:String? public let count:Int public let `default`:ValueType public var type:ArgumentType { return .Option } public init(_ name:String, _ `default`:ValueType, count: Int, description:String? = nil) { self.name = name self.`default` = `default` self.count = count self.description = description } public func parse(parser:ArgumentParser) throws -> ValueType { let values = try parser.shiftValuesForOption(name, count: count) return try values?.map { try T(string: $0) } ?? `default` } } public class Flag : ArgumentDescriptor { public typealias ValueType = Bool public let name:String public let flag:Character? public let disabledName:String public let disabledFlag:Character? public let description:String? public let `default`:ValueType public var type:ArgumentType { return .Option } public init(_ name:String, flag:Character? = nil, disabledName:String? = nil, disabledFlag:Character? = nil, description:String? = nil, `default`:Bool = false) { self.name = name self.disabledName = disabledName ?? "no-\(name)" self.flag = flag self.disabledFlag = disabledFlag self.description = description self.`default` = `default` } public func parse(parser:ArgumentParser) throws -> ValueType { if parser.hasOption(disabledName) { return false } if parser.hasOption(name) { return true } if let flag = flag { if parser.hasFlag(flag) { return true } } if let disabledFlag = disabledFlag { if parser.hasFlag(disabledFlag) { return false } } return `default` } } class BoxedArgumentDescriptor { let name:String let description:String? let `default`:String? let type:ArgumentType init<T : ArgumentDescriptor>(value:T) { name = value.name description = value.description type = value.type if let value = value as? Flag { `default` = value.`default`.description } else { // TODO, default for Option and Options `default` = nil } } } class UsageError : ErrorType, ANSIConvertible, CustomStringConvertible { let message: String let help: Help init(_ message: String, _ help: Help) { self.message = message self.help = help } var description: String { return [message, help.description].filter { !$0.isEmpty }.joinWithSeparator("\n\n") } var ansiDescription: String { return [message, help.ansiDescription].filter { !$0.isEmpty }.joinWithSeparator("\n\n") } } class Help : ErrorType, ANSIConvertible, CustomStringConvertible { let command:String? let group:Group? let descriptors:[BoxedArgumentDescriptor] init(_ descriptors:[BoxedArgumentDescriptor], command:String? = nil, group:Group? = nil) { self.command = command self.group = group self.descriptors = descriptors } func reraise(command:String? = nil) -> Help { if let oldCommand = self.command, newCommand = command { return Help(descriptors, command: "\(newCommand) \(oldCommand)") } return Help(descriptors, command: command ?? self.command) } var description: String { var output = [String]() let arguments = descriptors.filter { $0.type == ArgumentType.Argument } let options = descriptors.filter { $0.type == ArgumentType.Option } if let command = command { let args = arguments.map { "<\($0.name)>" } let usage = ([command] + args).joinWithSeparator(" ") output.append("Usage:") output.append("") output.append(" \(usage)") output.append("") } if let group = group { output.append("Commands:") output.append("") for command in group.commands { if let description = command.description { output.append(" + \(command.name) - \(description)") } else { output.append(" + \(command.name)") } } output.append("") } if !options.isEmpty { output.append("Options:") for option in options { // TODO: default, [default: `\(`default`)`] if let description = option.description { output.append(" --\(option.name) - \(description)") } else { output.append(" --\(option.name)") } } } return output.joinWithSeparator("\n") } var ansiDescription: String { var output = [String]() let arguments = descriptors.filter { $0.type == ArgumentType.Argument } let options = descriptors.filter { $0.type == ArgumentType.Option } if let command = command { let args = arguments.map { "<\($0.name)>" } let usage = ([command] + args).joinWithSeparator(" ") output.append("Usage:") output.append("") output.append(" \(usage)") output.append("") } if let group = group { output.append("Commands:") output.append("") for command in group.commands { if let description = command.description { output.append(" + \(ANSI.Green)\(command.name)\(ANSI.Reset) - \(description)") } else { output.append(" + \(ANSI.Green)\(command.name)\(ANSI.Reset)") } } output.append("") } if !options.isEmpty { output.append("Options:") for option in options { // TODO: default, [default: `\(`default`)`] if let description = option.description { output.append(" \(ANSI.Blue)--\(option.name)\(ANSI.Reset) - \(description)") } else { output.append(" \(ANSI.Blue)--\(option.name)\(ANSI.Reset)") } } } return output.joinWithSeparator("\n") } }
mit
3fdfa75d62884a1e11f84cea7606224e
24.40634
163
0.640994
4.302587
false
false
false
false
Rypac/hn
hn/HtmlParser.swift
1
3211
// swiftlint:disable cyclomatic_complexity import Foundation public struct HtmlParser { public static func parse(_ html: String) -> FormattedString? { var parser = HtmlParser(text: html) return parser.parse() } private var tokenizer: HtmlTokenizer private var result: String = "" private var points: [FormattingOptions] = [] private var tags: [HtmlTag: [(String.Index, HtmlAttributes)]] = [:] private var dealtWithOpeningTag = false private init(text: String) { tokenizer = HtmlTokenizer(text: text) result.reserveCapacity(text.utf8.count) } private mutating func parse() -> FormattedString? { while let token = tokenizer.nextToken() { switch token { case let .success(tag): switch tag { case let .open(tag, attributes): switch tag { case .p: handleParagraphTag() push(tag, attributes) case .br: let tagEnd = result.endIndex append(newline) points.append(FormattingOptions(.linebreak, range: result.startIndex ..< tagEnd)) default: push(tag, attributes) } case let .close(tag): pop(tag) case let .entity(char), let .text(char): result.unicodeScalars.append(char) } case let .failure(error) where error != .unknownTag: return .none default: break } } if let (index, _) = tags[.p]?.last { points.append(FormattingOptions(.paragraph, range: index ..< result.endIndex)) } return FormattedString(text: result, formatting: points) } private mutating func append(_ char: UnicodeScalar) { result.unicodeScalars.append(char) } private mutating func push(_ tag: HtmlTag, _ attributes: HtmlAttributes) { var stack = tags[tag] ?? [] stack.append((result.endIndex, attributes)) tags[tag] = stack } private mutating func pop(_ tag: HtmlTag) { if let (index, attributes) = tags[tag]?.popLast(), let type = Formatting(for: tag) { points.append( FormattingOptions( type, range: index ..< result.endIndex, attributes: Attributes(attributes) ) ) } } private mutating func handleParagraphTag() { if let (index, _) = tags[.p]?.popLast() { let openTagEnd = result.endIndex append(newline) append(newline) points.append(FormattingOptions(.paragraph, range: index ..< openTagEnd)) } else if !dealtWithOpeningTag { if !result.isEmpty { let openTagEnd = result.endIndex append(newline) append(newline) points.append(FormattingOptions(.paragraph, range: result.startIndex ..< openTagEnd)) } dealtWithOpeningTag = true } else { append(newline) append(newline) } } private let newline: UnicodeScalar = "\n" } public extension Formatting { init?(for tag: HtmlTag) { switch tag { case .a: self = .url case .b: self = .bold case .i: self = .italic case .u: self = .underline case .p: self = .paragraph case .pre: self = .preformatted case .code: self = .code case .br: self = .linebreak } } }
mit
e429cc036e091acbf0014f18cd4fa434
26.921739
93
0.611336
4.18099
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Services/FoodServices.swift
1
2023
// // FoodServices.swift // FoodAndFitness // // Created by Mylo Ho on 4/23/17. // Copyright © 2017 SuHoVan. All rights reserved. // import Foundation import Alamofire import ObjectMapper import RealmSwift import RealmS import SwiftyJSON final class FoodServices { var userFoodId: Int init(userFoodId: Int) { self.userFoodId = userFoodId } @discardableResult class func get(completion: @escaping Completion) -> Request? { let path = ApiPath.userFoods return ApiManager.request(method: .get, urlString: path, completion: { (result) in Mapper<UserFood>().map(result: result, type: .array, completion: completion) }) } @discardableResult class func save(params: UserFoodParams, completion: @escaping Completion) -> Request? { let path = ApiPath.userFoods let parameters: JSObject = [ "food_id": params.foodId, "weight": params.weight, "meal": params.meal ] return ApiManager.request(method: .post, urlString: path, parameters: parameters, completion: { (result) in Mapper<UserFood>().map(result: result, type: .object, completion: completion) }) } @discardableResult func delete(completion: @escaping Completion) -> Request? { let path = ApiPath.UserFood(id: userFoodId).delete return ApiManager.request(method: .delete, urlString: path, completion: { (result) in switch result { case .success(let value): let realm = RealmS() if let userFood = realm.object(ofType: UserFood.self, forPrimaryKey: self.userFoodId) { realm.write { realm.delete(userFood) completion(.success(value)) } } else { completion(.failure(FFError.json)) } case .failure(_): completion(result) } }) } }
mit
03bab38a3f200a06160b97b7c6fa68eb
30.107692
115
0.585559
4.503341
false
false
false
false
uber/RIBs
ios/tutorials/tutorial3/TicTacToe/Root/RootRouter.swift
1
2379
// // Copyright (c) 2017. Uber Technologies // // 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 RIBs protocol RootInteractable: Interactable, LoggedOutListener, LoggedInListener { var router: RootRouting? { get set } var listener: RootListener? { get set } } protocol RootViewControllable: ViewControllable { func present(viewController: ViewControllable) func dismiss(viewController: ViewControllable) } final class RootRouter: LaunchRouter<RootInteractable, RootViewControllable>, RootRouting { init(interactor: RootInteractable, viewController: RootViewControllable, loggedOutBuilder: LoggedOutBuildable, loggedInBuilder: LoggedInBuildable) { self.loggedOutBuilder = loggedOutBuilder self.loggedInBuilder = loggedInBuilder super.init(interactor: interactor, viewController: viewController) interactor.router = self } override func didLoad() { super.didLoad() routeToLoggedOut() } func routeToLoggedIn(withPlayer1Name player1Name: String, player2Name: String) { // Detach logged out. if let loggedOut = self.loggedOut { detachChild(loggedOut) viewController.dismiss(viewController: loggedOut.viewControllable) self.loggedOut = nil } let loggedIn = loggedInBuilder.build(withListener: interactor) attachChild(loggedIn) } // MARK: - Private private let loggedOutBuilder: LoggedOutBuildable private let loggedInBuilder: LoggedInBuildable private var loggedOut: ViewableRouting? private func routeToLoggedOut() { let loggedOut = loggedOutBuilder.build(withListener: interactor) self.loggedOut = loggedOut attachChild(loggedOut) viewController.present(viewController: loggedOut.viewControllable) } }
apache-2.0
5d52baf96e529f76c21c09a47d7e687e
32.041667
91
0.715427
4.777108
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/EntityFactory.swift
1
23803
// // EntityFactory.swift // gameninja // // Created by Benzi on 19/06/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import SpriteKit // MARK: EntityFactory ------------------------------------------ class EntityFactory { // MARK: EntityZIndex ------------------------------------------ struct EntityZIndex { static let Hud:CGFloat = 500.0 static let Background:CGFloat = 0.0 static let Items:CGFloat = 199.0 static let Goal:CGFloat = 200.0 static let Player:CGFloat = 201.0 static let Enemy:CGFloat = 201.0 static let Top:CGFloat = 300.0 static func GetGridIndex(row:Int) -> CGFloat { return 100.0+CGFloat(row) } } var world:WorldMapper init(world:WorldMapper){ self.world = world } func setupGame() { createGrid() createEntities() createPortals() world.cache() world.setupConditions() world.eventBus.raise(GameEvent.GameEntitiesCreated, data: nil) } func createEntities() { for i in 0..<world.level.levelObjects.count { let object = world.level.levelObjects[i] switch(object.group) { case LevelObjectGroup.Player: createPlayer(object.location) case LevelObjectGroup.Item: switch object.type! { case "goal": createGoal(object.location) case let x where x.hasPrefix("zone"): createZoneKey(object) default: break } case LevelObjectGroup.Enemy: createEnemy(object.location, type: getEnemyType(object.type)) case LevelObjectGroup.Powerup: createPowerup(object) default: continue } } } func getEnemyType(name:String) -> EnemyType { switch name { case "enemy" : return EnemyType.OneStep case "twostep" : return EnemyType.TwoStep case "cloner": return EnemyType.Cloner case "monster" : return EnemyType.Monster case "robot": return EnemyType.Robot case "slider_updown": return EnemyType.SliderUpDown case "slider_leftright": return EnemyType.SliderLeftRight case "destroyer" : return EnemyType.Destroyer default: return EnemyType.OneStep } } func createGrid() { let specialCells = world.level.levelObjects.filter({ $0.group == LevelObjectGroup.Cell }) for c in 0..<world.level.columns { for r in 0..<world.level.rows { let cell = world.level.cells[c,r]! let cellPosition = world.gs.getCellPosition(row: r, column: c) if cell.walls == Direction.All { if world.theme.settings.ignoreBlocks { continue } if (cell.blockRoundedness == 0) { continue } cell.type = CellType.Block var blockNodeName:String! switch cell.blockRoundedness { case 21: blockNodeName = "corner_tl" case 22: blockNodeName = "corner_tr" case 23: blockNodeName = "corner_bl" case 24: blockNodeName = "corner_br" case 29: blockNodeName = "corner_top" case 30: blockNodeName = "corner_bottom" case 31: blockNodeName = "corner_left" case 32: blockNodeName = "corner_right" case 35: blockNodeName = "corner_all" case 39: blockNodeName = "corner_diagonal_down" case 40: blockNodeName = "corner_diagonal_up" default: break } blockNodeName = world.theme.getTextureName(blockNodeName) let blockNode = SKSpriteNode(texture: SpriteManager.Shared.grid.texture(blockNodeName)) if world.theme.settings.colorizeCells { blockNode.colorBlendFactor = world.theme.settings.cellColorBlendFactor blockNode.color = world.theme.getBlockColor(column: c, row: r) } blockNode.size = CGSizeMake(world.gs.sideLength, world.gs.sideLength+world.gs.cellExtends) blockNode.position = CGPointMake(cellPosition.x, cellPosition.y-world.gs.cellExtends) blockNode.anchorPoint = CGPointZero blockNode.zPosition = EntityZIndex.GetGridIndex(r) world.scene!.gridNode.addChild(blockNode) let cellComponent = CellComponent(type: CellType.Block) if cell.zone > world.level.initialZone { blockNode.alpha = 0 } let e = world.manager.createEntity() let sprite = SpriteComponent(node: blockNode) world.manager.addComponent(e, c: cellComponent) world.manager.addComponent(e, c: sprite) world.manager.addComponent(e, c: cell.location) continue } // if this is a special cell // add custom changes var cellType = CellType.Normal for i in 0..<specialCells.count { let levelObject = specialCells[i] let l = levelObject.location if l.row == r && l.column == c { if levelObject.type == "fluffy" { cellType = CellType.Fluffy } else if levelObject.type == "falling" { cellType = CellType.Falling } break } } cell.type = cellType var cellNodeName = "cell" switch cell.cellRoundedness { case 17: cellNodeName = "cell_tl" case 18: cellNodeName = "cell_tr" case 19: cellNodeName = "cell_bl" case 20: cellNodeName = "cell_br" case 25: cellNodeName = "cell_top" case 26: cellNodeName = "cell_bottom" case 27: cellNodeName = "cell_left" case 28: cellNodeName = "cell_right" case 36: cellNodeName = "cell_all" default: break } if cellType == CellType.Falling { cellNodeName = "falling_" + cellNodeName } cellNodeName = world.theme.getTextureName(cellNodeName) let cellNode = gridSprite(cellNodeName) if world.theme.settings.colorizeCells { cellNode.color = world.theme.getCellColor(column: c, row: r) cellNode.colorBlendFactor = world.theme.settings.cellColorBlendFactor } cellNode.size = CGSizeMake(world.gs.sideLength, world.gs.sideLength+world.gs.cellExtends) cellNode.position = CGPointMake(cellPosition.x, cellPosition.y-world.gs.cellExtends) cellNode.anchorPoint = CGPointZero cellNode.zPosition = EntityZIndex.GetGridIndex(r) if cellType == CellType.Fluffy { // add an attachment // let fluffy = gridSprite("cell_attach_fluffy") // fluffy.size = world.gs.getSize(1.0) // fluffy.position = world.gs.childNodePositionForCell // cellNode.addChild(fluffy) // add a roatating spike of death type attachment let angle = (unitRandom() > 0.5 ? 1.0 : -1.0) * 2.0*CGFloat(M_PI) let outerSpikes = gridSprite("cell_attach_fluffy_spike_outer") outerSpikes.size = world.gs.getSize(1.0) outerSpikes.position = world.gs.childNodePositionForCell cellNode.addChild(outerSpikes) outerSpikes.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(angle, duration: 10.0))) // let innerSpikes = gridSprite("cell_attach_fluffy_spike_inner") // innerSpikes.size = world.gs.getSize(1.0) // innerSpikes.position = world.gs.childNodePositionForCell // cellNode.addChild(innerSpikes) // innerSpikes.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(-2.0*CGFloat(M_PI), duration: 10.0))) } world.scene!.gridNode.addChild(cellNode) // create the cell component let e = world.manager.createEntity() let sprite = SpriteComponent(node: cellNode) let cellComponent = CellComponent(type: cellType) if cell.zone > world.level.initialZone { cellNode.alpha = 0 } world.manager.addComponent(e, c: cellComponent) world.manager.addComponent(e, c: sprite) world.manager.addComponent(e, c: cell.location) if cell.walls > 0 { // add a wall node let wallNode = gridSprite("wall\(cell.walls)") wallNode.size = CGSizeMake(world.gs.sideLength, 1.125*world.gs.sideLength) wallNode.position = CGPointZero wallNode.anchorPoint = CGPointZero wallNode.color = world.theme.getWallColor() wallNode.colorBlendFactor = 1.0 cellNode.addChild(wallNode) } } } } func createPortals() { let portals:[LevelObject] = world.level.levelObjects.filter({ $0.group == LevelObjectGroup.Portal }) for var p=0; p+1<portals.count; p+=2 { // step in pairs let p1 = portals[p] let p2 = portals[p+1] let p1component = PortalComponent(destination: p2.location, color: PortalColor.Orange) let p2component = PortalComponent(destination: p1.location, color: PortalColor.Blue) let sprite1 = entitySprite("portal_orange") let sprite2 = entitySprite("portal_blue") let p1sprite = SpriteComponent(node: sprite1) let p2sprite = SpriteComponent(node: sprite2) let adjustedSize = world.gs.getSize(FactoredSizes.ScalingFactor.Portal) sprite1.size = adjustedSize sprite2.size = adjustedSize sprite1.position = world.gs.childNodePositionForCell sprite2.position = world.gs.childNodePositionForCell sprite1.position = world.gs.getEntityPosition(p1.location) sprite2.position = world.gs.getEntityPosition(p2.location) sprite1.zPosition = EntityZIndex.Items sprite2.zPosition = EntityZIndex.Items world.scene!.entitiesNode.addChild(sprite1) world.scene!.entitiesNode.addChild(sprite2) // first portal let p1entity = world.manager.createEntity() world.manager.addComponent(p1entity, c: p1component) world.manager.addComponent(p1entity, c: p1sprite) world.manager.addComponent(p1entity, c: p1.location) // second portal let p2entity = world.manager.createEntity() world.manager.addComponent(p2entity, c: p2component) world.manager.addComponent(p2entity, c: p2sprite) world.manager.addComponent(p2entity, c: p2.location) } } func createPlayer(location:LocationComponent) -> Entity { let sprite = entitySprite("player") sprite.size = world.gs.getSize(FactoredSizes.ScalingFactor.Player) sprite.zPosition = EntityZIndex.Player sprite.alpha = 0 // initially not visible let emotion = entitySprite("emotion_happy") emotion.size = sprite.size.scale(FactoredSizes.ScalingFactor.EmotionRelatedToBody) emotion.name = "emotion" sprite.addChild(emotion) world.scene?.entitiesNode.addChild(sprite) let e = world.manager.createEntity() let player = PlayerComponent() let render = SpriteComponent(node: sprite) world.manager.addComponent(e, c: player) world.manager.addComponent(e, c: location) world.manager.addComponent(e, c: render) world.playerLocation = location world.mainPlayer = e world.eventBus.raise(GameEvent.PlayerCreated, data: e) return e } func createEnemy(location:LocationComponent, type:EnemyType) -> Entity { switch type { case .Monster: return createMonster(location) case .Robot: return createRobot(location) case .SliderLeftRight: fallthrough case .SliderUpDown: return createSlider(type, location) case .OneStep: return createGenericMonster(type, location, "enemy", "emotion_angry") case .TwoStep: return createGenericMonster(type, location, "enemy_twostep", "emotion_angry") case .Cloner: return createGenericMonster(type, location, "enemy_cloner", "emotion_angry") case .Destroyer: return createGenericMonster(type, location, "destroyer", "emotion_angry") } } func constructSpriteNode(name:String, texture:String, size:CGSize) -> SKSpriteNode { let node = entitySprite(texture) node.name = name node.size = size return node } func createRobot(location:LocationComponent) -> Entity { let size = world.gs.getSize(FactoredSizes.ScalingFactor.Enemy) let robotBase = constructSpriteNode("base", texture: "robot_base", size: size ) let robotBody = constructSpriteNode("body", texture: "robot", size: size ) let robotLightHolder = constructSpriteNode("light_holder", texture: "robot_light_holder", size: size ) let robotLight = constructSpriteNode("light", texture: "robot_light", size: size ) let robotEyes = constructSpriteNode("emotion", texture: "robot_eyes", size: size.scale(FactoredSizes.ScalingFactor.EmotionRelatedToBody) ) let robotScanArea = constructSpriteNode("scan_area", texture: "robot_scan_area", size: size.scale(3.0)) robotBase.addChild(robotScanArea) robotBase.addChild(robotBody) robotBody.addChild(robotLightHolder) robotBody.addChild(robotLight) robotBody.addChild(robotEyes) robotLight.alpha = 0.0 // initially off return createEnemyEntity(EnemyType.Robot, location: location, rootSprite: robotBase) } func createMonster(location:LocationComponent) -> Entity { let monsterTexture = any(["monster_1","monster_2"]) let monsterBody = constructSpriteNode("body", texture: monsterTexture, size: world.gs.getSize(FactoredSizes.ScalingFactor.Monster) ) let monsterEyes = constructSpriteNode("emotion", texture: "emotion_monster_angry", size: world.gs.getSize(FactoredSizes.ScalingFactor.Monster).scale(FactoredSizes.ScalingFactor.EmotionRelatedToBody) ) monsterBody.addChild(monsterEyes) return createEnemyEntity(EnemyType.Monster, location: location, rootSprite: monsterBody) } func createGenericMonster(type:EnemyType, _ location:LocationComponent, _ bodyTexture:String, _ eyeTexture:String) -> Entity { let size = world.gs.getSize(FactoredSizes.ScalingFactor.Enemy) let monsterBody = constructSpriteNode("body", texture: bodyTexture, size: size ) let monsterEyes = constructSpriteNode("emotion", texture: eyeTexture, size: size.scale(FactoredSizes.ScalingFactor.EmotionRelatedToBody) ) monsterBody.addChild(monsterEyes) return createEnemyEntity(type, location: location, rootSprite: monsterBody) } func createSlider(type:EnemyType, _ location:LocationComponent) -> Entity { let size = world.gs.getSize(FactoredSizes.ScalingFactor.Enemy) let monsterBody = constructSpriteNode("body", texture: "slider", size: size ) let monsterEyes = constructSpriteNode("emotion", texture: "emotion_slider_normal", size: size.scale(FactoredSizes.ScalingFactor.EmotionRelatedToBody) ) monsterEyes.position = CGPointMake(0, 0.25*world.gs.sideLength) monsterBody.addChild(monsterEyes) return createEnemyEntity(type, location: location, rootSprite: monsterBody) } func createEnemyEntity(type:EnemyType, location:LocationComponent, rootSprite:SKSpriteNode) -> Entity { rootSprite.zPosition = EntityZIndex.Enemy // EntityZIndex.GetGridIndex(location.row) rootSprite.position = world.gs.getEnemyPosition(location, type: type) rootSprite.alpha = 0.0 world.scene?.entitiesNode.addChild(rootSprite) // create entity let e = world.manager.createEntity() let enemy = EnemyComponent(type: type) let render = SpriteComponent(node: rootSprite) world.manager.addComponent(e, c: enemy) world.manager.addComponent(e, c: location) world.manager.addComponent(e, c: render) world.eventBus.raise(GameEvent.EnemyCreated, data: e) return e } /// creates a clone at the specified location func cloneEnemy(fromEnemy:Entity) -> Entity { let location = world.location.get(fromEnemy).clone() return createGenericMonster(EnemyType.Cloner, location, "enemy_cloner", "emotion_angry") } func createGoal(location:LocationComponent) -> Entity { let sprite = entitySprite("goal") sprite.size = world.gs.getSize(FactoredSizes.ScalingFactor.Item) sprite.position = world.gs.getEntityPosition(location) sprite.zPosition = EntityZIndex.Goal world.scene!.entitiesNode.addChild(sprite) // the level zone system will take care of making goals visible sprite.alpha = 0.0 let goalAction = SKAction.repeatActionForever( SKAction.scaleTo(1.2, duration: 0.5) .followedBy(SKAction.scaleTo(1.0, duration: 0.5)) ) sprite.runAction(goalAction) let e = world.manager.createEntity() let goal = GoalComponent() let render = SpriteComponent(node: sprite) world.manager.addComponent(e, c: goal) world.manager.addComponent(e, c: location) world.manager.addComponent(e, c: render) world.manager.addComponent(e, c: CollectableComponent()) world.level.cells.get(location)!.goal = e return e } func createZoneKey(zoneKeyObject:LevelObject) -> Entity { let sprite = entitySprite("warp_key") //getNextZoneKey() sprite.size = world.gs.getSize(FactoredSizes.ScalingFactor.Item) sprite.position = world.gs.getEntityPosition(zoneKeyObject.location) sprite.zPosition = EntityZIndex.Items world.scene!.entitiesNode.addChild(sprite) sprite.alpha = 0.0 let scaleAction = SKAction.repeatActionForever( SKAction.scaleTo(1.2, duration: 0.5) .followedBy(SKAction.scaleTo(1.0, duration: 0.5)) ) sprite.runAction(scaleAction) let zonePart = NSString(string: zoneKeyObject.type).stringByReplacingOccurrencesOfString("zone", withString: "") let zoneID = UInt(NSString(string: zonePart).integerValue) let e = world.manager.createEntity() let zone = ZoneKeyComponent(zoneID: zoneID) let render = SpriteComponent(node: sprite) world.manager.addComponent(e, c: zone) world.manager.addComponent(e, c: zoneKeyObject.location) world.manager.addComponent(e, c: render) world.manager.addComponent(e, c: CollectableComponent()) world.level.cells.get(zoneKeyObject.location)!.zoneKey = e return e } /// creates a powerup entity for the specified level object func createPowerup(powerup:LevelObject) { var type:PowerupType! let duration = PowerupDuration.Infinite // determine the type of powerup switch(powerup.type!){ case "freeze": type = PowerupType.Freeze case "slide": type = PowerupType.Slide default:break } let sprite = entitySprite("powerup_\(powerup.type)_on") sprite.size = world.gs.getSize(FactoredSizes.ScalingFactor.Item) sprite.position = world.gs.getEntityPosition(powerup.location) sprite.zPosition = EntityZIndex.Items world.scene!.entitiesNode.addChild(sprite) sprite.alpha = 0.0 let scaleAction = SKAction.repeatActionForever( SKAction.scaleTo(1.2, duration: 0.5) .followedBy(SKAction.scaleTo(1.0, duration: 0.5)) ) sprite.runAction(scaleAction) let spriteComponent = SpriteComponent(node: sprite) // create the powerup entity let p = world.manager.createEntity() world.manager.addComponent(p, c: PowerupComponent(type: type, duration: duration)) world.manager.addComponent(p, c: powerup.location) world.manager.addComponent(p, c: SpriteComponent(node: sprite)) world.manager.addComponent(p, c: CollectableComponent()) world.level.cells.get(powerup.location)!.powerup = p } }
isc
9d1917eb99be38dc507f170de502ffa6
36.544164
133
0.549132
4.876665
false
false
false
false
sagittarius-90/conwaysgameoflife
conwaygame/engine/Engine.swift
1
2059
// // GamEengine.swift // conwaygame // // Created by Eni Sinanaj on 15/04/2017. // Copyright © 2017 NewlineCode. All rights reserved. // import Foundation class Engine { var board: Array<Array<Bool>> var gameSettings: GameSettings init(_ cols: Int,_ rows: Int) { board = Array<Any>() as! Array<Array<Bool>> for _ in 0...rows-1 { var rowValues = Array<Bool>() for _ in 0...cols-1 { rowValues.append(false) } board.append(rowValues) } gameSettings = GameSettings(2, cols: cols, rows: rows) } func statusAt(_ x: Int, _ y: Int) -> Bool { return board[x][y] } func switchOnAt(_ x: Int, _ y: Int) { board[x][y] = true //print(toString(board)) } func switchOffAt(_ x: Int, _ y: Int) { board[x][y] = false //print(toString(board)) } func passGeneration() { var newGeneration = Array<Array<Bool>>() for rowIndex in 0...gameSettings.rows-1 { var rowValues = Array<Bool>() for colIndex in 0...gameSettings.cols-1 { let value = CellProcessor(board: board, settings: gameSettings).processCellAt(row: rowIndex, col: colIndex, value: board[rowIndex][colIndex]) rowValues.append(value) } newGeneration.append(rowValues) } board.removeAll() board.append(contentsOf: newGeneration) //print(toString(board)) } func toString(_ board: Array<Array<Bool>>) -> String { var string: String = "_____________________________________\n" for rowIndex in 0...gameSettings.rows { string = string + "| " for colIndex in 0...gameSettings.cols { string = string + (board[rowIndex][colIndex] ? "true" : "false") + " |" } string = string + "\n" } return string } }
apache-2.0
fa462bca0ad6d08641e6021db6a7ea0c
26.44
157
0.501458
4.091451
false
false
false
false
danielmartin/swift
test/Syntax/round_trip_parse_gen.swift
2
10549
// RUN: rm -rf %t // RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t // RUN: diff -u %s %t // RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds // RUN: diff -u %S/Outputs/round_trip_parse_gen.swift.withkinds %t.withkinds // RUN: %swift-syntax-test -input-source-filename %s -eof > %t // RUN: diff -u %s %t // RUN: %swift-syntax-test -serialize-raw-tree -input-source-filename %s > %t.dump // RUN: %swift-syntax-test -deserialize-raw-tree -input-source-filename %t.dump -output-filename %t // RUN: diff -u %s %t import ABC import A.B.C @objc import A.B @objc import typealias A.B import struct A.B #warning("test warning") #error("test error") #if Blah class C { func bar(_ a: Int) {} func bar1(_ a: Float) -> Float { return -0.6 + 0.1 - 0.3 } func bar2(a: Int, b: Int, c:Int) -> Int { return 1 } func bar3(a: Int) -> Int { return 1 } func bar4(_ a: Int) -> Int { return 1 } func foo() { var a = /*comment*/"ab\(x)c"/*comment*/ var b = /*comment*/+2/*comment*/ bar(1) bar(+10) bar(-10) bar1(-1.1) bar1(1.1) var f = /*comments*/+0.1/*comments*/ foo() _ = "🙂🤗🤩🤔🤨" } func foo1() { _ = bar2(a:1, b:2, c:2) _ = bar2(a:1 + 1, b:2 * 2 + 2, c:2 + 2) _ = bar2(a : bar2(a: 1, b: 2, c: 3), b: 2, c: 3) _ = bar3(a : bar3(a: bar3(a: 1))) _ = bar4(bar4(bar4(1))) _ = [:] _ = [] _ = [1, 2, 3, 4] _ = [1:1, 2:2, 3:3, 4:4] _ = [bar3(a:1), bar3(a:1), bar3(a:1), bar3(a:1)] _ = ["a": bar3(a:1), "b": bar3(a:1), "c": bar3(a:1), "d": bar3(a:1)] foo(nil, nil, nil) _ = type(of: a).self _ = A -> B.C<Int> _ = [(A) throws -> B]() } func boolAnd() -> Bool { return true && false } func boolOr() -> Bool { return true || false } func foo2() { _ = true ? 1 : 0 _ = (true ? 1 : 0) ? (true ? 1 : 0) : (true ? 1 : 0) _ = (1, 2) _ = (first: 1, second: 2) _ = (1) _ = (first: 1) if !true { return } } func foo3() { _ = [Any]() _ = a.a.a _ = a.b _ = 1.a (1 + 1).a.b.foo _ = a as Bool || a as! Bool || a as? Bool _ = a is Bool _ = self _ = Self } func superExpr() { _ = super.foo super.bar() super[12] = 1 super.init() } func implictMember() { _ = .foo _ = .foo(x: 12) _ = .foo { 12 } _ = .foo[12] _ = .foo.bar } init() {} @objc private init(a: Int) init!(a: Int) {} init?(a: Int) {} public init(a: Int) throws {} @objc deinit {} private deinit {} internal subscript(x: Int) -> Int { get {} set {} } subscript() -> Int { return 1 } var x: Int { address { fatalError() } unsafeMutableAddress { fatalError() } } } protocol PP { associatedtype A associatedtype B: Sequence associatedtype C = Int associatedtype D: Sequence = [Int] associatedtype E: Sequence = [[Int]] where A.Element : Sequence private associatedtype F @objc associatedtype G } #endif #if blah typealias A = Any #elseif blahblah typealias B = (Array<Array<Any>>.Element, x: Int) #else typealias C = [Int] #endif typealias D = [Int: String] typealias E = Int?.Protocol typealias F = [Int]!.Type typealias G = (a x: Int, _ y: Int ... = 1) throw -> () -> () typealias H = () rethrows -> () typealias I = (A & B<C>) -> C & D typealias J = inout @autoclosure () -> Int typealias K = (@invalidAttr Int, inout Int, __shared Int, __owned Int) -> () @objc private typealias T<a,b> = Int @objc private typealias T<a,b> class Foo { let bar: Int } class Bar: Foo { var foo: Int = 42 } class C<A, B> where A: Foo, B == Bar {} @available(*, unavailable) private class C {} struct foo { struct foo { struct foo { func foo() { } } } struct foo {} } struct foo { @available(*, unavailable) struct foo {} public class foo { @available(*, unavailable) @objc(fooObjc) private static func foo() {} @objc(fooObjcBar:baz:) private static func foo(bar: String, baz: Int) } } struct S<A, B, C, @objc D> where A:B, B==C, A : C, B.C == D.A, A.B: C.D {} private struct S<A, B>: Base where A: B { private struct S: A, B {} } protocol P: class {} func foo(_ _: Int, a b: Int = 3 + 2, _ c: Int = 2, d _: Int = true ? 2: 3, @objc e: X = true, f: inout Int, g: Int...) throws -> [Int: String] {} func foo(_ a: Int) throws -> Int {} func foo( a: Int) rethrows -> Int {} struct C { @objc @available(*, unavailable) private static override func foo<a, b, c>(a b: Int, c: Int) throws -> [Int] where a==p1, b:p2 { ddd } func rootView() -> Label {} static func ==() -> bool {} static func !=<a, b, c>() -> bool {} } @objc private protocol foo : bar where A==B {} protocol foo { func foo() } private protocol foo{} @objc public protocol foo where A:B {} #if blah func tryfoo() { try foo() try! foo() try? foo() try! foo().bar().foo().bar() } #else func closure() { _ = {[weak a, unowned(safe) self, b = 3, unowned(unsafe) c = foo().bar] in } _ = {[] in } _ = { [] a, b, _ -> Int in return 2 } _ = { [] (a: Int, b: Int, _: Int) -> Int in return 2 } _ = { [] a, b, _ throws -> Int in return 2 } _ = { [] (a: Int, _ b: Int) throws -> Int in return 2 } _ = { a, b in } _ = { (a, b) in } _ = {} _ = { s1, s2 in s1 > s2 } _ = { $0 > $1 } } #endif func postfix() { foo() foo() {} foo {} foo.bar() foo.bar() {} foo.bar {} foo[] foo[1] foo[] {} foo[1] {} foo[1][2,x:3] foo?++.bar!(baz).self foo().0 foo<Int>.bar foo<Int>() foo.bar<Int>() foo(x:y:)() foo(x:)<Int> { } _ = .foo(x:y:) _ = x.foo(x:y:) _ = foo(&d) _ = <#Placeholder#> + <#T##(Int) -> Int#> } #if blah #else #endif class C { var a: Int { @objc mutating set(value) {} mutating get { return 3 } @objc didSet {} willSet(newValue){ } } var a : Int { return 3 } } protocol P { var a: Int { get set } var a: Int {} } private final class D { @objc static private var a: Int = 3 { return 3 }, b: Int, c = 4, d : Int { get {} get {}}, (a, b): (Int, Int) let (a, b) = (1,2), _ = 4 {} func patternTests() { for let (x, _) in foo {} for var x: Int in foo {} } } do { switch foo { case let a: break case let a as Int: break case let (a, b): break case (let a, var b): break case is Int: break case let .bar(x): break case MyEnum.foo: break case let a as Int: break case let a?: break } } func statementTests() { do { } catch (var x, let y) { } catch where false { } catch let e where e.foo == bar { } catch { } repeat { } while true LABEL: repeat { } while false while true { } LABEL: while true { } LABEL: do {} LABEL: switch foo { case 1: fallthrough case 2: break LABEL case 3: break } for a in b { defer { () } if c { throw MyError() continue } else { continue LABEL } } if foo, let a = foo, let b: Int = foo, var c = foo, case (let v, _) = foo, case (let v, _): (Int, Int) = foo { } else if foo { } else { } guard let a = b else {} for var i in foo where i.foo {} for case is Int in foo {} switch Foo { case n1: break case n2, n3l: break #if FOO case let (x, y) where !x, n3l where false: break #elseif BAR case let y: break #else case .foo(let x): break #endif default: break } switch foo { case 1, 2, 3: break default: break } switch foo { case 1, 2, 3: break @unknown default: break } switch foo { case 1, 2, 3: break @unknown case _: break } switch foo { case 1, 2, 3: break // This is rejected in Sema, but should be preserved by Syntax. @unknown case (42, -42) where 1 == 2: break @garbage case 0: break @garbage(foobar) case -1: break } } // MARK: - ExtensionDecl extension ext { var s: Int { return 42 } } @available(*, unavailable) fileprivate extension ext {} extension ext : extProtocol {} extension ext where A == Int, B: Numeric {} extension ext.a.b {} func foo() { var a = "abc \(foo()) def \(a + b + "a \(3)") gh" var a = """ abc \( foo() + bar() ) de \(3 + 3 + "abc \(foo()) def") fg """ } func keypath() { _ = \a.?.b _ = \a.b.c _ = \a.b[1] _ = \.a.b _ = \Array<Int>.[] _ = #keyPath(a.b.c) } func objcSelector() { _ = [ #selector(getter: Foo.bar), #selector(setter: Foo.Bar.baz), #selector(Foo.method(x:y:)), #selector(foo[42].bar(x)), #selector({ [x] in return nil }) ] } func objectLiterals() { #fileLiteral(a) #colorLiteral(a, b) #imageLiteral(a, b, c) #column #file #function #dsohandle } enum E1 : String { case foo = 1 case bar = "test", baz(x: Int, String) = 12 indirect case qux(E1) indirect private enum E2<T>: String where T: SomeProtocol { case foo, bar, baz } } precedencegroup FooPrecedence { higherThan: DefaultPrecedence, UnknownPrecedence assignment: false associativity: none } precedencegroup BarPrecedence {} precedencegroup BazPrecedence { associativity: left assignment: true associativity: right lowerThan: DefaultPrecedence } infix operator<++>:FooPrecedence prefix operator..<< postfix operator <- func higherOrderFunc() { let x = [1,2,3] x.reduce(0, +) } if #available(iOS 11, macOS 10.11.2, *) {} @_specialize(where T == Int) @_specialize(exported: true, where T == String) public func specializedGenericFunc<T>(_ t: T) -> T { return t } protocol Q { func g() var x: String { get } func f(x:Int, y:Int) -> Int #if FOO_BAR var conditionalVar: String #endif } struct S : Q, Equatable { @_implements(Q, f(x:y:)) func h(x:Int, y:Int) -> Int { return 6 } @_implements(Equatable, ==(_:_:)) public static func isEqual(_ lhs: S, _ rhs: S) -> Bool { return false } @_implements(P, x) var y: String @_implements(P, g()) func h() {} @available(*, deprecated: 1.2, message: "ABC") fileprivate(set) var x: String } struct ReadModify { var st0 = ("a", "b") var rm0: (String, String) { _read { yield (("a", "b")) } _modify { yield &st0 } } var rm1: (String, String) { _read { yield (st0) } } } @_alignment(16) public struct float3 { public var x, y, z: Float } #sourceLocation(file: "otherFile.swift", line: 5) func foo() {} #sourceLocation() "abc \( } ) def" #assert(true) #assert(false) #assert(true, "hello world")
apache-2.0
8b9f74d82083a22bf61cc9adfb8f5a55
17.677305
105
0.538637
2.846258
false
false
false
false
PrashantMangukiya/SwiftUIDemo
Demo2-UIButton/Demo2-UIButton/ViewController.swift
1
1114
// // ViewController.swift // Demo2-UIButton // // Created by Prashant on 25/09/15. // Copyright © 2015 PrashantKumar Mangukiya. All rights reserved. // import UIKit class ViewController: UIViewController { // number of click var clickCount: Int = 0 // outlet - clickCount label @IBOutlet var clickCountLabel: UILabel! // outlet - button @IBOutlet var buttonClickMe: UIButton! // action - button @IBAction func buttonClickMeAction(_ sender: UIButton) { self.clickCount = self.clickCount + 1 self.clickCountLabel.text = "\(self.clickCount)" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // set click count 0 at start self.clickCount = 0 // set value for click count self.clickCountLabel.text = "\(self.clickCount)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
1da8a651667222a17c7f651dae7b3e2a
23.195652
80
0.626235
4.797414
false
false
false
false
irisapp/das-quadrat
Source/Shared/DataCache.swift
1
9187
// // DataCache.swift // Quadrat // // Created by Constantine Fry on 01/12/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation #if os(iOS) import UIKit #endif /** Configs for data cache. */ struct DataCacheConfiguration { /** Time to keep a data in cache in seconds. Default is 1 week. */ private let maxCacheAge = (60 * 60 * 24 * 7) as NSTimeInterval /** The maximum size for disk cache in bytes. Default is 10MB. */ private let maxDiskCacheSize = (1024 * 1024 * 10) as UInt /** The maximum size for memory cache in bytes. Default is 10MB. */ private let maxMemoryCacheSize = (1024 * 1024 * 10) as UInt } /** The queue for I/O operations. Shared between several instances. */ private let privateQueue = NSOperationQueue() /** Responsible for caching data on disk and memory. Thread safe. */ class DataCache { /** Logger to log all errors. */ var logger: Logger? /** The URL to directory where we put all the files. */ private let directoryURL: NSURL /** In memory cache for NSData. */ private let cache = NSCache() /** Obsever objects from NSNotificationCenter. */ private var observers = [AnyObject]() /** The file manager to use for all file operations. */ private let fileManager = NSFileManager.defaultManager() /** The configuration for cache. */ private let cacheConfiguration = DataCacheConfiguration() init(name: String?) { cache.totalCostLimit = Int(cacheConfiguration.maxMemoryCacheSize) let directoryName = "net.foursquare.quadrat" let subdirectiryName = (name != nil) ? ( "Cache" + name! ) : "DefaultCache" let cacheURL: NSURL? do { cacheURL = try fileManager.URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) } catch _ { fatalError("Can't get access to cache directory") } self.directoryURL = cacheURL!.URLByAppendingPathComponent("\(directoryName)/DataCache/\(subdirectiryName)") privateQueue.maxConcurrentOperationCount = 1 createBaseDirectory() subscribeForNotifications() } deinit { self.observers.forEach { NSNotificationCenter.defaultCenter().removeObserver($0) } } /** Returns data for key. */ func dataForKey(key: String) -> NSData? { var result: NSData? privateQueue.addOperationWithBlock { result = self.cache.objectForKey(key) as? NSData if result == nil { let targetURL = self.directoryURL.URLByAppendingPathComponent(key) result = NSData(contentsOfURL: targetURL) if let result = result { self.cache.setObject(result, forKey: key, cost: result.length) } } } privateQueue.waitUntilAllOperationsAreFinished() return result } /** Copies file into cache. */ func addFileAtURL(URL: NSURL, withKey key: String) { privateQueue.addOperationWithBlock { () -> Void in let targetURL = self.directoryURL.URLByAppendingPathComponent(key) do { try self.fileManager.copyItemAtURL(URL, toURL: targetURL) } catch let error as NSError { self.logger?.logError(error, withMessage: "Cache can't copy file into cache directory.") } catch { } } privateQueue.waitUntilAllOperationsAreFinished() } /** Saves data into cache. */ func addData(data: NSData, withKey key: String) { privateQueue.addOperationWithBlock { () -> Void in let targetURL = self.directoryURL.URLByAppendingPathComponent(key) do { try data.writeToURL(targetURL, options: .DataWritingAtomic) } catch let error as NSError { self.logger?.logError(error, withMessage: "Cache can't save file into cache directory.") } catch { } } } /** Subcribes for iOS specific notifications to perform cache cleaning. */ private func subscribeForNotifications() { #if os(iOS) let center = NSNotificationCenter.defaultCenter() let didEnterBackground = UIApplicationDidEnterBackgroundNotification let firstObserver = center.addObserverForName(didEnterBackground, object: nil, queue: nil) { [weak self] (notification) -> Void in self?.cleanupCache() self?.cache.removeAllObjects() } self.observers.append(firstObserver) let didReceiveMemoryWaring = UIApplicationDidReceiveMemoryWarningNotification let secondObserver = center.addObserverForName(didReceiveMemoryWaring, object: nil, queue: nil) { [weak self] (notification) -> Void in self?.cache.removeAllObjects() } self.observers.append(secondObserver) #endif } /** Creates base directory. */ private func createBaseDirectory() { do { try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { self.logger?.logError(error, withMessage: "Cache can't create base directory.") } } /** Removes all cached files. */ func clearCache() { privateQueue.addOperationWithBlock { self.cache.removeAllObjects() do { try self.fileManager.removeItemAtURL(self.directoryURL) self.createBaseDirectory() } catch let error as NSError { self.logger?.logError(error, withMessage: "Cache can't remove base directory.") } catch { } } } /** Removes expired files. In addition removes 1/4 of files if total size exceeds `maxDiskCacheSize`. */ private func cleanupCache() { privateQueue.addOperationWithBlock { let fileURLs = self.getFilesToRemove() fileURLs.forEach { _ = try? self.fileManager.removeItemAtURL($0) } } } private func getFilesToRemove() -> [NSURL] { let expirationDate = NSDate(timeIntervalSinceNow: -self.cacheConfiguration.maxCacheAge) let properties = [NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey] var cacheSize: UInt = 0 var expiredFiles = [NSURL]() var validFiles = [NSURL]() let fileURLs = self.getCachedFileURLs() /** Searches for expired files and calculates total size. */ fileURLs.forEach { (aFileURL) -> () in let values: [String : AnyObject]? = try? aFileURL.resourceValuesForKeys(properties) if let values = values, let modificationDate = values[NSURLContentModificationDateKey] as? NSDate { if modificationDate.laterDate(expirationDate).isEqualToDate(modificationDate) { validFiles.append(aFileURL) if let fileSize = values[NSURLTotalFileAllocatedSizeKey] as? UInt { cacheSize += fileSize } } else { expiredFiles.append(aFileURL) } } } if cacheSize > self.cacheConfiguration.maxDiskCacheSize { validFiles = self.sortFileURLByModificationDate(validFiles) /** Let's just remove 1/4 of all files. */ validFiles.removeRange(Range(start: 0, end: validFiles.count / 4)) expiredFiles += validFiles } return expiredFiles } private func getCachedFileURLs() -> [NSURL] { let properties = [NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey] do { return try self.fileManager.contentsOfDirectoryAtURL(self.directoryURL, includingPropertiesForKeys: properties, options: .SkipsHiddenFiles) } catch let error as NSError { self.logger?.logError(error, withMessage: "Cache can't get properties of files in base directory.") return [NSURL]() } } private func sortFileURLByModificationDate(urls: [NSURL]) -> [NSURL] { return urls.sort { (url1, url2) -> Bool in let dateKey = [NSURLContentModificationDateKey] do { let values1 = try url1.resourceValuesForKeys(dateKey) as? [String: NSDate] let values2 = try url2.resourceValuesForKeys(dateKey) as? [String: NSDate] if let date1 = values1?[NSURLContentModificationDateKey] { if let date2 = values2?[NSURLContentModificationDateKey] { return date1.compare(date2) == .OrderedAscending } } } catch { return false } return false } } }
bsd-2-clause
6aadf8c64b5765662f371d1f6a794867
37.763713
115
0.60074
5.38827
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Items/Overview/ExpandItem.swift
1
670
class ExpandItem: TableItem { var title: String? var height: CGFloat = 50.0 var shouldShowArrow = false override func cellHeight(tableWidth: CGFloat) -> CGFloat { return height } override func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ExpandCell.hl_reuseIdentifier(), for: indexPath) as! ExpandCell cell.selectionBlock = selectionBlock cell.title = title cell.last = last if shouldShowArrow { cell.showArrow() } else { cell.hideArrow() } return cell } }
mit
0e1b2c5fceb0b7421157834bd9fa54ba
25.8
128
0.629851
4.890511
false
false
false
false
IamAlchemist/DemoDynamicCollectionView
DemoDynamicCollectionView/SpringyCollectionViewLayout.swift
1
5179
// // SpringyCollectionViewLayout.swift // DemoDynamicCollectionView // // Created by Wizard Li on 1/5/16. // Copyright © 2016 morgenworks. All rights reserved. // import UIKit class SpringyCollectionViewLayout : UICollectionViewFlowLayout { lazy var dynamicAnimator : UIDynamicAnimator = { [unowned self] in return UIDynamicAnimator(collectionViewLayout: self) }() var visibleIndexPathsSet : Set<NSIndexPath> = [] var latestDelta : CGFloat = 0 override init() { super.init() initialize() } func initialize() { minimumInteritemSpacing = 10 minimumLineSpacing = 10 itemSize = CGSizeMake(44, 44) sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override func prepareLayout() { super.prepareLayout() let visibleRect = CGRectInset(CGRect(origin: collectionView!.bounds.origin, size: collectionView!.bounds.size), -100, -100) let attributesInVisibleRect = super.layoutAttributesForElementsInRect(visibleRect)! var indexPathsInVisibleRect : Set<NSIndexPath> = Set() for layoutAttribute in attributesInVisibleRect { indexPathsInVisibleRect.insert(layoutAttribute.indexPath) } let noLongerVisibleBehaviors = dynamicAnimator.behaviors.filter { (behavior) -> Bool in if let attachBehavior = behavior as? UIAttachmentBehavior { return !indexPathsInVisibleRect.contains((attachBehavior.items.first as! UICollectionViewLayoutAttributes).indexPath) } else{ return false } } for behavior in noLongerVisibleBehaviors { dynamicAnimator.removeBehavior(behavior) visibleIndexPathsSet.remove(((behavior as! UIAttachmentBehavior).items.first as! UICollectionViewLayoutAttributes).indexPath) } let newlyVisibleItems = attributesInVisibleRect.filter({ (item) in return !visibleIndexPathsSet.contains(item.indexPath) }) let touchLocation = collectionView!.panGestureRecognizer.locationInView(collectionView) for layoutAttribute in newlyVisibleItems { var center = layoutAttribute.center let springyBehavior = UIAttachmentBehavior(item: layoutAttribute, attachedToAnchor: center) springyBehavior.length = 0 springyBehavior.damping = 0.8 springyBehavior.frequency = 1.0 if !CGPointEqualToPoint(CGPointZero, touchLocation) { let yDist = fabsf(Float(touchLocation.y - springyBehavior.anchorPoint.y)) let xDist = fabsf(Float(touchLocation.x - springyBehavior.anchorPoint.x)) let resistance = CGFloat((yDist + xDist) / 1500) if (latestDelta < 0) { center.y += max(latestDelta, latestDelta * resistance) } else{ center.y += min(latestDelta, latestDelta * resistance) } layoutAttribute.center = center dynamicAnimator.addBehavior(springyBehavior) visibleIndexPathsSet.insert(layoutAttribute.indexPath) } } } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return dynamicAnimator.itemsInRect(rect) as? [UICollectionViewLayoutAttributes] } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return dynamicAnimator.layoutAttributesForCellAtIndexPath(indexPath) } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { let scrollView = collectionView! as UIScrollView let delta = newBounds.origin.y - scrollView.bounds.origin.y latestDelta = delta let touchLocation = (collectionView?.panGestureRecognizer.locationInView(collectionView))! for behavior in dynamicAnimator.behaviors as! [UIAttachmentBehavior] { let yDistance = fabsf(Float(touchLocation.y - behavior.anchorPoint.y)) let xDistance = fabsf(Float(touchLocation.x - behavior.anchorPoint.x)) let scrollResistance = CGFloat((yDistance + xDistance)/1500) let item = behavior.items.first! var center = item.center if delta < 0 { center.y += max(delta, delta * scrollResistance) } else{ center.y += min(delta, delta * scrollResistance) } item.center = center dynamicAnimator.updateItemUsingCurrentState(item) } return false } func resetLayout() { dynamicAnimator.removeAllBehaviors() prepareLayout() } }
mit
91c3200aa37fac72b8a26bb2d06a4cbb
35.723404
137
0.618192
5.811448
false
false
false
false
catalanjrj/BarMate
BarMate/BarMate/Drink.swift
1
744
// // Drink.swift // BarMate // // Created by Jorge Catalan on 6/16/16. // Copyright © 2016 Jorge Catalan. All rights reserved. // import UIKit class Drink { var name = String() var image = String() var ingredients = String () var price = Float() init() { name = "" image = "" ingredients = "" price = 0 } init(data:[String:AnyObject]){ name = String(data["name"]) image = String(data["image"]) ingredients = String(data["ingreditents"]) price = data["price"] as! Float } // for(key.value) in barMenuDict func createMeFromFirebase(Data: [String:String]){ } }
cc0-1.0
b1ecb26ff0a99dc0324798ba2de62963
15.886364
56
0.507402
4.016216
false
false
false
false
mikina/Simple-custom-tab-bar
TabBarExample/SimpleCustomTabBar/SimpleCustomTabBar/SimpleCustomTabBar/SimpleCustomTabBarController.swift
1
5719
// // SimpleCustomTabBarController.swift // SimpleCustomTabBar // // Created by Mike Mikina on 3/23/16. // Copyright © 2016 FDT. All rights reserved. // import UIKit let kPageHasStartedTransition = "PageHasStartedTransition" class SimpleCustomTabBarController: UIViewController { var viewControllersCache: NSMutableDictionary? var destinationIdentifier: String? weak var destinationVC: UIViewController? var previousVC: UIViewController? var tabBarVisible = true var manualTransition = false let animationDuration = 0.3 //duration of show/hide tab bar animation let bottomPosition = 0 //bottom tab bar position, 0 - means it will stick to bottom @IBOutlet weak var container: UIView! @IBOutlet var tabButtons: [UIButton]! @IBOutlet weak var tabBar: UIView! @IBOutlet weak var tabBarHeight: NSLayoutConstraint! @IBOutlet weak var tabBarBottom: NSLayoutConstraint! @IBOutlet weak var containerBottom: NSLayoutConstraint! var swipeBackCancelled = false override func viewDidLoad() { super.viewDidLoad() self.viewControllersCache = NSMutableDictionary(); NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(SimpleCustomTabBarController.startedTransition(_:)), name: kPageHasStartedTransition, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.childViewControllers.count < 1 { self.performSegueWithIdentifier("vc1", sender: self.tabButtons[0]) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { self.previousVC = self.destinationVC guard let identifier = segue.identifier else { return; } if self.viewControllersCache?.objectForKey(identifier) == nil { self.viewControllersCache?.setObject(segue.destinationViewController, forKey: identifier) } self.destinationIdentifier = identifier self.destinationVC = self.viewControllersCache?.objectForKey(identifier) as? UIViewController if var hasSwipeBack = self.destinationVC as? SwipeBackPositionProtocol { hasSwipeBack.positionClosure = { position in if let nav = hasSwipeBack as? UINavigationController, let previousVC = nav.viewControllers.last as? TabBarVisibilityProtocol { if previousVC.isVisible && !self.tabBarVisible { self.calculateTabBarPosition(position) } } } } // TODO: Changing bottom constraint actually don't play well. When background // of container is different than white, is shows that container has ended just // before hidden tab bar while animating. /* if let nav = self.destinationVC as? UINavigationController, let vc = nav.viewControllers.last as? TabBarVisibilityProtocol { if vc.isVisible { self.containerBottom.constant = self.tabBarHeight.constant } } */ for button in self.tabButtons { button.selected = false } if let button = sender as? UIButton, let index = self.tabButtons.indexOf(button) { self.tabButtons[index].selected = true } } override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if self.destinationIdentifier == identifier { // We want to go back in navigation bar when user hit currently selected tab if let nav = self.destinationVC as? UINavigationController { nav.popToRootViewControllerAnimated(true) } return false } return true } func hideTabBar() { self.tabBar.layoutIfNeeded() self.tabBarBottom.constant = -self.tabBarHeight.constant UIView.animateWithDuration(self.animationDuration, animations: { self.tabBar.setNeedsLayout() self.tabBar.layoutIfNeeded() }) { (done) in if done { self.tabBarVisible = false } } } func hideTabBarOnCancel() { self.tabBar.layoutIfNeeded() self.tabBarBottom.constant = -self.tabBarHeight.constant UIView.animateWithDuration(self.animationDuration, animations: { self.tabBar.setNeedsLayout() self.tabBar.layoutIfNeeded() }) { (done) in if done { self.swipeBackCancelled = false self.tabBarVisible = false self.manualTransition = false } } } func showTabBar() { self.tabBar.layoutIfNeeded() self.tabBarBottom.constant = CGFloat(self.bottomPosition) UIView.animateWithDuration(self.animationDuration, animations: { self.tabBar.setNeedsLayout() self.tabBar.layoutIfNeeded() }) { (done) in if done { if !self.manualTransition { self.tabBarVisible = true } } } } func startedTransition(notification: NSNotification) { if let item = notification.object as? TabBarVisibilityProtocol { if item.isVisible { self.showTabBar() } else { self.hideTabBar() } } } func calculateTabBarPosition(position: Int) { self.manualTransition = true if position <= 0 { self.swipeBackCancelled = true self.hideTabBarOnCancel() return } if !self.swipeBackCancelled { self.tabBar.layoutIfNeeded() let windowSize = self.view.frame.size.width let percent = Double(position) / Double(windowSize) let calculated = (self.tabBarHeight.constant * CGFloat(percent)) - self.tabBarHeight.constant self.tabBarBottom.constant = calculated self.tabBar.layoutIfNeeded() } } }
mit
f48f56ca4535be06b4958d4fe0cc76ad
30.417582
134
0.689227
4.829392
false
false
false
false
natmark/ProcessingKit
ProcessingKitTests/CGPath+Extension/CGPath+Extension.swift
1
4320
// // CGPath+Extension.swift // ProcessingKitTests // // Created by AtsuyaSato on 2019/01/31. // Copyright © 2019 Atsuya Sato. All rights reserved. // import CoreGraphics extension CGPath: Equatable { public static func ==(lhs: CGPath, rhs: CGPath) -> Bool { if lhs.getPathElementsPoints().count != rhs.getPathElementsPoints().count { return false } if lhs.firstPoint != rhs.firstPoint { return false } if lhs.currentPoint != rhs.currentPoint { return false } for i in 0..<lhs.getPathElementsPoints().count { let lhsElm = lhs.getPathElementsPointsAndTypes().0[i] let lhsElmType = lhs.getPathElementsPointsAndTypes().1[i] let rhsElm = rhs.getPathElementsPointsAndTypes().0[i] let rhsElmType = rhs.getPathElementsPointsAndTypes().1[i] if lhsElmType != rhsElmType { return false } if Int(lhsElm.x * 100000000000) != Int(rhsElm.x * 100000000000) { return false } if Int(lhsElm.y * 100000000000) != Int(rhsElm.y * 100000000000) { return false } } return true } } extension CGPath { var firstPoint: CGPoint? { var firstPoint: CGPoint? = nil self.forEach { element in // Just want the first one, but we have to look at everything guard firstPoint == nil else { return } assert(element.type == .moveToPoint, "Expected the first point to be a move") firstPoint = element.points.pointee } return firstPoint } func forEach( body: @escaping @convention(block) (CGPathElement) -> Void) { typealias Body = @convention(block) (CGPathElement) -> Void let callback: @convention(c) (UnsafeMutableRawPointer, UnsafePointer<CGPathElement>) -> Void = { (info, element) in let body = unsafeBitCast(info, to: Body.self) body(element.pointee) } //print(MemoryLayout.size(ofValue: body)) let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self) self.apply(info: unsafeBody, function: unsafeBitCast(callback, to: CGPathApplierFunction.self)) } func getPathElementsPoints() -> [CGPoint] { var arrayPoints : [CGPoint]! = [CGPoint]() self.forEach { element in switch (element.type) { case CGPathElementType.moveToPoint: arrayPoints.append(element.points[0]) case .addLineToPoint: arrayPoints.append(element.points[0]) case .addQuadCurveToPoint: arrayPoints.append(element.points[0]) arrayPoints.append(element.points[1]) case .addCurveToPoint: arrayPoints.append(element.points[0]) arrayPoints.append(element.points[1]) arrayPoints.append(element.points[2]) default: break } } return arrayPoints } func getPathElementsPointsAndTypes() -> ([CGPoint],[CGPathElementType]) { var arrayPoints : [CGPoint]! = [CGPoint]() var arrayTypes : [CGPathElementType]! = [CGPathElementType]() self.forEach { element in switch (element.type) { case CGPathElementType.moveToPoint: arrayPoints.append(element.points[0]) arrayTypes.append(element.type) case .addLineToPoint: arrayPoints.append(element.points[0]) arrayTypes.append(element.type) case .addQuadCurveToPoint: arrayPoints.append(element.points[0]) arrayPoints.append(element.points[1]) arrayTypes.append(element.type) arrayTypes.append(element.type) case .addCurveToPoint: arrayPoints.append(element.points[0]) arrayPoints.append(element.points[1]) arrayPoints.append(element.points[2]) arrayTypes.append(element.type) arrayTypes.append(element.type) arrayTypes.append(element.type) default: break } } return (arrayPoints,arrayTypes) } }
mit
aed0cf191f2831a77f0bb7725e9835aa
37.221239
123
0.583468
4.604478
false
false
false
false
hooman/swift
stdlib/public/Concurrency/TaskGroup.swift
1
28594
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 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 // //===----------------------------------------------------------------------===// import Swift @_implementationOnly import _SwiftConcurrencyShims // ==== TaskGroup -------------------------------------------------------------- /// Starts a new task group which provides a scope in which a dynamic number of /// tasks may be spawned. /// /// Tasks added to the group by `group.spawn()` will automatically be awaited on /// when the scope exits. If the group exits by throwing, all added tasks will /// be cancelled and their results discarded. /// /// ### Implicit awaiting /// When the group returns it will implicitly await for all spawned tasks to /// complete. The tasks are only cancelled if `cancelAll()` was invoked before /// returning, the groups' task was cancelled, or the group body has thrown. /// /// When results of tasks added to the group need to be collected, one can /// gather their results using the following pattern: /// /// while let result = await group.next() { /// // some accumulation logic (e.g. sum += result) /// } /// /// It is also possible to collect results from the group by using its /// `AsyncSequence` conformance, which enables its use in an asynchronous for-loop, /// like this: /// /// for await result in group { /// // some accumulation logic (e.g. sum += result) /// } /// /// ### Cancellation /// If the task that the group is running in is cancelled, the group becomes /// cancelled and all child tasks spawned in the group are cancelled as well. /// /// Since the `withTaskGroup` provided group is specifically non-throwing, /// child tasks (or the group) cannot react to cancellation by throwing a /// `CancellationError`, however they may interrupt their work and e.g. return /// some best-effort approximation of their work. /// /// If throwing is a good option for the kinds of tasks spawned by the group, /// consider using the `withThrowingTaskGroup` function instead. /// /// Postcondition: /// Once `withTaskGroup` returns it is guaranteed that the `group` is *empty*. /// /// This is achieved in the following way: /// - if the body returns normally: /// - the group will await any not yet complete tasks, /// - once the `withTaskGroup` returns the group is guaranteed to be empty. @available(SwiftStdlib 5.5, *) @inlinable public func withTaskGroup<ChildTaskResult, GroupResult>( of childTaskResultType: ChildTaskResult.Type, returning returnType: GroupResult.Type = GroupResult.self, body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult ) async -> GroupResult { #if compiler(>=5.5) && $BuiltinTaskGroupWithArgument let _group = Builtin.createTaskGroup(ChildTaskResult.self) var group = TaskGroup<ChildTaskResult>(group: _group) // Run the withTaskGroup body. let result = await body(&group) await group.awaitAllRemainingTasks() Builtin.destroyTaskGroup(_group) return result #else fatalError("Swift compiler is incompatible with this SDK version") #endif } /// Starts a new throwing task group which provides a scope in which a dynamic /// number of tasks may be spawned. /// /// Tasks added to the group by `group.spawn()` will automatically be awaited on /// when the scope exits. If the group exits by throwing, all added tasks will /// be cancelled and their results discarded. /// /// ### Implicit awaiting /// When the group returns it will implicitly await for all spawned tasks to /// complete. The tasks are only cancelled if `cancelAll()` was invoked before /// returning, the groups' task was cancelled, or the group body has thrown. /// /// When results of tasks added to the group need to be collected, one can /// gather their results using the following pattern: /// /// while let result = await try group.next() { /// // some accumulation logic (e.g. sum += result) /// } /// /// It is also possible to collect results from the group by using its /// `AsyncSequence` conformance, which enables its use in an asynchronous for-loop, /// like this: /// /// for try await result in group { /// // some accumulation logic (e.g. sum += result) /// } /// /// ### Thrown errors /// When tasks are added to the group using the `group.spawn` function, they may /// immediately begin executing. Even if their results are not collected explicitly /// and such task throws, and was not yet cancelled, it may result in the `withTaskGroup` /// throwing. /// /// ### Cancellation /// If the task that the group is running in is cancelled, the group becomes /// cancelled and all child tasks spawned in the group are cancelled as well. /// /// If an error is thrown out of the task group, all of its remaining tasks /// will be cancelled and the `withTaskGroup` call will rethrow that error. /// /// Individual tasks throwing results in their corresponding `try group.next()` /// call throwing, giving a chance to handle individual errors or letting the /// error be rethrown by the group. /// /// Postcondition: /// Once `withThrowingTaskGroup` returns it is guaranteed that the `group` is *empty*. /// /// This is achieved in the following way: /// - if the body returns normally: /// - the group will await any not yet complete tasks, /// - if any of those tasks throws, the remaining tasks will be cancelled, /// - once the `withTaskGroup` returns the group is guaranteed to be empty. /// - if the body throws: /// - all tasks remaining in the group will be automatically cancelled. @available(SwiftStdlib 5.5, *) @inlinable public func withThrowingTaskGroup<ChildTaskResult, GroupResult>( of childTaskResultType: ChildTaskResult.Type, returning returnType: GroupResult.Type = GroupResult.self, body: (inout ThrowingTaskGroup<ChildTaskResult, Error>) async throws -> GroupResult ) async rethrows -> GroupResult { #if compiler(>=5.5) && $BuiltinTaskGroupWithArgument let _group = Builtin.createTaskGroup(ChildTaskResult.self) var group = ThrowingTaskGroup<ChildTaskResult, Error>(group: _group) do { // Run the withTaskGroup body. let result = try await body(&group) await group.awaitAllRemainingTasks() Builtin.destroyTaskGroup(_group) return result } catch { group.cancelAll() await group.awaitAllRemainingTasks() Builtin.destroyTaskGroup(_group) throw error } #else fatalError("Swift compiler is incompatible with this SDK version") #endif } /// A task group serves as storage for dynamically spawned tasks. /// /// It is created by the `withTaskGroup` function. @available(SwiftStdlib 5.5, *) @frozen public struct TaskGroup<ChildTaskResult: Sendable> { /// Group task into which child tasks offer their results, /// and the `next()` function polls those results from. @usableFromInline internal let _group: Builtin.RawPointer /// No public initializers @inlinable init(group: Builtin.RawPointer) { self._group = group } /// Add a child task to the group. /// /// ### Error handling /// Operations are allowed to `throw`, in which case the `try await next()` /// invocation corresponding to the failed task will re-throw the given task. /// /// The `add` function will never (re-)throw errors from the `operation`. /// Instead, the corresponding `next()` call will throw the error when necessary. /// /// - Parameters: /// - overridingPriority: override priority of the operation task /// - operation: operation to execute and add to the group /// - Returns: /// - `true` if the operation was added to the group successfully, /// `false` otherwise (e.g. because the group `isCancelled`) @_alwaysEmitIntoClient public mutating func addTask( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) { #if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: true, addPendingGroupTaskUnconditionally: true ) // Create the task in this group. _ = Builtin.createAsyncTaskInGroup(flags, _group, operation) #else fatalError("Unsupported Swift compiler") #endif } /// Add a child task to the group. /// /// ### Error handling /// Operations are allowed to `throw`, in which case the `try await next()` /// invocation corresponding to the failed task will re-throw the given task. /// /// The `add` function will never (re-)throw errors from the `operation`. /// Instead, the corresponding `next()` call will throw the error when necessary. /// /// - Parameters: /// - overridingPriority: override priority of the operation task /// - operation: operation to execute and add to the group /// - Returns: /// - `true` if the operation was added to the group successfully, /// `false` otherwise (e.g. because the group `isCancelled`) @_alwaysEmitIntoClient public mutating func addTaskUnlessCancelled( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) -> Bool { #if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false) guard canAdd else { // the group is cancelled and is not accepting any new work return false } let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: true, addPendingGroupTaskUnconditionally: false ) // Create the task in this group. _ = Builtin.createAsyncTaskInGroup(flags, _group, operation) return true #else fatalError("Unsupported Swift compiler") #endif } /// Wait for the a child task that was added to the group to complete, /// and return (or rethrow) the value it completed with. If no tasks are /// pending in the task group this function returns `nil`, allowing the /// following convenient expressions to be written for awaiting for one /// or all tasks to complete: /// /// Await on a single completion: /// /// if let first = try await group.next() { /// return first /// } /// /// Wait and collect all group child task completions: /// /// while let first = try await group.next() { /// collected += value /// } /// return collected /// /// Awaiting on an empty group results in the immediate return of a `nil` /// value, without the group task having to suspend. /// /// It is also possible to use `for await` to collect results of a task groups: /// /// for await try value in group { /// collected += value /// } /// /// ### Thread-safety /// Please note that the `group` object MUST NOT escape into another task. /// The `group.next()` MUST be awaited from the task that had originally /// created the group. It is not allowed to escape the group reference. /// /// Note also that this is generally prevented by Swift's type-system, /// as the `add` operation is `mutating`, and those may not be performed /// from concurrent execution contexts, such as child tasks. /// /// ### Ordering /// Order of values returned by next() is *completion order*, and not /// submission order. I.e. if tasks are added to the group one after another: /// /// group.spawn { 1 } /// group.spawn { 2 } /// /// print(await group.next()) /// /// Prints "1" OR "2" /// /// ### Errors /// If an operation added to the group throws, that error will be rethrown /// by the next() call corresponding to that operation's completion. /// /// It is possible to directly rethrow such error out of a `withTaskGroup` body /// function's body, causing all remaining tasks to be implicitly cancelled. public mutating func next() async -> ChildTaskResult? { // try!-safe because this function only exists for Failure == Never, // and as such, it is impossible to spawn a throwing child task. return try! await _taskGroupWaitNext(group: _group) } /// Await all the remaining tasks on this group. @usableFromInline internal mutating func awaitAllRemainingTasks() async { while let _ = await next() {} } /// Wait for all remaining tasks in the task group to complete before /// returning. @_alwaysEmitIntoClient public mutating func waitForAll() async { await awaitAllRemainingTasks() } /// Query whether the group has any remaining tasks. /// /// Task groups are always empty upon entry to the `withTaskGroup` body, and /// become empty again when `withTaskGroup` returns (either by awaiting on all /// pending tasks or cancelling them). /// /// - Returns: `true` if the group has no pending tasks, `false` otherwise. public var isEmpty: Bool { _taskGroupIsEmpty(_group) } /// Cancel all the remaining, and future, tasks in the group. /// /// A cancelled group will not will create new tasks when the `asyncUnlessCancelled`, /// function is used. It will, however, continue to create tasks when the plain `async` /// function is used. Such tasks will be created yet immediately cancelled, allowing /// the tasks to perform some short-cut implementation, if they are responsive to cancellation. /// /// This function may be called even from within child (or any other) tasks, /// and will reliably cause the group to become cancelled. /// /// - SeeAlso: `Task.isCancelled` /// - SeeAlso: `TaskGroup.isCancelled` public func cancelAll() { _taskGroupCancelAll(group: _group) } /// Returns `true` if the group was cancelled, e.g. by `cancelAll`. /// /// If the task currently running this group was cancelled, the group will /// also be implicitly cancelled, which will be reflected in the return /// value of this function as well. /// /// - Returns: `true` if the group (or its parent task) was cancelled, /// `false` otherwise. public var isCancelled: Bool { return _taskGroupIsCancelled(group: _group) } } // Implementation note: // We are unable to just™ abstract over Failure == Error / Never because of the // complicated relationship between `group.spawn` which dictates if `group.next` // AND the AsyncSequence conformances would be throwing or not. // // We would be able to abstract over TaskGroup<..., Failure> equal to Never // or Error, and specifically only add the `spawn` and `next` functions for // those two cases. However, we are not able to conform to AsyncSequence "twice" // depending on if the Failure is Error or Never, as we'll hit: // conflicting conformance of 'TaskGroup<ChildTaskResult, Failure>' to protocol // 'AsyncSequence'; there cannot be more than one conformance, even with // different conditional bounds // So, sadly we're forced to duplicate the entire implementation of TaskGroup // to TaskGroup and ThrowingTaskGroup. // // The throwing task group is parameterized with failure only because of future // proofing, in case we'd ever have typed errors, however unlikely this may be. // Today the throwing task group failure is simply automatically bound to `Error`. /// A task group serves as storage for dynamically spawned, potentially throwing, /// child tasks. /// /// It is created by the `withTaskGroup` function. @available(SwiftStdlib 5.5, *) @frozen public struct ThrowingTaskGroup<ChildTaskResult: Sendable, Failure: Error> { /// Group task into which child tasks offer their results, /// and the `next()` function polls those results from. @usableFromInline internal let _group: Builtin.RawPointer /// No public initializers @inlinable init(group: Builtin.RawPointer) { self._group = group } /// Await all the remaining tasks on this group. @usableFromInline internal mutating func awaitAllRemainingTasks() async { while true { do { guard let _ = try await next() else { return } } catch {} } } @usableFromInline internal mutating func _waitForAll() async throws { while let _ = try await next() { } } /// Wait for all remaining tasks in the task group to complete before /// returning. @_alwaysEmitIntoClient public mutating func waitForAll() async throws { while let _ = try await next() { } } /// Spawn, unconditionally, a child task in the group. /// /// ### Error handling /// Operations are allowed to `throw`, in which case the `try await next()` /// invocation corresponding to the failed task will re-throw the given task. /// /// The `add` function will never (re-)throw errors from the `operation`. /// Instead, the corresponding `next()` call will throw the error when necessary. /// /// - Parameters: /// - overridingPriority: override priority of the operation task /// - operation: operation to execute and add to the group /// - Returns: /// - `true` if the operation was added to the group successfully, /// `false` otherwise (e.g. because the group `isCancelled`) @_alwaysEmitIntoClient public mutating func addTask( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) { #if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: true, addPendingGroupTaskUnconditionally: true ) // Create the task in this group. _ = Builtin.createAsyncTaskInGroup(flags, _group, operation) #else fatalError("Unsupported Swift compiler") #endif } /// Add a child task to the group. /// /// ### Error handling /// Operations are allowed to `throw`, in which case the `try await next()` /// invocation corresponding to the failed task will re-throw the given task. /// /// The `add` function will never (re-)throw errors from the `operation`. /// Instead, the corresponding `next()` call will throw the error when necessary. /// /// - Parameters: /// - overridingPriority: override priority of the operation task /// - operation: operation to execute and add to the group /// - Returns: /// - `true` if the operation was added to the group successfully, /// `false` otherwise (e.g. because the group `isCancelled`) @_alwaysEmitIntoClient public mutating func addTaskUnlessCancelled( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) -> Bool { #if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false) guard canAdd else { // the group is cancelled and is not accepting any new work return false } let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: true, addPendingGroupTaskUnconditionally: false ) // Create the task in this group. _ = Builtin.createAsyncTaskInGroup(flags, _group, operation) return true #else fatalError("Unsupported Swift compiler") #endif } /// Wait for the a child task that was added to the group to complete, /// and return (or rethrow) the value it completed with. If no tasks are /// pending in the task group this function returns `nil`, allowing the /// following convenient expressions to be written for awaiting for one /// or all tasks to complete: /// /// Await on a single completion: /// /// if let first = try await group.next() { /// return first /// } /// /// Wait and collect all group child task completions: /// /// while let first = try await group.next() { /// collected += value /// } /// return collected /// /// Awaiting on an empty group results in the immediate return of a `nil` /// value, without the group task having to suspend. /// /// It is also possible to use `for await` to collect results of a task groups: /// /// for await try value in group { /// collected += value /// } /// /// ### Thread-safety /// Please note that the `group` object MUST NOT escape into another task. /// The `group.next()` MUST be awaited from the task that had originally /// created the group. It is not allowed to escape the group reference. /// /// Note also that this is generally prevented by Swift's type-system, /// as the `add` operation is `mutating`, and those may not be performed /// from concurrent execution contexts, such as child tasks. /// /// ### Ordering /// Order of values returned by next() is *completion order*, and not /// submission order. I.e. if tasks are added to the group one after another: /// /// group.spawn { 1 } /// group.spawn { 2 } /// /// print(await group.next()) /// /// Prints "1" OR "2" /// /// ### Errors /// If an operation added to the group throws, that error will be rethrown /// by the next() call corresponding to that operation's completion. /// /// It is possible to directly rethrow such error out of a `withTaskGroup` body /// function's body, causing all remaining tasks to be implicitly cancelled. public mutating func next() async throws -> ChildTaskResult? { return try await _taskGroupWaitNext(group: _group) } @_silgen_name("$sScg10nextResults0B0Oyxq_GSgyYaKF") @usableFromInline mutating func nextResultForABI() async throws -> Result<ChildTaskResult, Failure>? { do { guard let success: ChildTaskResult = try await _taskGroupWaitNext(group: _group) else { return nil } return .success(success) } catch { return .failure(error as! Failure) // as!-safe, because we are only allowed to throw Failure (Error) } } /// - SeeAlso: `next()` @_alwaysEmitIntoClient public mutating func nextResult() async -> Result<ChildTaskResult, Failure>? { return try! await nextResultForABI() } /// Query whether the group has any remaining tasks. /// /// Task groups are always empty upon entry to the `withTaskGroup` body, and /// become empty again when `withTaskGroup` returns (either by awaiting on all /// pending tasks or cancelling them). /// /// - Returns: `true` if the group has no pending tasks, `false` otherwise. public var isEmpty: Bool { _taskGroupIsEmpty(_group) } /// Cancel all the remaining tasks in the group. /// /// A cancelled group will not will NOT accept new tasks being added into it. /// /// Any results, including errors thrown by tasks affected by this /// cancellation, are silently discarded. /// /// This function may be called even from within child (or any other) tasks, /// and will reliably cause the group to become cancelled. /// /// - SeeAlso: `Task.isCancelled` /// - SeeAlso: `TaskGroup.isCancelled` public func cancelAll() { _taskGroupCancelAll(group: _group) } /// Returns `true` if the group was cancelled, e.g. by `cancelAll`. /// /// If the task currently running this group was cancelled, the group will /// also be implicitly cancelled, which will be reflected in the return /// value of this function as well. /// /// - Returns: `true` if the group (or its parent task) was cancelled, /// `false` otherwise. public var isCancelled: Bool { return _taskGroupIsCancelled(group: _group) } } /// ==== TaskGroup: AsyncSequence ---------------------------------------------- @available(SwiftStdlib 5.5, *) extension TaskGroup: AsyncSequence { public typealias AsyncIterator = Iterator public typealias Element = ChildTaskResult public func makeAsyncIterator() -> Iterator { return Iterator(group: self) } /// Allows iterating over results of tasks added to the group. /// /// The order of elements returned by this iterator is the same as manually /// invoking the `group.next()` function in a loop, meaning that results /// are returned in *completion order*. /// /// This iterator terminates after all tasks have completed successfully, or /// after any task completes by throwing an error. /// /// - SeeAlso: `TaskGroup.next()` @available(SwiftStdlib 5.5, *) public struct Iterator: AsyncIteratorProtocol { public typealias Element = ChildTaskResult @usableFromInline var group: TaskGroup<ChildTaskResult> @usableFromInline var finished: Bool = false // no public constructors init(group: TaskGroup<ChildTaskResult>) { self.group = group } /// Once this function returns `nil` this specific iterator is guaranteed to /// never produce more values. /// - SeeAlso: `TaskGroup.next()` for a detailed discussion its semantics. public mutating func next() async -> Element? { guard !finished else { return nil } guard let element = await group.next() else { finished = true return nil } return element } public mutating func cancel() { finished = true group.cancelAll() } } } @available(SwiftStdlib 5.5, *) extension ThrowingTaskGroup: AsyncSequence { public typealias AsyncIterator = Iterator public typealias Element = ChildTaskResult public func makeAsyncIterator() -> Iterator { return Iterator(group: self) } /// Allows iterating over results of tasks added to the group. /// /// The order of elements returned by this iterator is the same as manually /// invoking the `group.next()` function in a loop, meaning that results /// are returned in *completion order*. /// /// This iterator terminates after all tasks have completed successfully, or /// after any task completes by throwing an error. If a task completes by /// throwing an error, no further task results are returned. /// /// - SeeAlso: `ThrowingTaskGroup.next()` @available(SwiftStdlib 5.5, *) public struct Iterator: AsyncIteratorProtocol { public typealias Element = ChildTaskResult @usableFromInline var group: ThrowingTaskGroup<ChildTaskResult, Failure> @usableFromInline var finished: Bool = false // no public constructors init(group: ThrowingTaskGroup<ChildTaskResult, Failure>) { self.group = group } /// - SeeAlso: `ThrowingTaskGroup.next()` for a detailed discussion its semantics. public mutating func next() async throws -> Element? { guard !finished else { return nil } do { guard let element = try await group.next() else { finished = true return nil } return element } catch { finished = true throw error } } public mutating func cancel() { finished = true group.cancelAll() } } } /// ==== ----------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) @_silgen_name("swift_taskGroup_destroy") func _taskGroupDestroy(group: __owned Builtin.RawPointer) @available(SwiftStdlib 5.5, *) @_silgen_name("swift_taskGroup_addPending") @usableFromInline func _taskGroupAddPendingTask( group: Builtin.RawPointer, unconditionally: Bool ) -> Bool @available(SwiftStdlib 5.5, *) @_silgen_name("swift_taskGroup_cancelAll") func _taskGroupCancelAll(group: Builtin.RawPointer) /// Checks ONLY if the group was specifically cancelled. /// The task itself being cancelled must be checked separately. @available(SwiftStdlib 5.5, *) @_silgen_name("swift_taskGroup_isCancelled") func _taskGroupIsCancelled(group: Builtin.RawPointer) -> Bool @available(SwiftStdlib 5.5, *) @_silgen_name("swift_taskGroup_wait_next_throwing") func _taskGroupWaitNext<T>(group: Builtin.RawPointer) async throws -> T? @available(SwiftStdlib 5.5, *) @_silgen_name("swift_task_hasTaskGroupStatusRecord") func _taskHasTaskGroupStatusRecord() -> Bool @available(SwiftStdlib 5.5, *) enum PollStatus: Int { case empty = 0 case waiting = 1 case success = 2 case error = 3 } @available(SwiftStdlib 5.5, *) @_silgen_name("swift_taskGroup_isEmpty") func _taskGroupIsEmpty( _ group: Builtin.RawPointer ) -> Bool
apache-2.0
93913a8542af14e174e6c7f58780cf8f
34.919598
106
0.678896
4.496304
false
false
false
false
mipstian/catch
Sources/App/Defaults.swift
1
8761
import Foundation import os private extension Int { /// Maximum number of episodes per feed to keep in the download history. /// /// - SeeAlso: `Defaults.downloadHistory` /// - Note: this should be always higher than the number of episodes in a feed, /// otherwise we'd end up re-downloading episodes over and over. static let historyLimit = 200 } /// Singleton. Wrapper around UserDefaults.standard that provides a nice interface to the app's preferences /// and download history data. final class Defaults: NSObject { static let shared = Defaults() /// Posted whenever any default changes static let changedNotification = NSNotification.Name("Defaults.changedNotification") /// Posted whenever `downloadHistory` changes static let downloadHistoryChangedNotification = NSNotification.Name("Defaults.downloadHistoryChangedNotification") private struct Keys { static let feeds = "feeds" static let onlyUpdateBetween = "onlyUpdateBetween" static let updateFrom = "updateFrom" static let updateTo = "updateTo" static let torrentsSavePath = "savePath" static let shouldOrganizeTorrents = "organizeTorrents" static let shouldOpenTorrentsAutomatically = "openAutomatically" static let history = "history" static let shouldRunHeadless = "headless" static let preventSystemSleep = "preventSystemSleep" static let downloadScriptPath = "downloadScriptPath" static let isDownloadScriptEnabled = "downloadScriptEnabled" } var feeds: [Feed] { get { let rawFeeds = UserDefaults.standard.array(forKey: Keys.feeds) as! [[AnyHashable:Any]] return rawFeeds.compactMap { return Feed(dictionary: $0) } } set { UserDefaults.standard.set(newValue.removingDuplicates().map { $0.dictionaryRepresentation }, forKey: Keys.feeds) } } var areTimeRestrictionsEnabled: Bool { return UserDefaults.standard.bool(forKey: Keys.onlyUpdateBetween) } var fromDateForTimeRestrictions: Date { return UserDefaults.standard.object(forKey: Keys.updateFrom) as! Date } var toDateForTimeRestrictions: Date { return UserDefaults.standard.object(forKey: Keys.updateTo) as! Date } var shouldOrganizeTorrentsByShow: Bool { return UserDefaults.standard.bool(forKey: Keys.shouldOrganizeTorrents) } var shouldOpenTorrentsAutomatically: Bool { return UserDefaults.standard.bool(forKey: Keys.shouldOpenTorrentsAutomatically) } var torrentsSavePath: URL? { guard let rawValue = UserDefaults.standard.string(forKey: Keys.torrentsSavePath) else { return nil } let expanded = NSString(string: rawValue).expandingTildeInPath return URL(fileURLWithPath: expanded).standardizedFileURL } var downloadScriptPath: URL? { get { guard let rawValue = UserDefaults.standard.string(forKey: Keys.downloadScriptPath) else { return nil } let expanded = NSString(string: rawValue).expandingTildeInPath return URL(fileURLWithPath: expanded).standardizedFileURL } set { let rawValue = newValue?.absoluteString UserDefaults.standard.set(rawValue, forKey: Keys.downloadScriptPath) } } var isDownloadScriptEnabled: Bool { return UserDefaults.standard.bool(forKey: Keys.isDownloadScriptEnabled) } /// Recently downloaded episodes. Remembered so they won't be downloaded again /// every time feeds are checked. They are presented in the UI as well. /// Automatically kept sorted chronologically, newest to oldest. /// This is really slow to deserialize from and serialize to defaults, so /// keep it in memory while the app is running. var downloadHistory: [HistoryItem] = [] { didSet { // Only keep one copy of each episode var uniqueItems: [HistoryItem] = [] do { var seenEpisodes: Set<Episode> = [] for newItem in downloadHistory { if !seenEpisodes.contains(newItem.episode) { seenEpisodes.insert(newItem.episode) uniqueItems.append(newItem) } else { os_log("Discarding duplicate history item: %{public}@", log: .main, type: .info, "\(newItem)") } } } // Only keep the most recent items let truncatedCount = min(uniqueItems.count, .historyLimit * feeds.count) let truncatedHistory = uniqueItems.sorted().reversed().prefix(upTo: truncatedCount) downloadHistory = Array(truncatedHistory) NotificationCenter.default.post( name: Defaults.downloadHistoryChangedNotification, object: self ) } } var shouldRunHeadless: Bool { return UserDefaults.standard.bool(forKey: Keys.shouldRunHeadless) } var shouldPreventSystemSleep: Bool { return UserDefaults.standard.bool(forKey: Keys.preventSystemSleep) } var isConfigurationValid: Bool { return hasValidFeeds } var isTorrentsSavePathValid: Bool { return torrentsSavePath?.isWritableDirectory ?? false } var hasValidFeeds: Bool { return feeds.count > 0 } var hasShowRSSFeeds: Bool { return feeds.contains { $0.url.isShowRSSFeed } } var downloadOptions: DownloadOptions? { guard let torrentsSavePath = torrentsSavePath else { return nil } // Disable downloading any files if the download script is enabled. return DownloadOptions( containerDirectory: torrentsSavePath, shouldOrganizeByShow: shouldOrganizeTorrentsByShow, shouldSaveMagnetLinks: !shouldOpenTorrentsAutomatically && !isDownloadScriptEnabled, shouldSaveTorrentFiles: !isDownloadScriptEnabled ) } func restricts(date: Date) -> Bool { if !areTimeRestrictionsEnabled { return false } return !date.isTimeOfDayBetween( startTimeOfDay: fromDateForTimeRestrictions, endTimeOfDay: toDateForTimeRestrictions ) } func save() { // Only save history to defaults when necessary let serializedHistory = downloadHistory.map { $0.dictionaryRepresentation } UserDefaults.standard.set(serializedHistory, forKey: Keys.history) UserDefaults.standard.synchronize() } private override init() { super.init() // Default values for time restrictions let defaultFromTime = Calendar.current.date(from: DateComponents(hour: 24, minute: 0))! let defaultToTime = Calendar.current.date(from: DateComponents(hour: 8, minute: 0))! // Use user's Downloads directory as a default, fallback on home let defaultDownloadsDirectory = FileManager.default.downloadsDirectory ?? FileManager.default.homeDirectory // Set smart default defaults let defaultDefaults: [String:Any] = [ Keys.feeds: [], Keys.onlyUpdateBetween: false, Keys.updateFrom: defaultFromTime, Keys.updateTo: defaultToTime, Keys.torrentsSavePath: defaultDownloadsDirectory, Keys.shouldOrganizeTorrents: false, Keys.shouldOpenTorrentsAutomatically: true, Keys.history: [], Keys.shouldRunHeadless: false, Keys.preventSystemSleep: true, Keys.isDownloadScriptEnabled: false ] UserDefaults.standard.register(defaults: defaultDefaults) // Migrate from single-feed to multi-feed if let legacyFeedURLString = UserDefaults.standard.string(forKey: "feedURL") { os_log("Migrating feed URLs defaults", log: .main, type: .info) UserDefaults.standard.set(nil, forKey: "feedURL") if let legacyFeedURL = URL(string: legacyFeedURLString) { feeds.append(Feed(name: "ShowRSS", url: legacyFeedURL)) } } // Observe changes for all keys NotificationCenter.default.addObserver( self, selector: #selector(defaultsChanged), name: UserDefaults.didChangeNotification, object: nil ) // Load history from defaults at launch let rawHistory = UserDefaults.standard.array(forKey: Keys.history) as! [[AnyHashable:Any]] downloadHistory = rawHistory.compactMap(HistoryItem.init(defaultsDictionary:)) } @objc private func defaultsChanged(_: Notification) { NotificationCenter.default.post( name: Defaults.changedNotification, object: self ) } deinit { NotificationCenter.default.removeObserver(self) } } private extension HistoryItem { init?(defaultsDictionary: [AnyHashable:Any]) { guard let episode = Episode(dictionary: defaultsDictionary) else { return nil } self.episode = episode self.downloadDate = defaultsDictionary["date"] as? Date } } extension Collection where Element: Hashable { func removingDuplicates() -> [Element] { var set = Set<Element>() return compactMap { set.insert($0).inserted ? $0 : nil } } }
mit
9244892fba5d599fcfd22a6e30a826c6
32.060377
118
0.704942
4.574935
false
false
false
false
maranathApp/GojiiFramework
GojiiFrameWork/UIViewExtensions.swift
1
34687
// // CGFloatExtensions.swift // GojiiFrameWork // // Created by Stency Mboumba on 01/06/2017. // Copyright © 2017 Stency Mboumba. All rights reserved. // import UIKit import QuartzCore // MARK: - Extensions UIView BSFramework public extension UIView { /* --------------------------------------------------------------------------- */ // MARK: - Initilizers ( init ) /* --------------------------------------------------------------------------- */ /** Initializes UIView - parameter x: CGFloat - parameter y: CGFloat - parameter width: CGFloat - parameter height: CGFloat - returns: UIView */ public convenience init( x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { self.init (frame: CGRect (x: x, y: y, width: width, height: height)) } /** Initializes UIView with superview - parameter superView: UIView - returns: UIView */ public convenience init(superView: UIView) { self.init (frame: CGRect (origin: CGPoint(x:0,y:0), size: superView.size)) } /** Initializes UIView with puts padding around the view - parameter superView: UIView - parameter padding: CGFloat - returns: UIView */ public convenience init(superView: UIView, padding: CGFloat) { self.init(frame: CGRect(x: superView.x + padding, y: superView.y + padding, width: superView.width - padding*2, height: superView.height - padding*2)) } /* --------------------------------------------------------------------------- */ // MARK: - Size /* --------------------------------------------------------------------------- */ /// With size public var width:CGFloat { get { return self.frame.size.width } set { self.frame.size.width = newValue } } /// Height size public var height:CGFloat { get { return self.frame.size.height } set { self.frame.size.height = newValue } } /// Size public var size: CGSize { get { return self.frame.size } set { self.frame = CGRect (origin: self.frame.origin, size: newValue) } } /* --------------------------------------------------------------------------- */ // MARK: - Position /* --------------------------------------------------------------------------- */ /// X position public var x:CGFloat { get { return self.frame.origin.x } set { self.frame = CGRect (x: newValue, y: self.y, width: self.width, height: self.height) } } /// Y position public var y:CGFloat { get { return self.frame.origin.y } set { self.frame = CGRect (x: self.x, y: newValue, width: self.width, height: self.height) } } /// Position public var position: CGPoint { get { return self.frame.origin } set (value) { self.frame = CGRect (origin: value, size: self.frame.size) } } /// Center X public var centerX: CGFloat { return self.center.x } /// Center Y public var centerY: CGFloat { return self.center.y } /** Position Left / Droite - returns: CGFloat */ public func leftPosition() -> CGFloat { return self.x } /** Position Right / Gauche - returns: CGFloat */ public func rightPosition() -> CGFloat{ return self.x + self.width } /** Position top - returns: CGFloat */ public func topPosition() -> CGFloat{ return self.y } /** Position bottom - returns: CGFloat */ public func bottomPosition() -> CGFloat{ return self.y + self.height } /* --------------------------------------------------------------------------- */ // MARK: - Anchor Position /* --------------------------------------------------------------------------- */ /** Set Anchor position - parameter anchorPosition: AnchorPosition */ // public func setAnchorPosition (anchorPosition: AnchorPosition) { // self.layer.anchorPoint = anchorPosition.rawValue // } // /* --------------------------------------------------------------------------- */ // MARK: - NSLayoutConstraint /* --------------------------------------------------------------------------- */ /** Bound in side the superView <br><br>Example : <br><br>[ SuperView H/W [ MyView H/W ] ] -> SuperView H/W = MyView H/W<br><br> subview.boundInside(superView)<br><br> - parameter superView: UIView / Size in superView */ public func boundInside(superView: UIView){ self.translatesAutoresizingMaskIntoConstraints = false superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: [], metrics:nil, views:["subview":self])) superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: [], metrics:nil, views:["subview":self])) } /** Animate Constraint with duration <br><br>example use : <br><br>self.nameInputConstraint.constant = 8<br><br>view.animateConstraintWithDuration()<br><br> - parameter duration: NSTimeInterval - parameter delay: NSTimeInterval - parameter options: UIViewAnimationOptions - parameter completion: (Bool) -> ())? */ public func applyAnimateConstraintWithDuration( duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, options: UIViewAnimationOptions = [], completion: ((Bool) -> ())? = nil) { UIView.animate(withDuration: duration, delay:delay, options:options, animations: { [weak self] in self?.layoutIfNeeded() ?? () }, completion: completion) } /* --------------------------------------------------------------------------- */ // MARK: - Other ( Delete, image ) /* --------------------------------------------------------------------------- */ /** Remove allSubView */ public func removeAllSubViews() { for subView : AnyObject in self.subviews { subView.removeFromSuperview() } } /** UIView to Image - returns: UIImage */ func toImage () -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0) drawHierarchy(in: bounds, afterScreenUpdates: false) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } /* --------------------------------------------------------------------------- */ // MARK: - NIB /* --------------------------------------------------------------------------- */ /** Get view from nib, the first - parameter nameFile: String - returns: UIView */ public class func getViewFromNib(nameFile:String) -> UIView { return UINib(nibName: nameFile, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView } /** Get views collection from nib - parameter nameFile: String - returns: [UIView] */ public class func getViewCollectionFromNib(nameFile:String) -> [UIView] { return UINib(nibName: nameFile, bundle: nil).instantiate(withOwner: nil, options: nil) as! [UIView] } /* --------------------------------------------------------------------------- */ // MARK: - UIView → Constraint /* --------------------------------------------------------------------------- */ /** Add Constrain to UIView - parameter attribute: NSLayoutAttribute - parameter relation: NSLayoutRelation - parameter otherView: UIView - parameter otherAttribute: NSLayoutAttribute - parameter multiplier: CGFloat - parameter constant: CGFloat - parameter priority: UILayoutPriority - parameter identifier: String? - returns: NSLayoutConstraint */ public func constrain( attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to otherView: UIView, _ otherAttribute: NSLayoutAttribute, times multiplier: CGFloat = 1, plus constant: CGFloat = 0, atPriority priority: UILayoutPriority = UILayoutPriorityRequired, identifier: String? = nil) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: attribute, relatedBy: relation, toItem: otherView, attribute: otherAttribute, multiplier: multiplier, constant: constant) constraint.priority = priority constraint.identifier = identifier constraint.isActive = true return constraint } /** Add Constrain to UIView - parameter attribute: NSLayoutAttribute - parameter relation: NSLayoutRelation - parameter constant: CGFloat - parameter priority: UILayoutPriority - parameter identifier: String? - returns: NSLayoutConstraint */ public func constrain( attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to constant: CGFloat, atPriority priority: UILayoutPriority = UILayoutPriorityRequired, identifier: String? = nil) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: attribute, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: constant) constraint.priority = priority constraint.identifier = identifier constraint.isActive = true return constraint } /* --------------------------------------------------------------------------- */ // MARK: - UIView → Gesture /* --------------------------------------------------------------------------- */ /** Attaches a gesture recognizer **Tap** to the view. - parameter tapNumber: Int <br> **Number of Tap** - parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.** - parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.** */ public func addTapGesture(tapNumber: Int, target: AnyObject, action: Selector) { let tap = UITapGestureRecognizer(target: target, action: action) tap.numberOfTapsRequired = tapNumber addGestureRecognizer(tap) isUserInteractionEnabled = true } /** Attaches a gesture recognizer **Swipe** to the view. - parameter direction: UISwipeGestureRecognizerDirection <br> **.Right .Left .Up .Down** - parameter numberOfTouches: Int <br> **Number of touches for the swipe** - parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.** - parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.** */ public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int, target: AnyObject, action: Selector) { let swipe = UISwipeGestureRecognizer(target: target, action: action) swipe.direction = direction swipe.numberOfTouchesRequired = numberOfTouches addGestureRecognizer(swipe) isUserInteractionEnabled = true } /** Attaches a gesture recognizer **Pan** to the view. - parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.** - parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.** */ public func addPanGesture(target: AnyObject, action: Selector) { let pan = UIPanGestureRecognizer(target: target, action: action) addGestureRecognizer(pan) isUserInteractionEnabled = true } /** Attaches a gesture recognizer **Pinch** to the view. - parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.** - parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.** */ public func addPinchGesture(target: AnyObject, action: Selector) { let pinch = UIPinchGestureRecognizer(target: target, action: action) addGestureRecognizer(pinch) isUserInteractionEnabled = true } /** Attaches a gesture recognizer **Long Press** to the view. - parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.** - parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.** */ public func addLongPressGesture(target: AnyObject, action: Selector) { let longPress = UILongPressGestureRecognizer(target: target, action: action) addGestureRecognizer(longPress) isUserInteractionEnabled = true } /* --------------------------------------------------------------------------- */ // MARK: - UIView → Transform /* --------------------------------------------------------------------------- */ /** Set Rotation **X** - parameter x: CGFloat */ public func setRotationX(x: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, x.toDegreesToRadians, 1.0, 0.0, 0.0) self.layer.transform = transform } /** Set Rotation **Y** - parameter y: CGFloat */ public func setRotationY(y: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, y.toDegreesToRadians, 0.0, 1.0, 0.0) self.layer.transform = transform } /** Set Rotation **Z** - parameter z: CGFloat */ public func setRotationZ(z: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, y.toDegreesToRadians, 0.0, 0.0, 1.0) self.layer.transform = transform } /** Set rotation **X, Y, Z** - parameter x: CGFloat - parameter y: CGFloat - parameter z: CGFloat */ public func setRotation(x: CGFloat, y: CGFloat, z: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, x.toDegreesToRadians, 1.0, 0.0, 0.0) transform = CATransform3DRotate(transform, y.toDegreesToRadians, 0.0, 1.0, 0.0) transform = CATransform3DRotate(transform, z.toDegreesToRadians, 0.0, 0.0, 1.0) self.layer.transform = transform } /** Set Scale - parameter x: CGFloat - parameter y: CGFloat */ public func setScale(x: CGFloat, y: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DScale(transform, x, y, 1) self.layer.transform = transform } /* --------------------------------------------------------------------------- */ // MARK: - UIView → Layer /* --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- */ // MARK: - UIView → Layer / Border, Corner /* --------------------------------------------------------------------------- */ /** Set Rounder - parameter radius: CGFloat */ public func addRounder(radius:CGFloat) { self.layer.cornerRadius = radius self.clipsToBounds = true } /** Set Round */ public func addRound() { self.layer.cornerRadius = self.width / 2 self.clipsToBounds = true } /** Round cornerd on UIView by enum UIRectCorner with radius - parameter corners: UIRectCorner / .TopLeft, .TopRight, .BottomLeft, .BottomRight, .AllCorners - parameter radius: CGFloat */ public func addRoundCorners(corners:UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask } /** Add border - parameter width: CGFloat - parameter color: UIColor */ public func addBorder(width: CGFloat, color: UIColor) { self.layer.borderWidth = width self.layer.borderColor = color.cgColor self.layer.masksToBounds = true } /** Add Border Top - parameter size: CGFloat - parameter color: UIColor */ public func addBorderTop(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color) } /** Add Border Bottom - parameter size: CGFloat - parameter color: UIColor */ public func addBorderBottom(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color) } /** Add Border Left - parameter size: CGFloat - parameter color: UIColor */ public func addBorderLeft(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color) } /** Add Border Right - parameter size: CGFloat - parameter color: UIColor */ public func addBorderRight(size: CGFloat, color: UIColor) { addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color) } /** add border utility private - parameter x: CGFloat - parameter y: CGFloat - parameter width: CGFloat - parameter height: CGFloat - parameter color: UIColor */ private func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) { let border = CALayer() border.backgroundColor = color.cgColor border.frame = CGRect(x: x, y: y, width: width, height: height) layer.addSublayer(border) } /* --------------------------------------------------------------------------- */ // MARK: - UIView → Layer / Draw /* --------------------------------------------------------------------------- */ /** Draw Circle - parameter fillColor: UIColor - parameter strokeColor: UIColor - parameter strokeWidth: CGFloat */ public func drawCircle(fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.width, height: self.width), cornerRadius: self.width/2) let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.fillColor = fillColor.cgColor shapeLayer.strokeColor = strokeColor.cgColor shapeLayer.lineWidth = strokeWidth self.layer.addSublayer(shapeLayer) } /** Draw Stroke - parameter width: CGFloat - parameter color: UIColor */ public func drawStroke(width: CGFloat, color: UIColor) { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.width, height: self.width), cornerRadius: self.width/2) let shapeLayer = CAShapeLayer () shapeLayer.path = path.cgPath shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = color.cgColor shapeLayer.lineWidth = width self.layer.addSublayer(shapeLayer) } /* --------------------------------------------------------------------------- */ // MARK: - UIView → Layer / Shadow /* --------------------------------------------------------------------------- */ /** Apply Shadow - parameter offset: CGSize - parameter radius: CGFloat - parameter color: UIColor - parameter opacity: Float - parameter cornerRadius: CGFloat? */ public func addShadow(offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) { self.layer.shadowOffset = offset self.layer.shadowRadius = radius self.layer.shadowOpacity = opacity self.layer.shadowColor = color.cgColor if let r = cornerRadius { self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).cgPath } } /** Plain Shadow - parameter shadowColor: UIColor ( default = UIColor.blackColor() ) - parameter shadowOpacity: Float ( default = 0.4 ) - parameter shadowRadius: CGFloat ( default = 0.5 ) - parameter shadowOffset: CGSize ( default = CGSize(width: 0, height: 10) ) */ public func addPlainShadow( shadowColor:UIColor = UIColor.black, shadowOpacity:Float = 0.4, shadowRadius:CGFloat = 5, shadowOffset:CGSize = CGSize(width: 0, height: 10)) { self.layer.shadowColor = shadowColor.cgColor self.layer.shadowOffset = shadowOffset self.layer.shadowOpacity = shadowOpacity self.layer.shadowRadius = shadowRadius } /** Curved Shadow - parameter shadowOpacity: Float ( default = 0.3 ) - parameter shadowOffset: CGSize ( default = CGSize(width: 0, height: -3) ) - parameter shadowColor: UIColor ( default = UIColor.blackColor() ) - parameter depth: CGFloat ( default = 11.0 ) - parameter lessDepth: CGFloat ( default = 0.8 ) - parameter curviness: CGFloat ( default = 5 ) - parameter radius: CGFloat ( default = 1 ) */ public func addCurvedShadow( shadowOpacity:Float = 0.3, shadowOffset:CGSize = CGSize(width: 0, height: -3), shadowColor:UIColor = UIColor.black, depth:CGFloat = 11.00 , lessDepth:CGFloat = 0.8, curviness:CGFloat = 5, radius:CGFloat = 1 ) { let path = UIBezierPath() // top left path.move(to: CGPoint(x: radius, y: self.height)) // top right path.addLine(to: CGPoint(x: self.width - 2 * radius, y: self.height)) // bottom right + a little extra path.addLine(to: CGPoint(x: self.width - 2 * radius, y: self.height + depth)) // path to bottom left via curve path.addCurve( to: CGPoint(x: radius, y: self.height + depth), controlPoint1: CGPoint( x: self.width - curviness, y: self.height + (lessDepth * depth) - curviness), controlPoint2: CGPoint( x: curviness, y: self.height + (lessDepth * depth) - curviness)) self.layer.shadowPath = path.cgPath self.layer.shadowColor = shadowColor.cgColor self.layer.shadowOpacity = shadowOpacity self.layer.shadowRadius = radius self.layer.shadowOffset = shadowOffset } public func addHoverShadow() { let path = UIBezierPath(roundedRect: CGRect(x: 5, y: self.height + 5, width: self.width - 10, height: 15), cornerRadius: 10) self.layer.shadowPath = path.cgPath self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.2 self.layer.shadowRadius = 5 self.layer.shadowOffset = CGSize(width: 0, height: 0) } public func addFlatShadow(){ self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width:0.0, height:2.0) self.layer.masksToBounds = false self.layer.shadowRadius = 1.0 self.layer.shadowOpacity = 0.5 } /* --------------------------------------------------------------------------- */ // MARK: - Animate /* --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- */ // MARK: - Animate / Stop Start /* --------------------------------------------------------------------------- */ /** Stop current animation */ public func stopAnimation() { CATransaction.begin() self.layer.removeAllAnimations() CATransaction.commit() CATransaction.flush() } /** Is view is being animates - returns: Bool */ public func isBeingAnimated() -> Bool { return (self.layer.animationKeys()?.count)! > 0 } /* --------------------------------------------------------------------------- */ // MARK: - Animate / FadIn Out /* --------------------------------------------------------------------------- */ /** Fade In - parameter duration: NSTimeInterval ( default = 1.0 ) - parameter delay: NSTimeInterval ( default = 0 ) - parameter alpha: CGFloat ( default = 1.0 ) - parameter completionEnd: (() -> ())? When animation is finished */ public func applyFadeIn( duration: TimeInterval = 1.0, delay: TimeInterval = 0.0, toAlpha: CGFloat = 1, completionEnd: ((Bool) -> ())? = nil) { UIView.animate(withDuration: duration, delay: delay, options: [], animations: { self.alpha = toAlpha }, completion: completionEnd) /* let animation = CABasicAnimation(keyPath:"opacity") animation.beginTime = CACurrentMediaTime() + delay; animation.duration = duration animation.fromValue = 0 animation.toValue = alpha animation.fillMode = kCAFillModeBoth CATransaction.setCompletionBlock(completionEnd) self.layer.addAnimation(animation, forKey:"animateOpacity")*/ } /** Fade Out - parameter duration: NSTimeInterval ( default = 1.0 ) - parameter delay: NSTimeInterval ( default = 0.0 ) - parameter alpha: CGFloat ( default = 0 ) - parameter completionEnd: (() -> ())? When animation is finished */ public func applyFadeOut( duration: TimeInterval = 1.0, delay: TimeInterval = 0.0, toAlpha: CGFloat = 0, completionEnd: ((Bool) -> ())? = nil) { UIView.animate(withDuration: duration, delay: delay, options: [], animations: { self.alpha = toAlpha }, completion: completionEnd) /* let animation = CABasicAnimation(keyPath:"opacity") animation.beginTime = CACurrentMediaTime() + delay; animation.duration = duration animation.fromValue = 1 animation.toValue = alpha animation.fillMode = kCAFillModeBoth CATransaction.setCompletionBlock(completionEnd) self.layer.addAnimation(animation, forKey:"animateOpacity")*/ } /* --------------------------------------------------------------------------- */ // MARK: - Animate / Shake /* --------------------------------------------------------------------------- */ /** Shake Horizontally - parameter duration: duration ( default = 0.5 ) - parameter moveValues: moveValues ( default = [-12, 12, -8, 8, -4, 4, 0] ) - parameter completionEnd: (() -> ())? When animation is finished */ // public func applyShakeHorizontally( // duration:CFTimeInterval = 0.5, // moveValues:[Float] = [-12, 12, -8, 8, -4, 4, 0], // completionEnd: dispatch_block_t? = nil) { // // let animation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.translation.x") // // animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) // animation.duration = duration // animation.values = moveValues // // CATransaction.setCompletionBlock(completionEnd) // // self.layer.add(animation, forKey: "shake") // } /** Shake Vertically - parameter duration: duration ( default = 0.5 ) - parameter moveValues: moveValues ( default = [-12, 12, -8, 8, -4, 4, 0] ) - parameter completionEnd: (() -> ())? When animation is finished */ public func applyShakeVertically( duration:CFTimeInterval = 0.5, moveValues:[Float] = [(-12), (12), (-8), (8), (-4), (4), (0) ], completionEnd: @escaping (() -> ())) { let animation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.values = moveValues CATransaction.setCompletionBlock(completionEnd) self.layer.add(animation, forKey: "shake") } /* --------------------------------------------------------------------------- */ // MARK: - Animate / Rotate /* --------------------------------------------------------------------------- */ /** Set Animation Rotation on View - parameter angle: CGFloat ( example 360 = 360 degrees) - parameter duration: NSTimeInterval - parameter direction: UIViewContentMode ( .Left, .Right ) - parameter repeatCount: Float - parameter autoReverse: Bool - parameter completionEnd: (() -> ())? When animation is finished */ public func applyRotateToAngle( angle:CGFloat, duration:TimeInterval, direction:UIViewContentMode, repeatCount:Float = 0, autoReverse:Bool = false, completionEnd: (() -> Void)? = nil ) { let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnimation.fromValue = 0.0 rotationAnimation.toValue = (direction == UIViewContentMode.right ? angle.toDegreesToRadians : -angle.toDegreesToRadians) rotationAnimation.duration = duration rotationAnimation.autoreverses = autoReverse rotationAnimation.repeatCount = repeatCount rotationAnimation.isRemovedOnCompletion = false rotationAnimation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionLinear) CATransaction.setCompletionBlock(completionEnd) self.layer.add(rotationAnimation,forKey:"transform.rotation.z") } /** Set animation Pulse on View - parameter toScale: CGFloat - parameter duration: NSTimeInterval - parameter repeatAnimate: Bool - parameter completionEnd: (() -> ())? When animation is finished */ public func applyPulseToSize( duration:TimeInterval, toScale:CGFloat, repeatAnimate:Bool, completionEnd: (() -> Void)? = nil ) { let pulseAnimate = CABasicAnimation(keyPath: "transform.scale") pulseAnimate.duration = duration pulseAnimate.toValue = toScale pulseAnimate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pulseAnimate.autoreverses = true pulseAnimate.repeatCount = repeatAnimate ? Float.infinity : 0 CATransaction.setCompletionBlock(completionEnd) self.layer.add(pulseAnimate, forKey:"pulse") } @available(iOS 7,*) /** Motion Effects - parameter minimumRelativeValueX: Min Relative Value X ( default = -10.00 ) - parameter maximumRelativeValueX: Max Relative Value X ( default = 10.00 ) - parameter minimumRelativeValueY: Min Relative Value Y ( default = -10.00 ) - parameter maximumRelativeValueY: Max Relative Value Y ( default = 10.00 ) */ public func applyMotionEffects( minimumRelativeValueX:Float = -10.00, maximumRelativeValueX:Float = 10.00, minimumRelativeValueY:Float = -10.00, maximumRelativeValueY:Float = 10.00 ) { let horizontalEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type:.tiltAlongHorizontalAxis) horizontalEffect.minimumRelativeValue = minimumRelativeValueX horizontalEffect.maximumRelativeValue = maximumRelativeValueX let verticalEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) verticalEffect.minimumRelativeValue = minimumRelativeValueY verticalEffect.maximumRelativeValue = maximumRelativeValueY let motionEffectGroup = UIMotionEffectGroup() motionEffectGroup.motionEffects = [horizontalEffect, verticalEffect] self.addMotionEffect(motionEffectGroup) } }
mit
e35dd4c5fdb6097f3bf3f4d775157cca
35.116667
158
0.532101
5.34402
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Navigator.swift
1
5793
// // Wire // Copyright (C) 2021 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit // MARK: - NavigatorProtocol public typealias NavigateBackClosure = () -> Void public protocol NavigatorProtocol { var navigationController: UINavigationController { get } func push(_ viewController: UIViewController, animated: Bool, onNavigateBack: NavigateBackClosure?) func pop(_ animated: Bool) func present(_ viewController: UIViewController, animated: Bool, onComplete: (() -> Void)?) func setRoot(_ viewController: UIViewController, animated: Bool) func dismiss(_ viewController: UIViewController, animated: Bool) func addNavigateBack(closure: @escaping NavigateBackClosure, for viewController: UIViewController) } public extension NavigatorProtocol { func push(_ viewController: UIViewController) { push(viewController, animated: true, onNavigateBack: nil) } func push(_ viewController: UIViewController, animated: Bool) { push(viewController, animated: animated, onNavigateBack: nil) } func present(_ viewController: UIViewController) { present(viewController, animated: true, onComplete: nil) } func setRoot(_ viewController: UIViewController) { setRoot(viewController, animated: true) } } public class Navigator: NSObject, NavigatorProtocol { public let navigationController: UINavigationController private var closures: [UIViewController: NavigateBackClosure] = [:] public init(_ navigationController: UINavigationController) { self.navigationController = navigationController super.init() navigationController.delegate = self } public func push(_ viewController: UIViewController, animated: Bool, onNavigateBack: NavigateBackClosure? = nil) { if let closure = onNavigateBack { addNavigateBack(closure: closure, for: viewController) } navigationController.pushViewController(viewController, animated: animated) } public func pop(_ animated: Bool) { let vc = navigationController.popViewController(animated: animated) vc.flatMap { runCompletion(for: $0) } } public func dismiss(_ viewController: UIViewController, animated: Bool) { viewController.dismiss(animated: animated, completion: { [weak self] in self?.runCompletion(for: viewController) }) } public func present(_ viewController: UIViewController, animated: Bool, onComplete: (() -> Void)?) { navigationController.present(viewController, animated: animated, completion: onComplete) } public func setRoot(_ viewController: UIViewController, animated: Bool) { closures.forEach { $0.value() } closures = [:] navigationController.viewControllers = [viewController] } public func addNavigateBack(closure: @escaping NavigateBackClosure, for viewController: UIViewController) { print("adding closure for \(viewController)") closures.updateValue(closure, forKey: viewController) } private func runCompletion(for viewController: UIViewController) { guard let closure = closures.removeValue(forKey: viewController) else { return } print("adding closure for \(viewController)") closure() } } extension Navigator: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { guard let previousController = navigationController.transitionCoordinator?.viewController(forKey: .from), !navigationController.viewControllers.contains(previousController) else { return } runCompletion(for: previousController) } } // MARK: - NoBackTitleNavigationController public final class NoBackTitleNavigationController: UINavigationController { public override var viewControllers: [UIViewController] { didSet { viewControllers.forEach(hideBackButton(for:)) } } public override func pushViewController(_ viewController: UIViewController, animated: Bool) { super.pushViewController(viewController, animated: animated) hideBackButton(for: viewController) } public override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) { super.setViewControllers(viewControllers, animated: animated) viewControllers.forEach(hideBackButton(for:)) } private func hideBackButton(for viewController: UIViewController) { viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } }
gpl-3.0
caa60a7e78284eb4ea43ab8eed07fbdd
37.364238
111
0.665113
5.673849
false
false
false
false
solinor/paymenthighway-ios-framework
PaymentHighway/UI/ExpiryDatePickerView.swift
1
2443
// // DateExpiryPicker.swift // PaymentHighway // // Created by Stefano Pironato on 25/09/2018. // Copyright © 2018 Payment Highway Oy. All rights reserved. // import UIKit private let numberOfYears = 15 class ExpiryDatePickerView: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource { private var months: [Int] = [] private var years: [Int] = [] private var currentMonth = Calendar.current.component(.month, from: Date()) var onDateSelected: ((_ month: Int, _ year: Int) -> Void)? override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override func didMoveToSuperview() { super.didMoveToSuperview() notify() } private func initialize() { months = (1...12).map { $0 } let currentYear = Calendar.current.component(.year, from: Date()) years = (0..<numberOfYears).map { $0+currentYear } delegate = self dataSource = self selectCurrentMonth() } // MARK: UIPickerViewDataSource func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return months.count case 1: return years.count default: fatalError() } } // MARK: UIPickerViewDelegate func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch component { case 0: return "\(months[row])" case 1: return "\(years[row])" default: fatalError() } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if selectedRow(inComponent: 1) == 0 && selectedRow(inComponent: 0)+1 < currentMonth { selectCurrentMonth() } notify() } private func selectCurrentMonth() { selectRow(currentMonth - 1, inComponent: 0, animated: false) selectRow(0, inComponent: 1, animated: false) } private func notify() { let month = selectedRow(inComponent: 0)+1 let year = years[selectedRow(inComponent: 1)] onDateSelected?(month, year) } }
mit
23bc2530d1a2abc9c14b574b4e70b334
27.729412
111
0.609746
4.696154
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV1/Models/CredentialDetails.swift
1
15706
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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 /** Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. */ public struct CredentialDetails: Codable, Equatable { /** The authentication method for this credentials definition. The **credential_type** specified must be supported by the **source_type**. The following combinations are possible: - `"source_type": "box"` - valid `credential_type`s: `oauth2` - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. */ public enum CredentialType: String { case oauth2 = "oauth2" case saml = "saml" case usernamePassword = "username_password" case noauth = "noauth" case basic = "basic" case ntlmV1 = "ntlm_v1" case aws4Hmac = "aws4_hmac" } /** The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. */ public enum SourceVersion: String { case online = "online" } /** The authentication method for this credentials definition. The **credential_type** specified must be supported by the **source_type**. The following combinations are possible: - `"source_type": "box"` - valid `credential_type`s: `oauth2` - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. */ public var credentialType: String? /** The **client_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. */ public var clientID: String? /** The **enterprise_id** of the Box site that these credentials connect to. Only valid, and required, with a **source_type** of `box`. */ public var enterpriseID: String? /** The **url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `username_password`, `noauth`, and `basic`. */ public var url: String? /** The **username** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`. */ public var username: String? /** The **organization_url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`. */ public var organizationURL: String? /** The **site_collection.path** of the source that these credentials connect to. Only valid, and required, with a **source_type** of `sharepoint`. */ public var siteCollectionPath: String? /** The **client_secret** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. */ public var clientSecret: String? /** The **public_key_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. */ public var publicKeyID: String? /** The **private_key** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. */ public var privateKey: String? /** The **passphrase** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. */ public var passphrase: String? /** The **password** of the source that these credentials connect to. Only valid, and required, with **credential_type**s of `saml`, `username_password`, `basic`, or `ntlm_v1`. **Note:** When used with a **source_type** of `salesforce`, the password consists of the Salesforce password and a valid Salesforce security token concatenated. This value is never returned and is only used when creating or modifying **credentials**. */ public var password: String? /** The ID of the **gateway** to be connected through (when connecting to intranet sites). Only valid with a **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created using the `/v1/environments/{environment_id}/gateways` methods. */ public var gatewayID: String? /** The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. */ public var sourceVersion: String? /** SharePoint OnPrem WebApplication URL. Only valid, and required, with a **source_version** of `2016`. If a port is not supplied, the default to port `80` for http and port `443` for https connections are used. */ public var webApplicationURL: String? /** The domain used to log in to your OnPrem SharePoint account. Only valid, and required, with a **source_version** of `2016`. */ public var domain: String? /** The endpoint associated with the cloud object store that your are connecting to. Only valid, and required, with a **credential_type** of `aws4_hmac`. */ public var endpoint: String? /** The access key ID associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). */ public var accessKeyID: String? /** The secret access key associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). */ public var secretAccessKey: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case credentialType = "credential_type" case clientID = "client_id" case enterpriseID = "enterprise_id" case url = "url" case username = "username" case organizationURL = "organization_url" case siteCollectionPath = "site_collection.path" case clientSecret = "client_secret" case publicKeyID = "public_key_id" case privateKey = "private_key" case passphrase = "passphrase" case password = "password" case gatewayID = "gateway_id" case sourceVersion = "source_version" case webApplicationURL = "web_application_url" case domain = "domain" case endpoint = "endpoint" case accessKeyID = "access_key_id" case secretAccessKey = "secret_access_key" } /** Initialize a `CredentialDetails` with member variables. - parameter credentialType: The authentication method for this credentials definition. The **credential_type** specified must be supported by the **source_type**. The following combinations are possible: - `"source_type": "box"` - valid `credential_type`s: `oauth2` - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. - parameter clientID: The **client_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. - parameter enterpriseID: The **enterprise_id** of the Box site that these credentials connect to. Only valid, and required, with a **source_type** of `box`. - parameter url: The **url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `username_password`, `noauth`, and `basic`. - parameter username: The **username** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`. - parameter organizationURL: The **organization_url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`. - parameter siteCollectionPath: The **site_collection.path** of the source that these credentials connect to. Only valid, and required, with a **source_type** of `sharepoint`. - parameter clientSecret: The **client_secret** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - parameter publicKeyID: The **public_key_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - parameter privateKey: The **private_key** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - parameter passphrase: The **passphrase** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - parameter password: The **password** of the source that these credentials connect to. Only valid, and required, with **credential_type**s of `saml`, `username_password`, `basic`, or `ntlm_v1`. **Note:** When used with a **source_type** of `salesforce`, the password consists of the Salesforce password and a valid Salesforce security token concatenated. This value is never returned and is only used when creating or modifying **credentials**. - parameter gatewayID: The ID of the **gateway** to be connected through (when connecting to intranet sites). Only valid with a **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created using the `/v1/environments/{environment_id}/gateways` methods. - parameter sourceVersion: The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. - parameter webApplicationURL: SharePoint OnPrem WebApplication URL. Only valid, and required, with a **source_version** of `2016`. If a port is not supplied, the default to port `80` for http and port `443` for https connections are used. - parameter domain: The domain used to log in to your OnPrem SharePoint account. Only valid, and required, with a **source_version** of `2016`. - parameter endpoint: The endpoint associated with the cloud object store that your are connecting to. Only valid, and required, with a **credential_type** of `aws4_hmac`. - parameter accessKeyID: The access key ID associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - parameter secretAccessKey: The secret access key associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - returns: An initialized `CredentialDetails`. */ public init( credentialType: String? = nil, clientID: String? = nil, enterpriseID: String? = nil, url: String? = nil, username: String? = nil, organizationURL: String? = nil, siteCollectionPath: String? = nil, clientSecret: String? = nil, publicKeyID: String? = nil, privateKey: String? = nil, passphrase: String? = nil, password: String? = nil, gatewayID: String? = nil, sourceVersion: String? = nil, webApplicationURL: String? = nil, domain: String? = nil, endpoint: String? = nil, accessKeyID: String? = nil, secretAccessKey: String? = nil ) { self.credentialType = credentialType self.clientID = clientID self.enterpriseID = enterpriseID self.url = url self.username = username self.organizationURL = organizationURL self.siteCollectionPath = siteCollectionPath self.clientSecret = clientSecret self.publicKeyID = publicKeyID self.privateKey = privateKey self.passphrase = passphrase self.password = password self.gatewayID = gatewayID self.sourceVersion = sourceVersion self.webApplicationURL = webApplicationURL self.domain = domain self.endpoint = endpoint self.accessKeyID = accessKeyID self.secretAccessKey = secretAccessKey } }
apache-2.0
3c9ec5297355d6e9af960e29c8e63bfb
49.339744
145
0.670444
4.270256
false
false
false
false
TinyCrayon/TinyCrayon-iOS-SDK
TCMask/TCMaskView.swift
1
12019
// // TCMaskView.swift // TinyCrayon // // Created by Xin Zeng on 2/18/17. // // import UIKit /** The module that displays a UIViewController for image masking. A minimum implementation to present a TCMaskview within a UIViewController class is: ``` // Create TCMaskView, specifying the image for masking. let maskView = TCMaskView(image: self.image) // Present TCMaskView from current view controller. maskView.present(from: self, animated: true) ``` */ open class TCMaskView : NSObject { /** Localization dictionary, set it before you create any `TCMaskView`. An english fallback localization will be used when no matching localization is found. To determine the matching language TinyCrayon SDK uses `NSLocale.preferredLanguages`. To add suport for a language, set a localization dictionary like so: ``` TCMaskView.localizationDictionary = [ "Quick Select" : "Quick Select", "Hair Brush" : "Hair Brush", "Brush" : "Brush", "Add" : "Add", "Subtract" : "Subtract", "Setting" : "Setting", "Invert" : "Invert", "Brush size" : "Brush size", "Hardness" : "Hardness", "Opacity" : "Opacity", "Tips-Draw" : "Draw on the places to select/erase", "Tips-Zoom" : "Pinch to zoom in/out to refine details", "Tips-Move" : "Use two fingers dragging to move" ] ``` */ @objc public static var localizationDictionary = [String : [String : String]]() static let defaultLocalizationDictionary = [ "Quick Select" : "Quick Select", "Hair Brush" : "Hair Brush", "Brush" : "Brush", "Add" : "Add", "Subtract" : "Subtract", "Setting" : "Setting", "Invert" : "Invert", "Brush size" : "Brush size", "Hardness" : "Hardness", "Opacity" : "Opacity", "Tips-Draw" : "Draw on the places to select/erase", "Tips-Zoom" : "Pinch to zoom in/out to refine details", "Tips-Move" : "Use two fingers dragging to move" ] static let defaultViewModes = [TCMaskViewMode(foregroundColor: UIColor(white: 1, alpha: 0.5), backgroundImage: nil, isInverted: true), TCMaskViewMode.transparent(), TCMaskViewMode(foregroundColor: UIColor.black, backgroundImage: nil, isInverted: true)] static func getLocalizationDict() -> [String : String] { for language in NSLocale.preferredLanguages { if let dict = localizationDictionary[language] { return dict } } for language in NSLocale.preferredLanguages { let languageDict = NSLocale.components(fromLocaleIdentifier: language) if let languageCode = languageDict["kCFLocaleLanguageCodeKey"] { if let dict = localizationDictionary[languageCode] { return dict } } } return [String : String]() } let image: UIImage var controller: MaskViewController! var initialMaskValue: UInt8 = 0 var initialMaskArray: [UInt8]! var initialMaskSize = CGSize() /// Initialize a TCMaskView @objc public init(image: UIImage) { self.image = image.imageWithFixedOrientation() self.viewModes = TCMaskView.defaultViewModes self.initialTool = TCMaskTool.quickSelect self.prefersStatusBarHidden = false self.statusBarStyle = UIStatusBarStyle.default self.topBar = TCUIView() self.bottomBar = TCUIView() self.toolMenu = TCUIView() self.settingView = TCUIView() self.imageView = TCUIView() super.init() initTheme() } /// Optional delegate object that receives exit/completion notifications from this TCMaskView. @objc open weak var delegate : TCMaskViewDelegate? /** View modes of TCMaskView, if no viewModes is provided or by default, TCMaskView will use the following view modes: ``` viewModes[0] = TCMaskViewMode(foregroundColor: UIColor(white: 1, alpha: 0.5), backgroundImage: nil, isInverted: true); viewModes[1] = TCMaskViewMode.transparent() viewModes[2] = TCMaskViewMode(foregroundColor: UIColor.black, backgroundImage: nil, isInverted: true) ``` */ @objc open var viewModes: [TCMaskViewMode] /// Initial tool when TCMaskView is presented @objc open var initialTool: TCMaskTool /// True if the status bar should be hidden or false if it should be shown. @objc open var prefersStatusBarHidden: Bool /// The style of the device’s status bar. @objc open var statusBarStyle: UIStatusBarStyle /// Top bar of TCMaskView @objc open var topBar: TCUIView /// Bottom bar of TCMaskView @objc open var bottomBar: TCUIView /// Tool panel of TCMaskView @objc open var toolMenu: TCUIView /// Setting view of TCMaskView @objc open var settingView: TCUIView /// Image view of TCMaskView @objc open var imageView: TCUIView /// Test devices in development @objc open var testDevices = [String]() /// Initial state of TCMaskView @objc open var initialState = TCMaskViewState.add /** Presents the TCMaskView controller modally, which takes over the entire screen until the user closes or completes it. Set rootViewController to the current view controller at the time this method is called. **Delegates:** tcMaskViewDidExit: is called before TCMaskView is about to exit tcMaskViewDidComplete: is called before TCMaskView is about to complete - parameter rootViewController: The root view controller from which TCMaskView controller is presented - parameter animated: Specify true to animate the transition or false if you do not want the transition to be animated. */ @objc open func presentFrom(rootViewController: UIViewController, animated: Bool) { controller = MaskViewController(nibName: "MaskViewController", bundle: Bundle(identifier: "com.TinyCrayon.TCMask")) controller.setupImage(image) controller.isInNavigationViewController = false controller.modalPresentationStyle = .fullScreen setupMaskViewController(controller) rootViewController.present(controller, animated: animated, completion: nil) } /** Pushes a TCMaskView controller onto the navigationController’s stack and updates the display. TCMaskView becomes the top view controller on the navigation stack. Pushing a view controller causes its view to be embedded in the navigation interface. If the animated parameter is true, the view is animated into position; otherwise, the view is simply displayed in its final location. In addition to displaying the view associated with the new view controller at the top of the stack, this method also updates the navigation bar and tool bar accordingly. For information on how the navigation bar is updated, see Updating the Navigation Bar. **Delegates:** tcMaskViewDidExit: is called before TCMaskView is about to exit tcMaskViewDidComplete: is called before TCMaskView is about to complete tcMaskViewWillPushViewController: is called before navigation controller is about to accomplish TCMaskView and process to the next UIViewController - parameter navigationController: UINavigationController onto which TCMaskView is pushed - parameter animated: Specify true to animate the transition or false if you do not want the transition to be animated. */ @objc open func presentFrom(navigationController: UINavigationController, animated: Bool) { controller = MaskViewController(nibName: "MaskViewController", bundle: Bundle(identifier: "com.TinyCrayon.TCMask")) controller.setupImage(image) controller.isInNavigationViewController = true setupMaskViewController(controller) navigationController.pushViewController(controller, animated: animated) } /** Set the initial mask value of TCMaksView. - parameter mask: Initial mask value, the entire initial mask will be filled with this value */ @objc open func setInitialMaskWithValue(_ mask: UInt8) { initialMaskArray = nil initialMaskValue = mask } /** Set the initial mask value of TCMaksView. - parameter mask: Initial mask value, mask length should match TCMaskView image size (mask.count == image.size.width * image.size.height) */ @objc open func setInitialMaskWithArray(_ mask: [UInt8]) { assert(mask.count > 0, "setInitialMask: inital mask array is empty") setInitialMask(mask, size: image.size) } /** Set the initial mask value of TCMaksView. - parameter mask: Initial mask value - parameter size: Size of mask, mask length should match size (mask.count == size.width * size.height), if size is not the same as image size, the initial mask will be scalled to fit image size. */ @objc open func setInitialMask(_ mask: [UInt8], size: CGSize) { assert(Int(size.width * size.height) == mask.count, "setInitialMask: mask length \(mask.count) does not match size \(size)") initialMaskArray = mask initialMaskSize = size } func setupMaskViewController(_ controller: MaskViewController) { // setup view modes controller.viewModes.removeAll() if viewModes.count == 0 { controller.viewModes = TCMaskView.defaultViewModes } else { for mode in self.viewModes { controller.viewModes.append(mode.clone()) } } controller.viewModeIdx = 0 // deep copy UI settings var settings = UISettings() settings.prefersStatusBarHidden = self.prefersStatusBarHidden settings.statusBarStyle = self.statusBarStyle settings.topBar = self.topBar.clone() settings.imageView = self.imageView.clone() settings.bottomBar = self.bottomBar.clone() settings.toolMenu = self.toolMenu.clone() settings.settingView = self.settingView.clone() controller.uiSettings = settings // setup initial params controller.initialMaskValue = initialMaskValue controller.initialMaskArray = initialMaskArray controller.initialMaskSize = initialMaskSize controller.initialToolType = initialTool controller.initialState = initialState // setup delegate controller.delegate = self.delegate // setup test devices controller.testDevices = self.testDevices // setup localization controller.localizationDict = TCMaskView.getLocalizationDict() } func initTheme() { self.statusBarStyle = UIStatusBarStyle.default topBar.backgroundColor = UIColor.white topBar.tintColor = UIColor(white: 84/255, alpha: 1) imageView.backgroundColor = UIColor(white: 21/255, alpha: 1) toolMenu.backgroundColor = UIColor(red: 87/255, green: 100/255, blue: 116/255, alpha: 1) toolMenu.tintColor = UIColor.white toolMenu.highlightedColor = UIColor(red: 197/255, green: 164/255, blue: 126/255, alpha: 1) toolMenu.textColor = UIColor.white bottomBar.backgroundColor = UIColor.white bottomBar.tintColor = UIColor(white: 84/255, alpha: 1) bottomBar.textColor = UIColor(white: 84/255, alpha: 1) bottomBar.highlightedColor = UIColor(red: 75/255, green: 126/255, blue: 194/255, alpha: 1) settingView.backgroundColor = UIColor(white: 54/255, alpha: 0.9) settingView.tintColor = UIColor.lightGray settingView.textColor = UIColor.white } }
mit
dd8c66fa6c6d3d77bc5c877ef9d95461
38.653465
292
0.660924
4.848668
false
false
false
false
benlangmuir/swift
test/SourceKit/SyntaxMapData/syntaxmap-multiple-edits.swift
5
9931
// RUN: %sourcekitd-test -req=open -print-raw-response %S/Inputs/syntaxmap-multiple-edits.swift == -req=edit -print-raw-response -pos=6:13 -length=1 -replace=" " %S/Inputs/syntaxmap-multiple-edits.swift == -req="edit" -pos=14:1 -length=0 -replace="let y = 2" -print-raw-response %S/Inputs/syntaxmap-multiple-edits.swift == -req="edit" -pos=8:10 -length=7 -replace='Int64 = 3; let z = 2' -print-raw-response %S/Inputs/syntaxmap-multiple-edits.swift == -req="edit" -pos=4:9 -length=2 -replace='50 * 95 - 100' -print-raw-response %S/Inputs/syntaxmap-multiple-edits.swift == -req="edit" -pos=1:1 -length=0 -replace='func firstFunc(x: Int) {}' -print-raw-response %S/Inputs/syntaxmap-multiple-edits.swift | %sed_clean > %t.response // RUN: %FileCheck -input-file=%t.response %s // Initial syntax map // CHECK: {{^}}{ // CHECK-NEXT: key.offset: 0, // CHECK-NEXT: key.length: 152, // CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse, // CHECK-NEXT: key.syntaxmap: [ // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.doccomment, // CHECK-NEXT: key.offset: 2, // CHECK-NEXT: key.length: 14 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.doccomment, // CHECK-NEXT: key.offset: 16, // CHECK-NEXT: key.length: 6 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.doccomment.field, // CHECK-NEXT: key.offset: 22, // CHECK-NEXT: key.length: 4 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.doccomment, // CHECK-NEXT: key.offset: 26, // CHECK-NEXT: key.length: 19 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 45, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 49, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 53, // CHECK-NEXT: key.length: 2 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 57, // CHECK-NEXT: key.length: 6 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 64, // CHECK-NEXT: key.length: 5 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 74, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 78, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.typeidentifier, // CHECK-NEXT: key.offset: 81, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 87, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 91, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 95, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.typeidentifier, // CHECK-NEXT: key.offset: 98, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 104, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 109, // CHECK-NEXT: key.length: 4 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 114, // CHECK-NEXT: key.length: 4 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 127, // CHECK-NEXT: key.length: 6 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 134, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.operator, // CHECK-NEXT: key.offset: 135, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 136, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.operator, // CHECK-NEXT: key.offset: 138, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 140, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.operator, // CHECK-NEXT: key.offset: 141, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 142, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: } // CHECK-NEXT: ], // After replacing a space with a space // CHECK: {{^}}{ // CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse, // CHECK-NEXT: key.syntaxmap: [ // CHECK-NEXT: ], // After adding code at the end of the file // CHECK: {{^}}{ // CHECK-NEXT: key.offset: 151, // CHECK-NEXT: key.length: 9, // CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse, // CHECK-NEXT: key.syntaxmap: [ // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 151, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 155, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 159, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: } // CHECK-NEXT: ], // After inserting more than we removed // CHECK: {{^}}{ // CHECK-NEXT: key.offset: 98, // CHECK-NEXT: key.length: 20, // CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse, // CHECK-NEXT: key.syntaxmap: [ // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.typeidentifier, // CHECK-NEXT: key.offset: 98, // CHECK-NEXT: key.length: 5 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 106, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 109, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 113, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 117, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: } // CHECK-NEXT: ], // After inserting less than we removed // CHECK: {{^}}{ // CHECK-NEXT: key.offset: 53, // CHECK-NEXT: key.length: 13, // CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse, // CHECK-NEXT: key.syntaxmap: [ // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 53, // CHECK-NEXT: key.length: 2 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.operator, // CHECK-NEXT: key.offset: 56, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 58, // CHECK-NEXT: key.length: 2 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.operator, // CHECK-NEXT: key.offset: 61, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 63, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: } // CHECK-NEXT: ], // After adding code at the start of the file // CHECK: {{^}}{ // CHECK-NEXT: key.offset: 0, // CHECK-NEXT: key.length: 21, // CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse, // CHECK-NEXT: key.syntaxmap: [ // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 0, // CHECK-NEXT: key.length: 4 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 5, // CHECK-NEXT: key.length: 9 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 15, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.typeidentifier, // CHECK-NEXT: key.offset: 18, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: } // CHECK-NEXT: ],
apache-2.0
89d541368f41441ad2260006e0354a52
34.981884
726
0.624408
2.862785
false
false
false
false
Urinx/SomeCodes
Swift/The Swift Programming Language/10.Properties.playground/section-1.swift
1
3274
// P.366 // Properties struct FixedLengthRange { var firstValue: Int let length: Int } var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) rangeOfThreeItems.firstValue = 6 // Lazy Stored Properties class DataImporter { var fileName = "data.txt" } class dataManager { lazy var importer = DataImporter() var data = [String]() } let manager = dataManager() manager.data.append("Some data") manager.data.append("Some more data") // the DataImporter instance for the importer property has not yet been created println(manager.importer.fileName) // the DataImporter instance for the importer property has now been created // P.374 // Computed Properties struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) let initialSquareCenter = square.center square.center = Point(x: 15.0, y: 15.0) println("square.origin is now at (\(square.origin.x), \(square.origin.y))") // Shorthand Setter Declaration struct AlternativeRect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set { origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } } } // P.380 // Read-Only Computed Properties struct Cuboid { var width = 0.0, height = 0.0, depth = 0.0 var volume: Double { return width * height * depth } } let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0) println("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") // P.382 // Property Observers class StepCounter { var totalSteps: Int = 0 { willSet { println("About to set totalSteps tp \(newValue)") } didSet { if totalSteps > oldValue { println("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 // P.387 // Global and Local Variables struct AudioChannel { static let thresholdLevel = 10 static var maxInputLevelForAllChannels = 0 var currentLevel: Int = 0 { didSet { if currentLevel > AudioChannel.thresholdLevel { currentLevel = AudioChannel.thresholdLevel } if currentLevel > AudioChannel.maxInputLevelForAllChannels { AudioChannel.maxInputLevelForAllChannels = currentLevel } } } } var leftChannel = AudioChannel() var rightChannel = AudioChannel() leftChannel.currentLevel = 7 println(AudioChannel.maxInputLevelForAllChannels)
gpl-2.0
02965eeffa028c608344507c282f66c6
24.984127
87
0.619426
3.815851
false
false
false
false
BranchMetrics/iOS-Deferred-Deep-Linking-SDK
Branch-TestBed-Swift/TestBed-Swift/KeyValuePairTableViewController.swift
1
4680
// // KeyValuePairTableViewController.swift // TestBed-Swift // // Created by David Westgate on 8/29/16. // Copyright © 2016 Branch Metrics. All rights reserved. // import UIKit class KeyValuePairTableViewController: UITableViewController, UITextFieldDelegate, UITextViewDelegate { // MARK: - Controls @IBOutlet weak var keyTextField: UITextField! @IBOutlet weak var valueTextView: UITextView! @IBOutlet weak var clearButton: UIButton! @IBOutlet weak var saveButton: UIBarButtonItem! var incumbantKey = "" var incumbantValue = "" var viewTitle = "Default Title" var keyHeader = "Default Key Header" var keyPlaceholder = "Default Key Placeholder" var keyFooter = "Default Key Footer" var valueHeader = "Default Value Header" var valueFooter = "Default Value Footer" var keyKeyboardType = UIKeyboardType.default var valueKeyboardType = UIKeyboardType.default // MARK: - Core View Functions override func viewDidLoad() { super.viewDidLoad() title = viewTitle keyTextField.placeholder = keyPlaceholder keyTextField.text = incumbantKey keyTextField.keyboardType = keyKeyboardType keyTextField.addTarget(self, action: #selector(textFieldDidChange), for: UIControlEvents.editingChanged) valueTextView.delegate = self valueTextView.text = incumbantValue valueTextView.keyboardType = valueKeyboardType valueTextView.textColor = UIColor.lightGray updateButtonStates() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Control Functions @IBAction func clearButtonTouchUpInside(_ sender: AnyObject) { valueTextView.text = incumbantValue valueTextView.textColor = UIColor.lightGray valueTextView.becomeFirstResponder() valueTextView.selectedTextRange = valueTextView.textRange(from: valueTextView.beginningOfDocument, to: valueTextView.beginningOfDocument) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var header = "" switch section { case 0: header = keyHeader case 1: header = valueHeader default: break } return header } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { var footer = "" switch section { case 0: footer = keyFooter case 1: footer = valueFooter default: break } return footer } @objc func textFieldDidChange() { saveButton.isEnabled = keyTextField.text == "" ? false : true } func textViewDidChangeSelection(_ textView: UITextView) { if self.view.window != nil { if textView.textColor == UIColor.lightGray { textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument) } } } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard (text != "\n") else { performSegue(withIdentifier: "Save", sender: "save") return false } let t: NSString = textView.text as NSString let updatedText = t.replacingCharacters(in: range, with:text) guard (updatedText != "") else { clearButton.isHidden = true textView.text = incumbantValue textView.textColor = UIColor.lightGray textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument) return false } if (textView.textColor == UIColor.lightGray) { textView.text = nil textView.textColor = UIColor.black } return true } func textViewDidChange(_ textView: UITextView) { updateButtonStates() } func textViewDidBeginEditing(_ textView: UITextView) { clearButton.isHidden = textView.text == "" ? true : false } func textViewDidEndEditing(_ textView: UITextView) { clearButton.isHidden = true } func updateButtonStates() { clearButton.isHidden = valueTextView.textColor == UIColor.lightGray ? true : false saveButton.isEnabled = keyTextField.text == "" ? false : true } }
mit
998bc93238e3c11c55654740b959f085
31.047945
145
0.63069
5.485346
false
false
false
false
zalando/zmon-ios
zmon/controllers/NavigationVC.swift
1
2611
// // NavigationVC.swift // zmon // // Created by Andrej Kincel on 15/12/15. // Copyright © 2015 Zalando Tech. All rights reserved. // import UIKit class NavigationVC: UINavigationController { weak var rootVC: RootVC? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationBar.barStyle = UIBarStyle.Black self.navigationBar.tintColor = ZmonColor.textPrimary showZmonStatus() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation func showZmonStatus() { if let zmonStatusVC: BaseVC = self.storyboard!.instantiateViewControllerWithIdentifier("ZmonStatusVC") as? BaseVC { zmonStatusVC.rootVC = self.rootVC self.setViewControllers([zmonStatusVC], animated: true) } } func showObservedTeams() { if let observedTeamsVC: BaseVC = self.storyboard!.instantiateViewControllerWithIdentifier("ObservedTeamsVC") as? BaseVC { observedTeamsVC.rootVC = self.rootVC self.setViewControllers([observedTeamsVC], animated: true) } } func showObservedAlerts() { if let observedAlertsVC = self.storyboard?.instantiateViewControllerWithIdentifier("ObservedAlertsVC") as? ObservedAlertsVC { observedAlertsVC.rootVC = rootVC observedAlertsVC.fetchRemoteAlerts() setViewControllers([observedAlertsVC], animated: true) } } func showZmonDashboard() { if let zmonDashboardVC: BaseVC = self.storyboard!.instantiateViewControllerWithIdentifier("ZmonDashboardVC") as? BaseVC { zmonDashboardVC.rootVC = self.rootVC self.setViewControllers([zmonDashboardVC], animated: true) } } func showSettings() { let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString) if let url = settingsUrl { UIApplication.sharedApplication().openURL(url) } } func showLogout() { //reset username and password CredentialsStore.sharedInstance.clearCredentials() //delete the token CredentialsStore.sharedInstance.clearToken() //show the login view let result = self.storyboard?.instantiateViewControllerWithIdentifier("LoginVC") self.presentViewController(result!, animated: true, completion: nil) } }
mit
2949f1f6b5fb7387a85ca2c67a3b1237
29.705882
133
0.640613
5.199203
false
false
false
false
WickedColdfront/Slide-iOS
Slide for Reddit/SingleContentViewController.swift
1
3159
// // SingleContentViewController.swift // Slide for Reddit // // Created by Carlos Crane on 8/2/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import UIKit class SingleContentViewController: SwipeDownModalVC, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var vCs: [UIViewController] = [ClearVC()] var baseURL: URL? var lqURL: URL? public init(url: URL, lq: URL?){ self.baseURL = url self.lqURL = lq self.vCs.append(MediaDisplayViewController.init(url: baseURL!, text: nil, lqURL: lq))//todo change this super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = UIRectEdge.all self.extendedLayoutIncludesOpaqueBars = true } override func viewDidLoad(){ super.viewDidLoad() self.dataSource = self self.delegate = self view.backgroundColor = UIColor.black.withAlphaComponent(0.84) self.navigationController?.view.backgroundColor = UIColor.clear let firstViewController = vCs[1] setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil) } func pageViewController(_ pageViewController : UIPageViewController, didFinishAnimating: Bool, previousViewControllers: [UIViewController], transitionCompleted: Bool) { if(pageViewController.viewControllers?.first == vCs[0]){ self.dismiss(animated: true, completion: nil) } } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = vCs.index(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return nil } guard vCs.count > previousIndex else { return nil } return vCs[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = vCs.index(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 let orderedViewControllersCount = vCs.count guard orderedViewControllersCount != nextIndex else { return nil } guard orderedViewControllersCount > nextIndex else { return nil } return vCs[nextIndex] } }
apache-2.0
7f69c6788e484a2529af7e277dd41c5d
31.895833
172
0.618429
6.003802
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/LayoutKit/Sources/Math/AxisFlexibility.swift
8
1682
// Copyright 2016 LinkedIn Corp. // 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. /// A wrapper around Flexibility that makes it easy to do math relative to an axis. public struct AxisFlexibility { public let axis: Axis public let flexibility: Flexibility public var axisFlex: Flexibility.Flex { get { switch axis { case .horizontal: return flexibility.horizontal case .vertical: return flexibility.vertical } } } public var crossFlex: Flexibility.Flex { get { switch axis { case .horizontal: return flexibility.vertical case .vertical: return flexibility.horizontal } } } public init(axis: Axis, flexibility: Flexibility) { self.axis = axis self.flexibility = flexibility } public init(axis: Axis, axisFlex: Flexibility.Flex, crossFlex: Flexibility.Flex) { self.axis = axis switch axis { case .horizontal: self.flexibility = Flexibility(horizontal: axisFlex, vertical: crossFlex) case .vertical: self.flexibility = Flexibility(horizontal: crossFlex, vertical: axisFlex) } } }
mit
7866fab347fa5bcf0d031aa057880c06
32
131
0.627824
4.875362
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/InstantPageTextStyleStack.swift
1
7929
// // InstantPageTextStyleStack.swift // Telegram // // Created by keepcoder on 10/08/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TelegramCore import TGUIKit enum InstantPageTextStyle { case fontSize(CGFloat) case lineSpacingFactor(CGFloat) case fontSerif(Bool) case fontFixed(Bool) case bold case italic case underline case strikethrough case textColor(NSColor) case `subscript` case superscript case markerColor(NSColor) case marker case anchor(String, Bool) case linkColor(NSColor) case linkMarkerColor(NSColor) case link(Bool) } extension NSAttributedString.Key { static let instantPageLineSpacingFactorAttribute = NSAttributedString.Key("InstantPageLineSpacingFactorAttribute") static let instantPageMarkerColorAttribute = NSAttributedString.Key("InstantPageMarkerColorAttribute") static let instantPageMediaIdAttribute = NSAttributedString.Key("InstantPageMediaIdAttribute") static let instantPageMediaDimensionsAttribute = NSAttributedString.Key("InstantPageMediaDimensionsAttribute") static let instantPageAnchorAttribute = NSAttributedString.Key("InstantPageAnchorAttribute") } final class InstantPageTextStyleStack { private var items: [InstantPageTextStyle] = [] func push(_ item: InstantPageTextStyle) { items.append(item) } func pop() { if !items.isEmpty { items.removeLast() } } func textAttributes() -> [NSAttributedString.Key: Any] { var fontSize: CGFloat? var fontSerif: Bool? var fontFixed: Bool? var bold: Bool? var italic: Bool? var strikethrough: Bool? var underline: Bool? var color: NSColor? var lineSpacingFactor: CGFloat? var baselineOffset: CGFloat? var markerColor: NSColor? var marker: Bool? var anchor: Dictionary<String, Any>? var linkColor: NSColor? var linkMarkerColor: NSColor? var link: Bool? for item in self.items.reversed() { switch item { case let .fontSize(value): if fontSize == nil { fontSize = value } case let .fontSerif(value): if fontSerif == nil { fontSerif = value } case let .fontFixed(value): if fontFixed == nil { fontFixed = value } case .bold: if bold == nil { bold = true } case .italic: if italic == nil { italic = true } case .strikethrough: if strikethrough == nil { strikethrough = true } case .underline: if underline == nil { underline = true } case let .textColor(value): if color == nil { color = value } case let .lineSpacingFactor(value): if lineSpacingFactor == nil { lineSpacingFactor = value } case .subscript: if baselineOffset == nil { baselineOffset = 0.35 underline = false } case .superscript: if baselineOffset == nil { baselineOffset = -0.35 } case let .markerColor(color): if markerColor == nil { markerColor = color } case .marker: if marker == nil { marker = true } case let .anchor(name, empty): if anchor == nil { anchor = ["name": name, "empty": empty] } case let .linkColor(color): if linkColor == nil { linkColor = color } case let .linkMarkerColor(color): if linkMarkerColor == nil { linkMarkerColor = color } case let .link(instant): if link == nil { link = instant } } } var attributes: [NSAttributedString.Key: Any] = [:] var parsedFontSize: CGFloat if let fontSize = fontSize { parsedFontSize = fontSize } else { parsedFontSize = 16.0 } if let baselineOffset = baselineOffset { attributes[.baselineOffset] = round(parsedFontSize * baselineOffset); parsedFontSize = round(parsedFontSize * 0.85) } if (bold != nil && bold!) && (italic != nil && italic!) { if fontSerif != nil && fontSerif! { attributes[.font] = NSFont(name: "Georgia-BoldItalic", size: parsedFontSize) } else if fontFixed != nil && fontFixed! { attributes[.font] = NSFont(name: "Menlo-BoldItalic", size: parsedFontSize) } else { attributes[.font] = systemMediumFont(parsedFontSize) } } else if bold != nil && bold! { if fontSerif != nil && fontSerif! { attributes[.font] = NSFont(name: "Georgia-Bold", size: parsedFontSize) } else if fontFixed != nil && fontFixed! { attributes[.font] = NSFont(name: "Menlo-Bold", size: parsedFontSize) } else { attributes[.font] = NSFont.bold(parsedFontSize) } } else if italic != nil && italic! { if fontSerif != nil && fontSerif! { attributes[.font] = NSFont(name: "Georgia-Italic", size: parsedFontSize) } else if fontFixed != nil && fontFixed! { attributes[.font] = NSFont(name: "Menlo-Italic", size: parsedFontSize) } else { attributes[.font] = NSFont.italic(parsedFontSize) } } else { if fontSerif != nil && fontSerif! { attributes[.font] = NSFont(name: "Georgia", size: parsedFontSize) } else if fontFixed != nil && fontFixed! { attributes[.font] = NSFont(name: "Menlo", size: parsedFontSize) } else { attributes[.font] = NSFont.normal(parsedFontSize) } } if strikethrough != nil && strikethrough! { attributes[.strikethroughStyle] = (NSUnderlineStyle.single.rawValue | NSUnderlineStyle.patternDash.rawValue) as NSNumber } if underline != nil && underline! { attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue as NSNumber } if let link = link, let linkColor = linkColor { attributes[.foregroundColor] = linkColor if link, let linkMarkerColor = linkMarkerColor { attributes[.instantPageMarkerColorAttribute] = linkMarkerColor } } else { if let color = color { attributes[.foregroundColor] = color } else { attributes[.foregroundColor] = NSColor.black } } if let lineSpacingFactor = lineSpacingFactor { attributes[.instantPageLineSpacingFactorAttribute] = lineSpacingFactor as NSNumber } if marker != nil && marker!, let markerColor = markerColor { attributes[.instantPageMarkerColorAttribute] = markerColor } if let anchor = anchor { attributes[.instantPageAnchorAttribute] = anchor } return attributes } }
gpl-2.0
0e2a3a1bfab133a5ecf3e308a808d610
33.172414
132
0.525858
5.327957
false
false
false
false
avhurst/week3
InstaClone/InstaClone/ModelAdditions.swift
1
842
// // ModelAdditions.swift // InstaClone // // Created by Allen Hurst on 2/16/16. // Copyright © 2016 Allen Hurst. All rights reserved. // import UIKit import CloudKit enum PostError: ErrorType { case WritingImage case CreatingCKRecord } extension Post { class func recordWith(post:Post) throws -> CKRecord? { let imageURL = NSURL.imageURL() guard let data = UIImageJPEGRepresentation(post.image, 0.7) else { throw PostError.WritingImage } let saved = data.writeToURL(imageURL, atomically: true) if saved { let asset = CKAsset(fileURL: imageURL) let record = CKRecord(recordType: "Post") record.setObject(asset, forKey: "image") return record } else { throw PostError.CreatingCKRecord } } }
mit
29b5f956a94a0ca478108f448f35cf91
23.057143
105
0.621879
4.312821
false
false
false
false
GeoThings/LakestoneGeometry
Source/Coordinate.swift
1
5720
// // Coordinate.swift // LakestoneGeometry // // Created by Volodymyr Andriychenko on 10/14/16. // Copyright © 2016 GeoThings. 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. // #if COOPER import lakestonecore.android #else import LakestoneCore import Foundation #endif // these are needed for math functions, java would just use Math.<function_name> #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin.C #elseif os(Linux) import Glibc #endif //MARK: - Coordinate using Double type public class Coordinate { /*! primarily designated to store longitude in degrees */ public var x: Double /*! primarily designated to store latitude in degrees */ public var y: Double public init(x: Double, y: Double){ self.x = x self.y = y } // for CustomSerialization public required init(){ self.x = 0 self.y = 0 } public required init(variableMap: [String : Any]) throws { guard let x = variableMap["x"] else { throw DictionaryInstantiationError.Representation(fieldName: "x", detail: "not found").error } guard let y = variableMap["y"] else { throw DictionaryInstantiationError.Representation(fieldName: "x", detail: "not found").error } self.x = x as! Double self.y = y as! Double } } //MARK: Operations on Coordinates public func distanceBetween(fromPoint pointA: Coordinate, toPoint pointB: Coordinate) -> Double { #if COOPER return Math.sqrt(Line(endpointA: pointA, endpointB: pointB).squaredLength) #else return sqrt(Line(endpointA: pointA, endpointB: pointB).squaredLength) #endif } //MARK: CustomStringConvertable extension Coordinate: CustomStringConvertible { public var description: String { return "Coordinate: { long: \(self.x), lat: \(self.y) }" } #if COOPER public override func toString() -> String { return self.description } #endif } //MARK: CustomSerializable extension Coordinate: CustomSerializable { public static var readingIgnoredVariableNames: Set<String> { return Set<String>() } public static var writingIgnoredVariableNames: Set<String> { return Set<String>() } public static var allowedTypeDifferentVariableNames: Set<String> { return Set<String>() } public static var variableNamesAlliases: [String: String] { return [String: String]() } public var manuallySerializedValues: [String: Any] { return [String: Any]() } } //MARK: Java's Equatable analogue extension Coordinate: Equatable { #if COOPER public override func equals(_ o: Object!) -> Bool { guard let other = o as? Self else { return false } return (self == other) } #endif } public func ==(lhs: Coordinate, rhs: Coordinate) -> Bool { return (lhs.x == rhs.x && lhs.y == rhs.y) } //----------------------------------------------------------------------------------- //MARK: - Coordinate using Int type public class CoordinateInt { /*! primarily designated to store longitude in degrees */ public var x: Int /*! primarily designated to store latitude in degrees */ public var y: Int public init(x: Int, y: Int){ self.x = x self.y = y } // for CustomSerialization public required init(){ self.x = 0 self.y = 0 } public required init(variableMap: [String : Any]) throws { guard let x = variableMap["x"] else { throw DictionaryInstantiationError.Representation(fieldName: "x", detail: "not found").error } guard let y = variableMap["y"] else { throw DictionaryInstantiationError.Representation(fieldName: "x", detail: "not found").error } self.x = x as! Int self.y = y as! Int } } //MARK: CustomStringConvertable extension CoordinateInt: CustomStringConvertible { public var description: String { return "CoordinateInt: { long: \(self.x), lat: \(self.y) }" } #if COOPER public override func toString() -> String { return self.description } #endif } //MARK: CustomSerializable extension CoordinateInt: CustomSerializable { public static var readingIgnoredVariableNames: Set<String> { return Set<String>() } public static var writingIgnoredVariableNames: Set<String> { return Set<String>() } public static var allowedTypeDifferentVariableNames: Set<String> { return Set<String>() } public static var variableNamesAlliases: [String: String] { return [String: String]() } public var manuallySerializedValues: [String: Any] { return [String: Any]() } } //MARK: Java's Equatable analogue extension CoordinateInt: Equatable { #if COOPER public override func equals(_ o: Object!) -> Bool { guard let other = o as? Self else { return false } return (self == other) } #endif } public func ==(lhs: CoordinateInt, rhs: CoordinateInt) -> Bool { return (lhs.x == rhs.x && lhs.y == rhs.y) }
apache-2.0
333deeda4108165d30c5c6b40c3334a0
27.034314
140
0.633852
4.319486
false
false
false
false
ApplauseOSS/Swifjection
Example/Tests/Helpers/ExampleClasses.swift
1
2407
// // Copyright © 2017 Applause Inc. All rights reserved. // import Foundation @testable import Swifjection protocol EmptySwiftProtocol {} class ClassConformingToProtocol: EmptySwiftProtocol {} struct StructConformingToProtocol: EmptySwiftProtocol {} class EmptySwiftClass {} protocol InjectableClassProtocol: class, Injectable {} class InjectableClass: InjectableClassProtocol { var injector: Injecting? var injectDependenciesCalled = false var initCallsCount = 0 var injectDependenciesCallsCount = 0 required convenience init?(injector: Injecting) { self.init() self.initCallsCount += 1 self.injector = injector } func injectDependencies(injector: Injecting) { self.injectDependenciesCalled = true self.injectDependenciesCallsCount += 1 } } class InjectableObjCClass: NSObject, Injectable { var injector: Injecting? var injectDependenciesCalled = false var initCallsCount = 0 var injectDependenciesCallsCount = 0 required convenience init?(injector: Injecting) { self.init() self.initCallsCount += 1 self.injector = injector } func injectDependencies(injector: Injecting) { self.injectDependenciesCalled = true self.injectDependenciesCallsCount += 1 } } class ObjCClass: NSObject { var initCallsCount = 0 override init() { self.initCallsCount += 1 } } class ClassWithDependencies: Injectable { var injector: Injecting? var objectConformingToProtocol: EmptySwiftProtocol? var emptySwiftObject: EmptySwiftClass? var injectableObject: InjectableClass? var injectableObjCObject: InjectableObjCClass? var objCObject: ObjCClass? required convenience init?(injector: Injecting) { self.init() self.injector = injector } func injectDependencies(injector: Injecting) { self.objectConformingToProtocol = injector.getObject(withType: EmptySwiftProtocol.self) self.emptySwiftObject = injector.getObject(withType: EmptySwiftClass.self) self.injectableObject = injector.getObject(withType: InjectableClass.self) self.injectableObjCObject = injector.getObject(withType: InjectableObjCClass.self) self.objCObject = injector.getObject(withType: ObjCClass.self) } }
mit
f0c66cde8baa146815c523097483c351
24.870968
95
0.700333
4.77381
false
false
false
false
wenluma/swift
test/decl/protocol/special/coding/struct_codable_failure_diagnostics.swift
4
4204
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s 2>&1 | %FileCheck %s // Codable struct with non-Codable property. struct S1 : Codable { struct Nested {} var a: String = "" var b: Int = 0 var c: Nested = Nested() } // Codable struct with non-enum CodingKeys. struct S2 : Codable { var a: String = "" var b: Int = 0 var c: Double? struct CodingKeys : CodingKey { var stringValue: String = "" var intValue: Int? = nil init?(stringValue: String) {} init?(intValue: Int) {} } } // Codable struct with CodingKeys not conforming to CodingKey. struct S3 : Codable { var a: String = "" var b: Int = 0 var c: Double? enum CodingKeys : String { case a case b case c } } // Codable struct with extraneous CodingKeys struct S4 : Codable { var a: String = "" var b: Int = 0 var c: Double? enum CodingKeys : String, CodingKey { case a case a2 case b case b2 case c case c2 } } // Codable struct with non-decoded property (which has no default value). struct S5 : Codable { var a: String = "" var b: Int var c: Double? enum CodingKeys : String, CodingKey { case a case c } } // Structs cannot yet synthesize Encodable or Decodable in extensions. struct S6 {} extension S6 : Codable {} // Decodable diagnostics are output first here { // CHECK: error: type 'S1' does not conform to protocol 'Decodable' // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: note: cannot automatically synthesize 'Decodable' because 'S1.Nested' does not conform to 'Decodable' // CHECK: error: type 'S2' does not conform to protocol 'Decodable' // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: note: cannot automatically synthesize 'Decodable' because 'CodingKeys' is not an enum // CHECK: error: type 'S3' does not conform to protocol 'Decodable' // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: note: cannot automatically synthesize 'Decodable' because 'CodingKeys' does not conform to CodingKey // CHECK: error: type 'S4' does not conform to protocol 'Decodable' // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: note: CodingKey case 'a2' does not match any stored properties // CHECK: note: CodingKey case 'b2' does not match any stored properties // CHECK: note: CodingKey case 'c2' does not match any stored properties // CHECK: error: type 'S5' does not conform to protocol 'Decodable' // CHECK: note: protocol requires initializer 'init(from:)' with type 'Decodable' // CHECK: note: cannot automatically synthesize 'Decodable' because 'b' does not have a matching CodingKey and does not have a default value // CHECK: error: implementation of 'Decodable' cannot be automatically synthesized in an extension yet // } // Encodable { // CHECK: error: type 'S1' does not conform to protocol 'Encodable' // CHECK: note: protocol requires function 'encode(to:)' with type 'Encodable' // CHECK: note: cannot automatically synthesize 'Encodable' because 'S1.Nested' does not conform to 'Encodable' // CHECK: error: type 'S2' does not conform to protocol 'Encodable' // CHECK: note: protocol requires function 'encode(to:)' with type 'Encodable' // CHECK: note: cannot automatically synthesize 'Encodable' because 'CodingKeys' is not an enum // CHECK: error: type 'S3' does not conform to protocol 'Encodable' // CHECK: note: protocol requires function 'encode(to:)' with type 'Encodable' // CHECK: note: cannot automatically synthesize 'Encodable' because 'CodingKeys' does not conform to CodingKey // CHECK: error: type 'S4' does not conform to protocol 'Encodable' // CHECK: note: protocol requires function 'encode(to:)' with type 'Encodable' // CHECK: note: CodingKey case 'a2' does not match any stored properties // CHECK: note: CodingKey case 'b2' does not match any stored properties // CHECK: note: CodingKey case 'c2' does not match any stored properties // CHECK: error: implementation of 'Encodable' cannot be automatically synthesized in an extension yet // }
mit
563301e7b505c79ccec3b9ca6c133da7
34.033333
140
0.712417
3.940019
false
false
false
false
testpress/ios-app
ios-app/UI/ContentsTableViewCell.swift
1
7073
// // ContentsTableViewCell.swift // ios-app // // Copyright © 2017 Testpress. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class ContentsTableViewCell: UITableViewCell { @IBOutlet weak var contentName: UILabel! @IBOutlet weak var contentViewCell: UIView! @IBOutlet weak var thumbnailImage: UIImageView! @IBOutlet weak var videoDurationLabel: UILabel! @IBOutlet weak var thumbnailImageContainer: UIView! @IBOutlet weak var duration: UILabel! @IBOutlet weak var questionsCount: UILabel! @IBOutlet weak var examDetailsLayout: UIStackView! @IBOutlet weak var attemptedTick: UIImageView! @IBOutlet weak var lock: UIView! @IBOutlet weak var contentLayout: UIStackView! @IBOutlet weak var questionsCountStack: UIStackView! var parentViewController: ContentsTableViewController! = nil var position: Int! func initCell(position: Int, viewController: ContentsTableViewController) { parentViewController = viewController self.position = position let content = parentViewController.items[position] contentName.text = content.name thumbnailImage.addRoundedCorners(radius: 3.0) lock.addRoundedCorners(radius: 9.0) addThumbnail(content: content) if content.exam != nil { duration.text = content.exam?.duration questionsCount.text = String(content.exam!.numberOfQuestions) examDetailsLayout.isHidden = false } else if content.video != nil { thumbnailImageContainer.addSubview(videoDurationLabel) videoDurationLabel.addRoundedCorners(radius: 2.0) videoDurationLabel.isHidden = false videoDurationLabel.text = content.video?.duration examDetailsLayout.isHidden = true } else { examDetailsLayout.isHidden = true } if content.isLocked || content.isScheduled || content.hasEnded{ lock.isHidden = false contentLayout.alpha = 0.5 thumbnailImage.alpha = 0.5 attemptedTick.isHidden = true if (content.isScheduled) { showScheduledDate() } if (content.hasEnded) { showExpiryInfo() } } else { lock.isHidden = true contentLayout.alpha = 1 thumbnailImage.alpha = 1 attemptedTick.isHidden = content.attemptsCount == 0 } thumbnailImageContainer.addSubview(attemptedTick) let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onItemClick)) contentViewCell.addGestureRecognizer(tapRecognizer) } func addThumbnail(content: Content) { if (content.coverImageSmall != nil) { thumbnailImage.isHidden = false thumbnailImage.contentMode = .scaleToFill thumbnailImage.kf.setImage(with: URL(string: content.coverImageSmall), placeholder: Images.PlaceHolder.image) } else { thumbnailImageContainer.backgroundColor = UIColor.lightGray thumbnailImage.isHidden = true let frontimgview = UIImageView(image: getThumbnailIcon(content: content)) frontimgview.frame = CGRect(x: (thumbnailImageContainer.frame.width / 2) - 13, y: (thumbnailImageContainer.frame.height / 2) - 13, width: 32, height: 32) thumbnailImageContainer.addSubview(frontimgview) } } func getThumbnailIcon(content: Content) -> UIImage { if (content.video != nil) { return Images.VideoIconWhite.image } else if (content.videoConference != nil) { return Images.LiveClassIcon.image } else if (content.htmlObject != nil) { return Images.NotesIconWhite.image } else if (content.attachment != nil) { return Images.AttachmentIconWhite.image } return Images.ExamIconWhite.image } func showScheduledDate() { let content = parentViewController.items[position] if content.isScheduled { examDetailsLayout.isHidden = false let date = FormatDate.format(dateString: content.start) duration.text = "This will be available on \(date)" questionsCountStack.isHidden = true } } func showExpiryInfo() { let content = parentViewController.items[position] examDetailsLayout.isHidden = false let date = FormatDate.format(dateString: content.end) duration.text = "This content is expired on \(date)" questionsCountStack.isHidden = true } func addOverlay(on view: UIView) { let overlay: UIView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)) overlay.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.1) view.addSubview(overlay) } @objc func onItemClick() { let content = parentViewController.items[position] if (content.isScheduled || content.isLocked || content.hasEnded) { return } let viewController = parentViewController.storyboard?.instantiateViewController( withIdentifier: Constants.CONTENT_DETAIL_PAGE_VIEW_CONTROLLER) as! ContentDetailPageViewController viewController.contents = parentViewController.items viewController.title = parentViewController.title viewController.contentAttemptCreationDelegate = parentViewController viewController.position = position parentViewController.present(viewController, animated: true, completion: nil) } } extension UIView { func addRoundedCorners(radius: Float) { layer.cornerRadius = 3.0 self.clipsToBounds = true } }
mit
4414b9cff99c3853af4ce5e62ed630e0
39.181818
165
0.657523
5.008499
false
false
false
false
KiranJasvanee/OnlyPictures
OnlyPictures/Classes/OnlyHorizontalPictures.swift
1
6757
// // OnlyHorizontalPictures.swift // KJBubblePictures // // Created by Karan on 28/09/17. // Copyright © 2017 KiranJasvanee. All rights reserved. // import UIKit public enum PositionOfCount { case left, right } public enum Alignment { case left, center, right } public enum RecentAt { case left, right } public class OnlyHorizontalPictures: OnlyPictures { // init override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // layout subviews when layout changes override public func layoutSubviews() { super.layoutSubviews() self.doLayoutChanges() } private func doLayoutChanges() { // Set frame of whole buuble picture self.resetLayoutBasedOnCurrentPropertyValues() } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ func resetLayoutBasedOnCurrentPropertyValues() { // OnlyPictures functions self.setGap() self.setSpacing() // OnlyHorizontalPictures functions self.setPicturesAlignment() self.setRecentAt() self.setCountPosition() } // set pictures alignment -------- public var alignment: Alignment = .center { didSet { if (self.dataSource != nil) { self.setPicturesAlignment() } } } func setPicturesAlignment() { // Remove constraints of stackview. for constraint in super.scrollView.constraints { if constraint.firstItem as! NSObject == self.stackView{ self.scrollView.removeConstraint(constraint) } } if checkSupperViewRunningOutOfBounds() { switch self.alignment { case .left, .center, .right: self.stackView.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor).isActive = true self.stackView.topAnchor.constraint(equalTo: self.scrollView.topAnchor).isActive = true self.stackView.trailingAnchor.constraint(equalTo: self.scrollView.trailingAnchor).isActive = true self.stackView.bottomAnchor.constraint(equalTo: self.scrollView.bottomAnchor).isActive = true break } self.scrollView.layoutIfNeeded() // Based on orientation change, we have to occupy new contentSize to scrollview to receive exact layout. self.scrollView.contentSize = self.stackView.bounds.size // Update scrollview contentSize switch self.alignment { case .left, .center: self.scrollView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: false) break case .right: self.scrollView.scrollRectToVisible(CGRect(x: self.scrollView.contentSize.width-1, y: self.scrollView.contentSize.height-1, width: 1, height: 1), animated: false) break } }else{ self.scrollView.contentSize = self.stackView.bounds.size // Scrollview size automatically set it's content size based on stackview bounds size increases, but when stackview size decreases it stucks at OnlyHorizontalPictures view's bounds with some extra width. So, it requires to set scrollview content size again with equal to stackview bounds size. switch self.alignment { case .left: self.stackView.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor).isActive = true self.stackView.centerYAnchor.constraint(equalTo: self.scrollView.centerYAnchor).isActive = true break case .center: self.stackView.centerXAnchor.constraint(equalTo: self.scrollView.centerXAnchor).isActive = true self.stackView.centerYAnchor.constraint(equalTo: self.scrollView.centerYAnchor).isActive = true break case .right: // scrollView's trailingAnchor will return wrong value, which will be in minus to leadingAnchor. Will result to invisible stackview. // Solution of this issue: set leadingAnchor of stackView with distance. /* <------- Self -----------> -------------------------- | distance |<-StackView->| -------------------------- */ self.stackView.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: (self.bounds.size.width-self.stackView.bounds.size.width)).isActive = true self.stackView.centerYAnchor.constraint(equalTo: self.scrollView.centerYAnchor).isActive = true break } } } func checkSupperViewRunningOutOfBounds() -> Bool{ /* If stackview width size greater than super (OnlyPictures) bounds size, it indicates scrollview content size shoulbe be activated. Activate it by replacing constraints of scrollview. */ if self.stackView.bounds.size.width >= self.bounds.size.width { return true }else{ return false } } // ----------------------------- // set recentAt ---------------- public var recentAt: RecentAt = .right { didSet { if (self.dataSource != nil) { self.setRecentAt() } } } func setRecentAt() { switch self.recentAt { case .left: self.stackviewOfImageViews.semanticContentAttribute = .forceRightToLeft break case .right: self.stackviewOfImageViews.semanticContentAttribute = .forceLeftToRight break } } // ----------------------------- // set count position ---------------- public var countPosition: PositionOfCount = .right { didSet { if (self.dataSource != nil) { self.setCountPosition() } } } func setCountPosition() { switch self.countPosition { case .left: self.stackView.semanticContentAttribute = .forceRightToLeft break case .right: self.stackView.semanticContentAttribute = .forceLeftToRight break } } // -------------------------------------------- }
mit
ce6632ff0ce9e9fb6b8f1309dac16968
34.1875
362
0.579485
5.361905
false
false
false
false
naoto0822/swift-ec-client
SwiftECClient/MasterViewController.swift
1
3885
// // MasterViewController.swift // SwiftECClient // // Created by naoto yamaguchi on 2014/06/10. // Copyright (c) 2014 naoto yamaguchi. All rights reserved. // import UIKit class MasterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIRequestDelegate { var tableView: UITableView! let requester: APIRequest! var jsonArray: NSArray = NSArray() let cellID: String = "cellID" init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.title = "Swift EC Client" self.requester = APIRequest(delegate: self) } override func viewDidLoad() { super.viewDidLoad() self.itemRequest() } func itemRequest() { self.requester.request() } override func loadView() { super.loadView() self.tableView = UITableView(frame: self.view.frame, style: .Plain) self.tableView.delegate = self self.tableView.dataSource = self self.view.addSubview(self.tableView) self.tableView.registerClass(CustomCell.classForCoder(), forCellReuseIdentifier: cellID) } func didRequest(data: NSData, responseHeaders: NSDictionary, error: NSError?) { if (error) { println("error request") } else { if let validArray: NSArray = Parser.jsonParser(data) as? NSArray { self.jsonArray = validArray dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } else { println("error json parser") } } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.jsonArray.count } func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat { return CustomCell.cellHeight() } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell: CustomCell = self.tableView.dequeueReusableCellWithIdentifier(cellID) as CustomCell let item: NSDictionary = self.jsonArray[indexPath.row] as NSDictionary cell.setItemEntity(item, indexPath: indexPath) cell.starButton.addTarget(self, action: Selector("pressStarButton:event:"), forControlEvents: .TouchUpInside) return cell } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) let item: NSDictionary = self.jsonArray[indexPath.row] as NSDictionary let urlString: String = item["Url"] as String let webBrowser: WebBrowserController = WebBrowserController(urlString: urlString) self.navigationController.pushViewController(webBrowser, animated: true) } func pressStarButton(sender: UIButton, event: UIEvent) { let indexPath: NSIndexPath = self.indexPathForControlEvent(event) let item: NSDictionary = self.jsonArray[indexPath.row] as NSDictionary println("\(item)") // core data insert ["Code"] // // } func indexPathForControlEvent(event: UIEvent) -> NSIndexPath { let touch: UITouch = event.allTouches().anyObject() as UITouch let point: CGPoint = touch.locationInView(self.tableView) let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(point) return indexPath } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
c018db7e0135ffc1606bd7d91fc57ac0
33.380531
117
0.644015
5.336538
false
false
false
false
cinnamon/MPFramework
MPFramework/Views/MPBaseButton.swift
1
835
// // MPBaseButton.swift // MPFramework // // Created by 이인재 on 2017.07.11. // Copyright © 2017 magentapink. All rights reserved. // import UIKit open class MPBaseButton: UIButton { @IBInspectable open var selectedBackgroundColor: UIColor? @IBInspectable open var highlightedBackgroundColor: UIColor? private var backgroundColorBuffer: UIColor! open override var isSelected: Bool { didSet { if backgroundColorBuffer == nil { backgroundColorBuffer = backgroundColor } backgroundColor = isSelected ? selectedBackgroundColor : backgroundColorBuffer } } open override var isHighlighted: Bool { didSet { if backgroundColorBuffer == nil { backgroundColorBuffer = backgroundColor } backgroundColor = isHighlighted ? highlightedBackgroundColor : backgroundColorBuffer } } }
apache-2.0
4017fa35da64fed8e3a9b264d6c0c1a7
21.378378
87
0.740338
4.404255
false
false
false
false
austinzheng/swift
test/Driver/Dependencies/fail-simple.swift
3
1234
/// bad ==> main | bad --> other // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-simple/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled main.swift // CHECK-FIRST: Handled bad.swift // CHECK-FIRST: Handled other.swift // RUN: touch -t 201401240006 %t/bad.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies-bad.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps // CHECK-SECOND: Handled bad.swift // CHECK-SECOND-NOT: Handled main.swift // CHECK-SECOND-NOT: Handled other.swift // CHECK-RECORD-DAG: "./bad.swift": !dirty [ // CHECK-RECORD-DAG: "./main.swift": !dirty [ // CHECK-RECORD-DAG: "./other.swift": !private [
apache-2.0
2b8b2a087d47838f809013ec709376f0
50.416667
292
0.699352
3.069652
false
false
false
false
kzaher/RxSwift
Tests/RxSwiftTests/Observable+CombineLatestTests.swift
5
59600
// // Observable+CombineLatestTests.swift // Tests // // Created by Krunoslav Zaher on 3/4/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import XCTest import RxSwift import RxTest class ObservableCombineLatestTest : RxTest { } extension ObservableCombineLatestTest { func testCombineLatest_NeverEmpty() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .completed(210) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, []) XCTAssertEqual(e0.subscriptions, [Subscription(200, 1000)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 210)]) } } func testCombineLatest_EmptyNever() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .completed(210) ]) let e1 = scheduler.createHotObservable([ .next(150, 1) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, []) XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 1000)]) } } func testCombineLatest_EmptyReturn() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .completed(210) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(220) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.completed(215)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 215)]) } } func testCombineLatest_ReturnEmpty() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(220) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .completed(210) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.completed(215)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 215)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 210)]) } } func testCombineLatest_NeverReturn() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(220) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, []) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 1000)]) } } func testCombineLatest_ReturnNever() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(220) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, []) XCTAssertEqual(e0.subscriptions, [Subscription(200, 1000)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ReturnReturn1() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(220, 3), .completed(240) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.next(220, (2 + 3)), .completed(240)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 240)]) } } func testCombineLatest_ReturnReturn2() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(220, 3), .completed(240) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(230) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.next(220, (2 + 3)), .completed(240)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 240)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)]) } } func testCombineLatest_EmptyError() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ErrorEmpty() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .completed(230) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ReturnThrow() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(210, 2), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ThrowReturn() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(210, 2), .completed(230) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ThrowThrow1() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError1), ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(230, testError2), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError1)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ThrowThrow2() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .error(230, testError1), ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError2), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError2)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ErrorThrow() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(210, 2), .error(220, testError1), ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(230, testError2), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError1)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ThrowError() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .error(230, testError2), ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(210, 2), .error(220, testError1), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError1)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_SomeThrow() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ThrowSome() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError), ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(230) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(220, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ThrowAfterCompleteLeft() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(220) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(230, testError), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(230, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)]) } } func testCombineLatest_ThrowAfterCompleteRight() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .error(230, testError), ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(220) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(230, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_TestInterleavedWithTail() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .next(225, 4), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(220, 3), .next(230, 5), .next(235, 6), .next(240, 7), .completed(250) ]) let res = scheduler.start { factory(e0, e1) } let messages = Recorded.events( .next(220, 2 + 3), .next(225, 3 + 4), .next(230, 4 + 5), .next(235, 4 + 6), .next(240, 4 + 7), .completed(250) ) XCTAssertEqual(res.events, messages) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 250)]) } } func testCombineLatest_Consecutive() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .next(225, 4), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(235, 6), .next(240, 7), .completed(250) ]) let res = scheduler.start { factory(e0, e1) } let messages = Recorded.events( .next(235, 4 + 6), .next(240, 4 + 7), .completed(250) ) XCTAssertEqual(res.events, messages) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 250)]) } } func testCombineLatest_ConsecutiveEndWithErrorLeft() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .next(225, 4), .error(230, testError) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(235, 6), .next(240, 7), .completed(250) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [.error(230, testError)]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)]) } } func testCombineLatest_ConsecutiveEndWithErrorRight() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable.combineLatest(e0, e1) { x1, x2 in x1 + x2 } }, { e0, e1 in Observable.combineLatest(e0, e1).map { x1, x2 in x1 + x2 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .next(225, 4), .completed(250) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(235, 6), .next(240, 7), .error(245, testError) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .next(235, 4 + 6), .next(240, 4 + 7), .error(245, testError) ] as [Recorded<Event<Int>>]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 245)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 245)]) } } #if TRACE_RESOURCES func testCombineLatestReleasesResourcesOnComplete1() { _ = Observable.combineLatest(Observable.just(1), Observable.just(1)).subscribe() } func testCombineLatestReleasesResourcesOnComplete2() { _ = Observable.combineLatest(Observable.just(1), Observable.just(1), resultSelector: +).subscribe() } func testCombineLatestReleasesResourcesOnError1() { _ = Observable.combineLatest(Observable.just(1), Observable<Int>.error(testError)).subscribe() } func testCombineLatestReleasesResourcesOnError2() { _ = Observable.combineLatest(Observable.just(1), Observable.error(testError), resultSelector: +).subscribe() } #endif } extension ObservableCombineLatestTest { func testCombineLatest_DeadlockErrorAfterN() { var nEvents = 0 let observable = Observable.combineLatest( Observable.concat([Observable.of(0, 1, 2), Observable.error(testError)]), Observable.of(0, 1, 2) ) { $0 + $1 } _ = observable.subscribe(onError: { _ in nEvents += 1 }) XCTAssertEqual(nEvents, 1) } func testCombineLatest_DeadlockErrorImmediately() { var nEvents = 0 let observable = Observable.combineLatest( Observable.error(testError), Observable.of(0, 1, 2) ) { $0 + $1 } _ = observable.subscribe(onError: { n in nEvents += 1 }) XCTAssertEqual(nEvents, 1) } func testReplay_DeadlockEmpty() { var nEvents = 0 let observable = Observable.combineLatest( Observable.empty(), Observable.of(0, 1, 2) ) { $0 + $1 } _ = observable.subscribe(onCompleted: { nEvents += 1 }) XCTAssertEqual(nEvents, 1) } #if TRACE_RESOURCES func testCombineLatestReleasesResourcesOnComplete() { _ = Observable.combineLatest(Observable.just(1), Observable.just(1), resultSelector: +).subscribe() } func testCombineLatestReleasesResourcesOnError() { _ = Observable.combineLatest(Observable.just(1), Observable<Int>.error(testError), resultSelector: +).subscribe() } #endif } extension ObservableCombineLatestTest { func testCombineLatest_emptyArrayN() { let factories: [() -> Observable<Int>] = [ { Observable<Int>.combineLatest(([] as [Observable<Int>]).map { $0.asObservable() }).map { $0.reduce(0, +) } }, { Observable.combineLatest(([] as [Observable<Int>]).map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let res = scheduler.start { factory() } XCTAssertEqual(res.events, [ .next(200, 0), .completed(200) ]) } } func testCombineLatest_NeverN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1, e2 in Observable<Int>.combineLatest([e0, e1, e2].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1, e2 in Observable.combineLatest([e0, e1, e2].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1) ]) let e1 = scheduler.createHotObservable([ .next(150, 1) ]) let e2 = scheduler.createHotObservable([ .next(150, 1) ]) let res = scheduler.start { factory(e0, e1, e2) } XCTAssertEqual(res.events, []) XCTAssertEqual(e0.subscriptions, [Subscription(200, 1000)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 1000)]) XCTAssertEqual(e2.subscriptions, [Subscription(200, 1000)]) } } func testCombineLatest_NeverEmptyN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .completed(210) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, []) XCTAssertEqual(e0.subscriptions, [Subscription(200, 1000)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 210)]) } } func testCombineLatest_EmptyNeverN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .completed(210) ]) let e1 = scheduler.createHotObservable([ .next(150, 1) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, []) XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 1000)]) } } func testCombineLatest_EmptyReturnN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .completed(210) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(220) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .completed(215) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 215)]) } } func testCombineLatest_ReturnReturnN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(220, 3), .completed(240) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .next(220, 2 + 3), .completed(240) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 240)]) } } func testCombineLatest_EmptyErrorN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .error(220, testError) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ReturnErrorN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(210, 2), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .error(220, testError) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ErrorErrorN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError1) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(230, testError2), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .error(220, testError1) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_NeverErrorN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError2), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .error(220, testError2) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_SomeErrorN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(220, testError2), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .error(220, testError2) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } } func testCombineLatest_ErrorAfterCompletedN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(220) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .error(230, testError2), ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .error(230, testError2) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)]) } } func testCombineLatest_InterleavedWithTailN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .next(225, 4), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(220, 3), .next(230, 5), .next(235, 6), .next(240, 7), .completed(250) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .next(220, 2 + 3), .next(225, 3 + 4), .next(230, 4 + 5), .next(235, 4 + 6), .next(240, 4 + 7), .completed(250) ] as [Recorded<Event<Int>>]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 250)]) } } func testCombineLatest_ConsecutiveN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .next(225, 4), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(235, 6), .next(240, 7), .completed(250) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .next(235, 4 + 6), .next(240, 4 + 7), .completed(250) ] as [Recorded<Event<Int>>]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 250)]) } } func testCombineLatest_ConsecutiveNWithErrorLeft() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .next(225, 4), .error(230, testError) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(235, 6), .next(240, 7), .completed(250) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .error(230, testError) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)]) } } func testCombineLatest_ConsecutiveNWithErrorRight() { let factories: [(TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1 in Observable<Int>.combineLatest([e0, e1].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1 in Observable.combineLatest([e0, e1].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .next(225, 4), .completed(250) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(235, 6), .next(240, 7), .error(245, testError) ]) let res = scheduler.start { factory(e0, e1) } XCTAssertEqual(res.events, [ .next(235, 4 + 6), .next(240, 4 + 7), .error(245, testError) ] as [Recorded<Event<Int>>]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 245)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 245)]) } } func testCombineLatest_SelectorThrowsN() { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(215, 2), .completed(230) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(220, 3), .completed(240) ]) let res = scheduler.start { Observable .combineLatest([e0, e1] .map { $0.asObservable() }) { _ -> Int in throw testError } } XCTAssertEqual(res.events, [ .error(220, testError) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)]) } func testCombineLatest_willNeverBeAbleToCombineN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1, e2 in Observable<Int>.combineLatest([e0, e1, e2].map { $0.asObservable() }).map { _ in 42 } }, { e0, e1, e2 in Observable.combineLatest([e0, e1, e2].map { $0.asObservable() }) { _ in 42 } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .completed(250) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .completed(260) ]) let e2 = scheduler.createHotObservable([ .next(150, 1), .next(500, 2), .completed(800) ]) let res = scheduler.start { factory(e0, e1, e2) } XCTAssertEqual(res.events, [ .completed(500) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 260)]) XCTAssertEqual(e2.subscriptions, [Subscription(200, 500)]) } } func testCombineLatest_typicalN() { let factories: [(TestableObservable<Int>, TestableObservable<Int>, TestableObservable<Int>) -> Observable<Int>] = [ { e0, e1, e2 in Observable<Int>.combineLatest([e0, e1, e2].map { $0.asObservable() }).map { $0.reduce(0, +) } }, { e0, e1, e2 in Observable.combineLatest([e0, e1, e2].map { $0.asObservable() }) { $0.reduce(0, +) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(210, 1), .next(410, 4), .completed(800) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(220, 2), .next(420, 5), .completed(800) ]) let e2 = scheduler.createHotObservable([ .next(150, 1), .next(230, 3), .next(430, 6), .completed(800) ]) let res = scheduler.start { factory(e0, e1, e2) } XCTAssertEqual(res.events, [ .next(230, 6), .next(410, 9), .next(420, 12), .next(430, 15), .completed(800) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 800)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 800)]) XCTAssertEqual(e2.subscriptions, [Subscription(200, 800)]) } } func testCombineLatest_NAry_symmetric() { let factories: [(TestableObservable<Int>, TestableObservable<Int>, TestableObservable<Int>) -> Observable<EquatableArray<Int>>] = [ { e0, e1, e2 in Observable<Int>.combineLatest([e0, e1, e2].map { $0.asObservable() }).map { EquatableArray($0) } }, { e0, e1, e2 in Observable.combineLatest([e0, e1, e2].map { $0.asObservable() }) { EquatableArray($0) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(210, 1), .next(250, 4), .completed(420) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(220, 2), .next(240, 5), .completed(410) ]) let e2 = scheduler.createHotObservable([ .next(150, 1), .next(230, 3), .next(260, 6), .completed(400) ]) let res = scheduler.start { factory(e0, e1, e2) } XCTAssertEqual(res.events, [ .next(230, EquatableArray([1, 2, 3])), .next(240, EquatableArray([1, 5, 3])), .next(250, EquatableArray([4, 5, 3])), .next(260, EquatableArray([4, 5, 6])), .completed(420) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 420)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 410)]) XCTAssertEqual(e2.subscriptions, [Subscription(200, 400)]) } } func testCombineLatest_NAry_asymmetric() { let factories: [(TestableObservable<Int>, TestableObservable<Int>, TestableObservable<Int>) -> Observable<EquatableArray<Int>>] = [ { e0, e1, e2 in Observable<Int>.combineLatest([e0, e1, e2].map { $0.asObservable() }).map { EquatableArray($0) } }, { e0, e1, e2 in Observable.combineLatest([e0, e1, e2].map { $0.asObservable() }) { EquatableArray($0) } }, ] for factory in factories { let scheduler = TestScheduler(initialClock: 0) let e0 = scheduler.createHotObservable([ .next(150, 1), .next(210, 1), .next(250, 4), .completed(270) ]) let e1 = scheduler.createHotObservable([ .next(150, 1), .next(220, 2), .next(240, 5), .next(290, 7), .next(310, 9), .completed(410) ]) let e2 = scheduler.createHotObservable([ .next(150, 1), .next(230, 3), .next(260, 6), .next(280, 8), .completed(300) ]) let res = scheduler.start { factory(e0, e1, e2) } XCTAssertEqual(res.events, [ .next(230, EquatableArray([1, 2, 3])), .next(240, EquatableArray([1, 5, 3])), .next(250, EquatableArray([4, 5, 3])), .next(260, EquatableArray([4, 5, 6])), .next(280, EquatableArray([4, 5, 8])), .next(290, EquatableArray([4, 7, 8])), .next(310, EquatableArray([4, 9, 8])), .completed(410) ]) XCTAssertEqual(e0.subscriptions, [Subscription(200, 270)]) XCTAssertEqual(e1.subscriptions, [Subscription(200, 410)]) XCTAssertEqual(e2.subscriptions, [Subscription(200, 300)]) } } #if TRACE_RESOURCES func testCombineLatestArrayReleasesResourcesOnComplete1() { _ = Observable.combineLatest([Observable.just(1), Observable.just(1)]) { $0.reduce(0, +) }.subscribe() } func testCombineLatestArrayReleasesResourcesOnError1() { _ = Observable.combineLatest([Observable<Int>.error(testError), Observable.just(1)]) { $0.reduce(0, +) }.subscribe() } func testCombineLatestArrayReleasesResourcesOnComplete2() { _ = Observable<Int>.combineLatest([Observable.just(1), Observable.just(1)]).subscribe() } func testCombineLatestArrayReleasesResourcesOnError2() { _ = Observable<Int>.combineLatest([Observable<Int>.error(testError), Observable.just(1)]).subscribe() } #endif }
mit
11da5698ff15bdf296afd793c9765341
33.331221
137
0.465092
4.711383
false
true
false
false
simplymadeapps/SMASaveSystem
Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift
4
5365
// // ChaCha20.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 25/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // final public class ChaCha20: BlockCipher { public enum Error: ErrorType { case MissingContext } static let blockSize = 64 // 512 / 8 private let stateSize = 16 private var context:Context? final private class Context { var input:Array<UInt32> = Array<UInt32>(count: 16, repeatedValue: 0) deinit { for i in 0..<input.count { input[i] = 0x00; } } } public init?(key:Array<UInt8>, iv:Array<UInt8>) { if let c = contextSetup(iv: iv, key: key) { context = c } else { return nil } } private final func wordToByte(input:Array<UInt32> /* 64 */) -> Array<UInt8>? /* 16 */ { if (input.count != stateSize) { return nil; } var x = input for _ in 0..<10 { quarterround(&x[0], &x[4], &x[8], &x[12]) quarterround(&x[1], &x[5], &x[9], &x[13]) quarterround(&x[2], &x[6], &x[10], &x[14]) quarterround(&x[3], &x[7], &x[11], &x[15]) quarterround(&x[0], &x[5], &x[10], &x[15]) quarterround(&x[1], &x[6], &x[11], &x[12]) quarterround(&x[2], &x[7], &x[8], &x[13]) quarterround(&x[3], &x[4], &x[9], &x[14]) } var output = Array<UInt8>() output.reserveCapacity(16) for i in 0..<16 { x[i] = x[i] &+ input[i] output.appendContentsOf(x[i].bytes().reverse()) } return output; } private func contextSetup(iv iv:Array<UInt8>, key:Array<UInt8>) -> Context? { let ctx = Context() let kbits = key.count * 8 if (kbits != 128 && kbits != 256) { return nil } // 4 - 8 for i in 0..<4 { let start = i * 4 ctx.input[i + 4] = wordNumber(key[start..<(start + 4)]) } var addPos = 0; switch (kbits) { case 256: addPos += 16 // sigma ctx.input[0] = 0x61707865 //apxe ctx.input[1] = 0x3320646e //3 dn ctx.input[2] = 0x79622d32 //yb-2 ctx.input[3] = 0x6b206574 //k et default: // tau ctx.input[0] = 0x61707865 //apxe ctx.input[1] = 0x3620646e //6 dn ctx.input[2] = 0x79622d31 //yb-1 ctx.input[3] = 0x6b206574 //k et break; } // 8 - 11 for i in 0..<4 { let start = addPos + (i*4) let bytes = key[start..<(start + 4)] ctx.input[i + 8] = wordNumber(bytes) } // iv ctx.input[12] = 0 ctx.input[13] = 0 ctx.input[14] = wordNumber(iv[0..<4]) ctx.input[15] = wordNumber(iv[4..<8]) return ctx } private final func encryptBytes(message:Array<UInt8>) throws -> Array<UInt8> { guard let ctx = context else { throw Error.MissingContext } var c:Array<UInt8> = Array<UInt8>(count: message.count, repeatedValue: 0) var cPos:Int = 0 var mPos:Int = 0 var bytes = message.count while (true) { if let output = wordToByte(ctx.input) { ctx.input[12] = ctx.input[12] &+ 1 if (ctx.input[12] == 0) { ctx.input[13] = ctx.input[13] &+ 1 /* stopping at 2^70 bytes per nonce is user's responsibility */ } if (bytes <= ChaCha20.blockSize) { for i in 0..<bytes { c[i + cPos] = message[i + mPos] ^ output[i] } return c } for i in 0..<ChaCha20.blockSize { c[i + cPos] = message[i + mPos] ^ output[i] } bytes -= ChaCha20.blockSize cPos += ChaCha20.blockSize mPos += ChaCha20.blockSize } } } private final func quarterround(inout a:UInt32, inout _ b:UInt32, inout _ c:UInt32, inout _ d:UInt32) { a = a &+ b d = rotateLeft((d ^ a), 16) //FIXME: WAT? n: c = c &+ d b = rotateLeft((b ^ c), 12); a = a &+ b d = rotateLeft((d ^ a), 8); c = c &+ d b = rotateLeft((b ^ c), 7); } } // MARK: Cipher extension ChaCha20: Cipher { public func encrypt(bytes:Array<UInt8>) throws -> Array<UInt8> { guard context != nil else { throw Error.MissingContext } return try encryptBytes(bytes) } public func decrypt(bytes:Array<UInt8>) throws -> Array<UInt8> { return try encrypt(bytes) } } // MARK: Helpers /// Change array to number. It's here because arrayOfBytes is too slow private func wordNumber(bytes:ArraySlice<UInt8>) -> UInt32 { var value:UInt32 = 0 for i:UInt32 in 0..<4 { let j = bytes.startIndex + Int(i) value = value | UInt32(bytes[j]) << (8 * i) } return value }
mit
e49272008f1879e9730c12b0bd2fe576
26.942708
107
0.463187
3.720527
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Models/Balance/ObservableType+MoneyValue.swift
1
698
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import RxSwift extension Observable where Element == CryptoValue { public var moneyValue: Observable<MoneyValue> { map(\.moneyValue) } } extension Observable where Element == FiatValue { public var moneyValue: Observable<MoneyValue> { map(\.moneyValue) } } extension PrimitiveSequence where Trait == SingleTrait, Element == CryptoValue { public var moneyValue: Single<MoneyValue> { map(\.moneyValue) } } extension PrimitiveSequence where Trait == SingleTrait, Element == FiatValue { public var moneyValue: Single<MoneyValue> { map(\.moneyValue) } }
lgpl-3.0
96d2da51c41f174e7e1b1be5419d0a11
23.892857
80
0.695839
4.741497
false
false
false
false
ndagrawal/TipCalculator
TipCalculator/TipCalculator/MKTableViewCell.swift
5
2392
// // MKTableViewCell.swift // MaterialKit // // Created by Le Van Nghia on 11/15/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit public class MKTableViewCell : UITableViewCell { @IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation { didSet { mkLayer.rippleLocation = rippleLocation } } @IBInspectable public var rippleAniDuration: Float = 0.75 @IBInspectable public var backgroundAniDuration: Float = 1.0 @IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear @IBInspectable public var shadowAniEnabled: Bool = true // color @IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) { didSet { mkLayer.setCircleLayerColor(rippleLayerColor) } } @IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) { didSet { mkLayer.setBackgroundLayerColor(backgroundLayerColor) } } private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.contentView.layer) private var contentViewResized = false override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayer() } private func setupLayer() { selectionStyle = .None mkLayer.setBackgroundLayerColor(backgroundLayerColor) mkLayer.setCircleLayerColor(rippleLayerColor) mkLayer.ripplePercent = 1.2 } override public func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) if let firstTouch = touches.first as? UITouch { if !contentViewResized { mkLayer.superLayerDidResize() contentViewResized = true } mkLayer.didChangeTapLocation(firstTouch.locationInView(contentView)) mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(rippleAniDuration)) mkLayer.animateAlphaForBackgroundLayer(MKTimingFunction.Linear, duration: CFTimeInterval(backgroundAniDuration)) } } }
mit
cb3739c3bcf5704a1e962d251ece4cfa
34.701493
152
0.686873
5.155172
false
false
false
false
coinbase/coinbase-ios-sdk
Tests/Support/Matchers/ResultMatchers.swift
1
1591
// // ResultMatchers.swift // CoinbaseTests // // Copyright © 2018 Coinbase, Inc. All rights reserved. // import Quick import Nimble import CoinbaseSDK func beSuccessful<T>() -> Predicate<Result<T>> { return Predicate.define { actualExpression in let msg = ExpectationMessage.expectedActualValueTo("be successful") let optActual = try actualExpression.evaluate() guard let actual = optActual else { return PredicateResult(status: .fail, message: .fail("expected a result, got <nil>")) } return PredicateResult(bool: actual.isSuccess, message: msg) } } func beFailed<T>() -> Predicate<Result<T>> { return Predicate.define { actualExpression in let msg = ExpectationMessage.expectedActualValueTo("be failed") let optActual = try actualExpression.evaluate() guard let actual = optActual else { return PredicateResult(status: .fail, message: .fail("expected a result, got <nil>")) } return PredicateResult(bool: actual.isFailure, message: msg) } } func beFailed<T, U>(with: U.Type) -> Predicate<Result<T>> { return Predicate.define { actualExpression in let msg = ExpectationMessage.expectedActualValueTo("be failed with \(U.self)") let optActual = try actualExpression.evaluate() guard let actual = optActual else { return PredicateResult(status: .fail, message: .fail("expected a result, got <nil>")) } return PredicateResult(bool: actual.isFailure && type(of: actual.error!) == U.self, message: msg) } }
apache-2.0
aa7b59d5404284b9c2cf1c6131143db1
35.976744
105
0.667925
4.453782
false
false
false
false
pablogm/CameraKit
Pod/Classes/Extensions/UIViewController+Utils.swift
1
2423
/* Copyright (c) 2015 Pablo GM <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit public typealias CancelActionPerformed = (UIAlertAction) -> () public typealias OkActionPerformed = (UIAlertAction) -> () public typealias AlertPerformed = () -> () extension UIViewController { public func showAlert(title: String, message: String, ok: String, cancel: String, cancelAction: CancelActionPerformed?, okAction: OkActionPerformed?, completion: AlertPerformed?) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) if cancelAction != nil { let cancelAction = UIAlertAction(title: cancel, style: .Cancel) { (action) in if let a = cancelAction { a(action) } } alertController.addAction(cancelAction) } let OKAction = UIAlertAction(title: ok, style: .Default) { (action) in if let a = okAction { a(action) } } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true) { if let a = completion { a() } } } }
mit
e2aa33563844529e444304226c9f9f12
38.096774
107
0.64837
5.210753
false
false
false
false
mightydeveloper/swift
test/SILGen/let_decls.swift
9
15162
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s func takeClosure(a : () -> Int) {} // Let decls don't get boxes for trivial types. // // CHECK-LABEL: sil hidden @{{.*}}test1 func test1(a : Int) -> Int { // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack let (b,c) = (a, 32) return b+c // CHECK: return } // rdar://15716277 // CHECK: @{{.*}}let_destructuring func let_destructuring() -> Int { let (a, b) = ((1,2), 5) return a.1+a.0+b } // Let decls being closed over. // // CHECK-LABEL: sil hidden @{{.*}}test2 func test2() { // No allocations. // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack let x = 42 takeClosure({x}) // CHECK: return } // The closure just returns its value, which it captured directly. // CHECK: sil shared @_TFF9let_decls5test2FT_T_U_FT_Si : $@convention(thin) (Int) -> Int // CHECK: bb0(%0 : $Int): // CHECK: return %0 : $Int // Verify that we can close over let decls of tuple type. struct RegularStruct { var a: Int } func testTupleLetCapture() { let t = (RegularStruct(a: 41), 42) takeClosure( { t.0.a }) } func getAString() -> String { return "" } func useAString(a : String) {} // rdar://15689514 - Verify that the cleanup for the let decl runs at the end of // the 'let' lifetime, not at the end of the initializing expression. // // CHECK-LABEL: sil hidden @{{.*}}test3 func test3() { // CHECK: [[GETFN:%[0-9]+]] = function_ref{{.*}}getAString // CHECK-NEXT: [[STR:%[0-9]+]] = apply [[GETFN]]() let o = getAString() // CHECK-NOT: release_value // CHECK: [[USEFN:%[0-9]+]] = function_ref{{.*}}useAString // CHECK-NEXT: retain_value [[STR]] // CHECK-NEXT: [[USE:%[0-9]+]] = apply [[USEFN]]([[STR]]) useAString(o) // CHECK: release_value [[STR]] } struct AddressOnlyStruct<T> { var elt : T var str : String } func produceAddressOnlyStruct<T>(x : T) -> AddressOnlyStruct<T> {} // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyStructString func testAddressOnlyStructString<T>(a : T) -> String { return produceAddressOnlyStruct(a).str // CHECK: [[PRODFN:%[0-9]+]] = function_ref @{{.*}}produceAddressOnlyStruct // CHECK: [[TMPSTRUCT:%[0-9]+]] = alloc_stack $AddressOnlyStruct<T> // CHECK: apply [[PRODFN]]<T>([[TMPSTRUCT]]#1, // CHECK-NEXT: [[STRADDR:%[0-9]+]] = struct_element_addr [[TMPSTRUCT]]#1 : $*AddressOnlyStruct<T>, #AddressOnlyStruct.str // CHECK-NEXT: [[STRVAL:%[0-9]+]] = load [[STRADDR]] // CHECK-NEXT: retain_value [[STRVAL]] // CHECK-NEXT: destroy_addr [[TMPSTRUCT]] // CHECK-NEXT: dealloc_stack [[TMPSTRUCT]] // CHECK: return [[STRVAL]] } // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyStructElt func testAddressOnlyStructElt<T>(a : T) -> T { return produceAddressOnlyStruct(a).elt // CHECK: [[PRODFN:%[0-9]+]] = function_ref @{{.*}}produceAddressOnlyStruct // CHECK: [[TMPSTRUCT:%[0-9]+]] = alloc_stack $AddressOnlyStruct<T> // CHECK: apply [[PRODFN]]<T>([[TMPSTRUCT]]#1, // CHECK-NEXT: [[ELTADDR:%[0-9]+]] = struct_element_addr [[TMPSTRUCT]]#1 : $*AddressOnlyStruct<T>, #AddressOnlyStruct.elt // CHECK-NEXT: copy_addr [[ELTADDR]] to [initialization] %0 : $*T // CHECK-NEXT: destroy_addr [[TMPSTRUCT]] } // rdar://15717123 - let decls of address-only type. // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyLet func testAddressOnlyLet<T>(a : T) { let x = produceAddressOnlyStruct(a) } func produceSubscriptableRValue() -> [String] {} // CHECK-LABEL: sil hidden @{{.*}}subscriptRValue func subscriptRValue() { var a = produceSubscriptableRValue()[0] } struct GetOnlySubscriptStruct { // get-only subscript subscript (i : Int) -> Int { get {} } } // CHECK-LABEL: sil hidden @{{.*}}testGetOnlySubscript func testGetOnlySubscript(x : GetOnlySubscriptStruct, idx : Int) -> Int { return x[idx] // CHECK: [[SUBFN:%[0-9]+]] = function_ref @{{.*}}g9subscript // CHECK-NEXT: [[CALL:%[0-9]+]] = apply [[SUBFN]]( // CHECK: return [[CALL]] } // Address-only let's get captured by box. extension Optional { func getLV() -> Int { } } struct CloseOverAddressOnlyConstant<T> { func isError() { let AOV = Optional<T>() takeClosure({ AOV.getLV() }) } } // CHECK-LABEL: sil hidden @{{.*}}callThroughLet func callThroughLet(predicate: (Int, Int) -> Bool) { let p = predicate if p(1, 2) { } } // Verify that we can emit address-only rvalues directly into the result slot in // chained calls. struct GenericTestStruct<T> { func pass_address_only_rvalue_result(i: Int) -> T { return self[i] } subscript (i : Int) -> T { get {} set {} } } // CHECK-LABEL: sil hidden @{{.*}}pass_address_only_rvalue_result // CHECK: bb0(%0 : $*T, // CHECK: [[FN:%[0-9]+]] = function_ref @{{.*}}GenericTestStructg9subscript // CHECK: apply [[FN]]<T>(%0, struct NonMutableSubscriptable { subscript(x : Int) -> Int { get {} nonmutating set {} } } func produceNMSubscriptableRValue() -> NonMutableSubscriptable {} // CHECK-LABEL: sil hidden @{{.*}}test_nm_subscript_get // CHECK: bb0(%0 : $Int): // CHECK: [[FR1:%[0-9]+]] = function_ref @{{.*}}produceNMSubscriptableRValue // CHECK-NEXT: [[RES:%[0-9]+]] = apply [[FR1]]() // CHECK: [[GETFN:%[0-9]+]] = function_ref @_TFV9let_decls23NonMutableSubscriptableg9subscript // CHECK-NEXT: [[RES2:%[0-9]+]] = apply [[GETFN]](%0, [[RES]]) // CHECK-NEXT: return [[RES2]] func test_nm_subscript_get(a : Int) -> Int { return produceNMSubscriptableRValue()[a] } // CHECK-LABEL: sil hidden @{{.*}}test_nm_subscript_set // CHECK: bb0(%0 : $Int): // CHECK: [[FR1:%[0-9]+]] = function_ref @{{.*}}produceNMSubscriptableRValue // CHECK-NEXT: [[RES:%[0-9]+]] = apply [[FR1]]() // CHECK: [[SETFN:%[0-9]+]] = function_ref @_TFV9let_decls23NonMutableSubscriptables9subscript // CHECK-NEXT: [[RES2:%[0-9]+]] = apply [[SETFN]](%0, %0, [[RES]]) func test_nm_subscript_set(a : Int) { produceNMSubscriptableRValue()[a] = a } struct WeirdPropertyTest { // This property has a mutating getter and !mutating setter. var p : Int { mutating get {} nonmutating set {} } } // CHECK-LABEL: sil hidden @{{.*}}test_weird_property func test_weird_property(v : WeirdPropertyTest, i : Int) -> Int { var v = v // CHECK: [[VBOX:%[0-9]+]] = alloc_box $WeirdPropertyTest // CHECK: store %0 to [[VBOX]]#1 // The setter isn't mutating, so we need to load the box. // CHECK: [[VVAL:%[0-9]+]] = load [[VBOX]]#1 // CHECK: [[SETFN:%[0-9]+]] = function_ref @_TFV9let_decls17WeirdPropertyTests1pSi // CHECK: apply [[SETFN]](%1, [[VVAL]]) v.p = i // The getter is mutating, so it takes the box address. // CHECK: [[GETFN:%[0-9]+]] = function_ref @_TFV9let_decls17WeirdPropertyTestg1pSi // CHECK-NEXT: [[RES:%[0-9]+]] = apply [[GETFN]]([[VBOX]]#1) // CHECK: return [[RES]] return v.p } // CHECK-LABEL: sil hidden @{{.*}}generic_identity // CHECK: bb0(%0 : $*T, %1 : $*T): // CHECK-NEXT: debug_value_addr %1 : $*T // CHECK-NEXT: copy_addr [take] %1 to [initialization] %0 : $*T // CHECK-NEXT: %4 = tuple () // CHECK-NEXT: return %4 func generic_identity<T>(a : T) -> T { // Should be a single copy_addr, with no temporary. return a } struct StaticLetMember { static let x = 5 } // CHECK-LABEL: sil hidden @{{.*}}testStaticLetMember func testStaticLetMember() -> Int { // CHECK: function_ref @{{.*}}StaticLetMemberau1xSi // CHECK: load {{.*}} : $*Int // CHECK-NEXT: return return StaticLetMember.x } protocol SimpleProtocol { func doSomethingGreat() } // Verify that no temporaries+copies are produced when calling non-@mutable // methods on protocol and archetypes calls. // CHECK-LABEL: sil hidden @{{.*}}testLetProtocolBases // CHECK: bb0(%0 : $*SimpleProtocol): func testLetProtocolBases(p : SimpleProtocol) { // CHECK-NEXT: debug_value_addr // CHECK-NEXT: open_existential_addr // CHECK-NEXT: witness_method // CHECK-NEXT: apply p.doSomethingGreat() // CHECK-NEXT: open_existential_addr // CHECK-NEXT: witness_method // CHECK-NEXT: apply p.doSomethingGreat() // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: tuple // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @{{.*}}testLetArchetypeBases // CHECK: bb0(%0 : $*T): func testLetArchetypeBases<T : SimpleProtocol>(p : T) { // CHECK-NEXT: debug_value_addr // CHECK-NEXT: witness_method $T // CHECK-NEXT: apply p.doSomethingGreat() // CHECK-NEXT: witness_method $T // CHECK-NEXT: apply p.doSomethingGreat() // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: tuple // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @{{.*}}testDebugValue // CHECK: bb0(%0 : $Int, %1 : $*SimpleProtocol): // CHECK-NEXT: debug_value %0 : $Int // let a // CHECK-NEXT: debug_value_addr %1 : $*SimpleProtocol // let b func testDebugValue(a : Int, b : SimpleProtocol) -> Int { // CHECK-NEXT: debug_value %0 : $Int // let x let x = a // CHECK: apply b.doSomethingGreat() // CHECK: destroy_addr // CHECK: return %0 return x } // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyTupleArgument func testAddressOnlyTupleArgument(bounds: (start: SimpleProtocol, pastEnd: Int)) { // CHECK: bb0(%0 : $*SimpleProtocol, %1 : $Int): // CHECK-NEXT: %2 = alloc_stack $(start: SimpleProtocol, pastEnd: Int) // let bounds // CHECK-NEXT: %3 = tuple_element_addr %2#1 : $*(start: SimpleProtocol, pastEnd: Int), 0 // CHECK-NEXT: copy_addr [take] %0 to [initialization] %3 : $*SimpleProtocol // CHECK-NEXT: %5 = tuple_element_addr %2#1 : $*(start: SimpleProtocol, pastEnd: Int), 1 // CHECK-NEXT: store %1 to %5 : $*Int // CHECK-NEXT: debug_value_addr %2 // CHECK-NEXT: destroy_addr %2#1 : $*(start: SimpleProtocol, pastEnd: Int) // CHECK-NEXT: dealloc_stack %2#0 : $*@local_storage (start: SimpleProtocol, pastEnd: Int) } func address_only_let_closure<T>(x:T) -> T { return { { x }() }() } struct GenericFunctionStruct<T, U> { var f: T -> U } // CHECK-LABEL: sil hidden @{{.*}}member_ref_abstraction_change // CHECK: function_ref reabstraction thunk helper // CHECK: return func member_ref_abstraction_change(x: GenericFunctionStruct<Int, Int>) -> Int -> Int { return x.f } // CHECK-LABEL: sil hidden @{{.*}}call_auto_closure // CHECK: apply %0() func call_auto_closure(@autoclosure x: () -> Bool) -> Bool { return x() // Calls of autoclosures should be marked transparent. } class SomeClass {} struct AnotherStruct { var i : Int var c : SomeClass } struct StructMemberTest { var c : SomeClass var i = 42 var s : AnotherStruct var t : (Int, AnotherStruct) // rdar://15867140 - Accessing the int member here should not retain the // whole struct. func testIntMemberLoad() -> Int { return i } // CHECK-LABEL: sil hidden @{{.*}}testIntMemberLoad{{.*}} : $@convention(method) (@guaranteed StructMemberTest) // CHECK: bb0(%0 : $StructMemberTest): // CHECK: debug_value %0 : $StructMemberTest // let self // CHECK: %2 = struct_extract %0 : $StructMemberTest, #StructMemberTest.i // CHECK-NOT: release_value %0 : $StructMemberTest // CHECK: return %2 : $Int // Accessing the int member in s should not retain the whole struct. func testRecursiveIntMemberLoad() -> Int { return s.i } // CHECK-LABEL: sil hidden @{{.*}}testRecursiveIntMemberLoad{{.*}} : $@convention(method) (@guaranteed StructMemberTest) // CHECK: bb0(%0 : $StructMemberTest): // CHECK: debug_value %0 : $StructMemberTest // let self // CHECK: %2 = struct_extract %0 : $StructMemberTest, #StructMemberTest.s // CHECK: %3 = struct_extract %2 : $AnotherStruct, #AnotherStruct.i // CHECK-NOT: release_value %0 : $StructMemberTest // CHECK: return %3 : $Int func testTupleMemberLoad() -> Int { return t.1.i } // CHECK-LABEL: sil hidden @{{.*}}testTupleMemberLoad{{.*}} : $@convention(method) (@guaranteed StructMemberTest) // CHECK: bb0(%0 : $StructMemberTest): // CHECK-NEXT: debug_value %0 : $StructMemberTest // let self // CHECK-NEXT: [[T0:%.*]] = struct_extract %0 : $StructMemberTest, #StructMemberTest.t // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : $(Int, AnotherStruct), 0 // CHECK-NEXT: [[T2:%.*]] = tuple_extract [[T0]] : $(Int, AnotherStruct), 1 // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T2]] : $AnotherStruct, #AnotherStruct.i // CHECK-NEXT: return [[T3]] : $Int } struct GenericStruct<T> { var a : T var b : Int func getA() -> T { return a } // CHECK-LABEL: sil hidden @{{.*}}GenericStruct4getA{{.*}} : $@convention(method) <T> (@out T, @in_guaranteed GenericStruct<T>) // CHECK: bb0(%0 : $*T, %1 : $*GenericStruct<T>): // CHECK-NEXT: debug_value_addr %1 : $*GenericStruct<T> // let self // CHECK-NEXT: %3 = struct_element_addr %1 : $*GenericStruct<T>, #GenericStruct.a // CHECK-NEXT: copy_addr %3 to [initialization] %0 : $*T // CHECK-NEXT: %5 = tuple () // CHECK-NEXT: return %5 : $() func getB() -> Int { return b } // CHECK-LABEL: sil hidden @{{.*}}GenericStruct4getB{{.*}} : $@convention(method) <T> (@in_guaranteed GenericStruct<T>) -> Int // CHECK: bb0(%0 : $*GenericStruct<T>): // CHECK-NEXT: debug_value_addr %0 : $*GenericStruct<T> // let self // CHECK-NEXT: %2 = struct_element_addr %0 : $*GenericStruct<T>, #GenericStruct.b // CHECK-NEXT: %3 = load %2 : $*Int // CHECK-NOT: destroy_addr %0 : $*GenericStruct<T> // CHECK-NEXT: return %3 : $Int } // rdar://15877337 struct LetPropertyStruct { let lp : Int } // CHECK-LABEL: sil hidden @{{.*}}testLetPropertyAccessOnLValueBase // CHECK: bb0(%0 : $LetPropertyStruct): // CHECK: [[ABOX:%[0-9]+]] = alloc_box $LetPropertyStruct // CHECK: store %0 to [[ABOX]]#1 : $*LetPropertyStruct // CHECK: [[A:%[0-9]+]] = load [[ABOX]]#1 : $*LetPropertyStruct // CHECK: [[LP:%[0-9]+]] = struct_extract [[A]] : $LetPropertyStruct, #LetPropertyStruct.lp // CHECK: strong_release [[ABOX]]#0 : $@box LetPropertyStruct // CHECK: return [[LP]] : $Int func testLetPropertyAccessOnLValueBase(a : LetPropertyStruct) -> Int { var a = a return a.lp } var addressOnlyGetOnlyGlobalProperty : SimpleProtocol { get {} } // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyGetOnlyGlobalProperty // CHECK: bb0(%0 : $*SimpleProtocol): // CHECK-NEXT: // function_ref // CHECK-NEXT: %1 = function_ref @{{.*}}addressOnlyGetOnlyGlobalProperty // CHECK-NEXT: %2 = apply %1(%0) : $@convention(thin) (@out SimpleProtocol) -> () // CHECK-NEXT: %3 = tuple () // CHECK-NEXT: return %3 : $() // CHECK-NEXT: } func testAddressOnlyGetOnlyGlobalProperty() -> SimpleProtocol { return addressOnlyGetOnlyGlobalProperty } // rdar://15962740 struct LetDeclInStruct { let immutable: Int init() { immutable = 1 } } // rdar://19854166 - Swift 1.2 uninitialized constant causes crash // The destroy_addr for a let stack temporary should be generated against // mark_uninitialized instruction, so DI will see it. func test_unassigned_let_constant() { let string : String } // CHECK: [[S:%[0-9]+]] = alloc_stack $String // let string // CHECK-NEXT: [[MUI:%[0-9]+]] = mark_uninitialized [var] [[S]]#1 : $*String // CHECK-NEXT: destroy_addr [[MUI]] : $*String // CHECK-NEXT: dealloc_stack [[S]]#0 : $*@local_storage String
apache-2.0
327afb2777fe76b2b31116cd591f0e0b
29.083333
129
0.634943
3.291079
false
true
false
false
exchangegroup/FitLoader
FitLoader/TegReachabilityMessage.swift
2
1840
import UIKit import Dodo class TegReachabilityMessage { weak var delegate: TegReachabilityMessageDelegate? /// Shows an expected error message with a close button. func showWithCloseButton(message: String?, inViewController viewController: TegReachableViewController) { let actualMessage = message ?? TegReachabilityConstants.errorMessages.unexpectedResponse show(actualMessage, inViewController: viewController, withIcon: .Close) } /// Show "No Internet connection" message with no button func noInternet(viewController: TegReachableViewController) { show(TegReachabilityConstants.errorMessages.noInternet, inViewController: viewController, withIcon: nil) } /// Show an unexpected message with a reload icon func showWithReloadButton(message: String, inViewController viewController: TegReachableViewController) { show(message, inViewController: viewController, withIcon: .Reload) } func hide(viewController: TegReachableViewController) { viewController.view.dodo.hide() } private func show(message: String, inViewController viewController: TegReachableViewController, withIcon icon: DodoIcons?) { let view = viewController.view view.dodo.topLayoutGuide = viewController.topLayoutGuide view.dodo.bottomLayoutGuide = viewController.bottomLayoutGuide view.dodo.style.leftButton.icon = nil view.dodo.style.leftButton.onTap = nil if let icon = icon { view.dodo.style.leftButton.icon = icon switch icon { case .Reload: view.dodo.style.leftButton.onTap = { [weak self] in self?.delegate?.tegReachabilityMessageDelegate_didTapReloadButton() } case .Close: view.dodo.style.leftButton.hideOnTap = true } } view.dodo.error(message) } }
mit
37c757b6f3d53d40f25f5980b6fe23ef
31.875
97
0.727717
4.946237
false
false
false
false
chinlam91/edx-app-ios
Source/HTMLBlockViewController.swift
2
2656
// // HTMLBlockViewController.swift // edX // // Created by Akiva Leffert on 5/26/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit public class HTMLBlockViewController: UIViewController, CourseBlockViewController, PreloadableBlockController { public struct Environment { let config : OEXConfig? let courseDataManager : CourseDataManager let session : OEXSession? let styles : OEXStyles } public let courseID : String public let blockID : CourseBlockID? private let webController : AuthenticatedWebViewController private let loader = BackedStream<CourseBlock>() private let courseQuerier : CourseOutlineQuerier public init(blockID : CourseBlockID?, courseID : String, environment : Environment) { self.courseID = courseID self.blockID = blockID let authEnvironment = AuthenticatedWebViewController.Environment(config : environment.config, session : environment.session, styles : environment.styles) webController = AuthenticatedWebViewController(environment: authEnvironment) courseQuerier = environment.courseDataManager.querierForCourseWithID(courseID) super.init(nibName : nil, bundle : nil) addChildViewController(webController) webController.didMoveToParentViewController(self) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() view.addSubview(webController.view) } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) loadData() } private func loadData() { if !loader.hasBacking { loader.backWithStream(courseQuerier.blockWithID(self.blockID).firstSuccess()) loader.listen (self, success : {[weak self] block in if let url = block.blockURL { let graded = block.graded ?? false self?.webController.headerView = graded ? GradedSectionMessageView() : nil let request = NSURLRequest(URL: url) self?.webController.loadRequest(request) } else { self?.webController.showError(nil) } }, failure : {[weak self] error in self?.webController.showError(error) }) } } public func preloadData() { let _ = self.view loadData() } }
apache-2.0
5afda468b278fe1bd8c65ade94e4e3d5
32.2
161
0.625377
5.615222
false
false
false
false