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
matteobruni/OAuthSwift
Sources/OAuthSwiftURLHandlerType.swift
1
5533
// // OAuthSwiftURLHandlerType.swift // OAuthSwift // // Created by phimage on 11/05/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation #if os(iOS) || os(tvOS) import UIKit #elseif os(watchOS) import WatchKit #elseif os(OSX) import AppKit #endif @objc public protocol OAuthSwiftURLHandlerType { func handle(_ url: URL) } // MARK: Open externally open class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType { public static var sharedInstance: OAuthSwiftOpenURLExternally = OAuthSwiftOpenURLExternally() @objc open func handle(_ url: URL) { #if os(iOS) || os(tvOS) #if !OAUTH_APP_EXTENSIONS UIApplication.shared.openURL(url) #endif #elseif os(watchOS) // WATCHOS: not implemented #elseif os(OSX) NSWorkspace.shared().open(url) #endif } } // MARK: Open SFSafariViewController #if os(iOS) import SafariServices @available(iOS 9.0, *) open class SafariURLHandler: NSObject, OAuthSwiftURLHandlerType, SFSafariViewControllerDelegate { public typealias UITransion = (_ controller: SFSafariViewController, _ handler: SafariURLHandler) -> Void open let oauthSwift: OAuthSwift open var present: UITransion open var dismiss: UITransion // retains observers var observers = [String: NSObjectProtocol]() open var factory: (_ URL: URL) -> SFSafariViewController = {URL in return SFSafariViewController(url: URL) } // delegates open weak var delegate: SFSafariViewControllerDelegate? // configure default presentation and dismissal code open var animated: Bool = true open var presentCompletion: (() -> Void)? open var dismissCompletion: (() -> Void)? open var delay: UInt32? = 1 // init public init(viewController: UIViewController, oauthSwift: OAuthSwift) { self.oauthSwift = oauthSwift self.present = { controller, handler in viewController.present(controller, animated: handler.animated, completion: handler.presentCompletion) } self.dismiss = { controller, handler in viewController.dismiss(animated: handler.animated, completion: handler.dismissCompletion) } } public init(present: @escaping UITransion, dismiss: @escaping UITransion, oauthSwift: OAuthSwift) { self.oauthSwift = oauthSwift self.present = present self.dismiss = dismiss } @objc open func handle(_ url: URL) { let controller = factory(url) controller.delegate = self // present controller in main thread OAuthSwift.main { [weak self] in guard let this = self else { return } if let delay = this.delay { // sometimes safari show a blank view.. sleep(delay) } this.present(controller, this) } let key = UUID().uuidString observers[key] = OAuthSwift.notificationCenter.addObserver( forName: OAuthSwift.CallbackNotification.notificationName, object: nil, queue: OperationQueue.main, using: { [weak self] _ in guard let this = self else { return } if let observer = this.observers[key] { OAuthSwift.notificationCenter.removeObserver(observer) this.observers.removeValue(forKey: key) } OAuthSwift.main { this.dismiss(controller, this) } } ) } // Clear internal observers on authentification flow open func clearObservers() { clearLocalObservers() self.oauthSwift.removeCallbackNotificationObserver() } open func clearLocalObservers() { for (_, observer) in observers { OAuthSwift.notificationCenter.removeObserver(observer) } observers.removeAll() } // SFSafariViewControllerDelegate public func safariViewController(_ controller: SFSafariViewController, activityItemsFor URL: Foundation.URL, title: String?) -> [UIActivity] { return self.delegate?.safariViewController?(controller, activityItemsFor: URL, title: title) ?? [] } public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { // "Done" pressed self.clearObservers() self.delegate?.safariViewControllerDidFinish?(controller) } public func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) { self.delegate?.safariViewController?(controller, didCompleteInitialLoad: didLoadSuccessfully) } } #endif // MARK: Open url using NSExtensionContext open class ExtensionContextURLHandler: OAuthSwiftURLHandlerType { fileprivate var extensionContext: NSExtensionContext public init(extensionContext: NSExtensionContext) { self.extensionContext = extensionContext } @objc open func handle(_ url: URL) { extensionContext.open(url, completionHandler: nil) } }
mit
5a8beb7e54b53bc7e2796e9c7fa4384f
32.131737
150
0.609615
5.538539
false
false
false
false
AckeeCZ/ACKategories
ACKategories-iOS/UIColorExtensions.swift
1
4756
import UIKit public extension UIColor { /** Initialize color from hex int (eg. 0xff00ff). - parameter hex: Hex int to create color from */ convenience init(hex: UInt32) { self.init( red: CGFloat(Double((hex & 0xFF0000) >> 16) / 255.0), green: CGFloat(Double((hex & 0xFF00) >> 8) / 255.0), blue: CGFloat(Double(hex & 0xFF) / 255.0), alpha: 1.0 ) } /** Initialize color from hex string (eg. "#ff00ff"). Leading '#' is mandatory. - parameter hexString: Hex string to create color from */ convenience init(hexString: String) { var rgbValue: UInt32 = 0 let scanner = Scanner(string: hexString) scanner.scanLocation = 1 // bypass '#' character scanner.scanHexInt32(&rgbValue) self.init(hex: rgbValue) } /** Returns color as hex string (eg. '#ff00ff') or nil if RGBA components couldn't be loaded. Monochrome check included (works for white/black/clear). */ var hexString: String? { guard let components = cgColor.components, cgColor.numberOfComponents > 1 else { return nil } let isMonochrome = cgColor.colorSpace?.model == .monochrome let r: CGFloat = isMonochrome ? components[0] : components[0] let g: CGFloat = isMonochrome ? components[0] : components[1] let b: CGFloat = isMonochrome ? components[0] : components[2] return String(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255))) } /// Create random color static func random() -> UIColor { let randomRed = CGFloat(arc4random()) / CGFloat(UInt32.max) let randomGreen = CGFloat(arc4random()) / CGFloat(UInt32.max) let randomBlue = CGFloat(arc4random()) / CGFloat(UInt32.max) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) } /** Make color lighter with defined amount. - parameter amount: Defines how much lighter color is returned. Should be from 0.0 to 1.0 */ func brightened(by amount: CGFloat = 0.25) -> UIColor { return with(brightnessAmount: 1 + max(0, amount)) } /** Make color darker with defined amount. - parameter amount: Defines how much darker color is returned. Should be from 0.0 to 1.0 */ func darkened(by amount: CGFloat = 0.25) -> UIColor { return with(brightnessAmount: 1 - max(0, amount)) } fileprivate func with(brightnessAmount: CGFloat) -> UIColor { var h: CGFloat = 0 var s: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 guard getHue(&h, saturation: &s, brightness: &b, alpha: &a) else { return self } return UIColor( hue: h, saturation: s, brightness: b * brightnessAmount, alpha: a ) } /// Returns true for light colors. When light color is used as background, you should use black as a text color. var isLight: Bool { guard let components = cgColor.components else { return true } let red = components[0] let green = components[1] let blue = components[2] let brightness = (red * 299 + green * 587 + blue * 114) / 1000 return brightness > 0.5 } /// Returns true for dark colors. When dark color is used as background, you should use white as a text color. var isDark: Bool { return !isLight } /// Create image from color with defined size. func image(of size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() if #available(iOS 13.0, *) { // if self has alpha < 1 then this alpha is correctly applied on content // during context rendering, which is right behavior. But after that in // `.withTintColor(self)` below, this alpha is applied again and resulting // image is more transparent then it should be. So use any non-transparent // color here to draw the content and set resulting color with alpha only below. context?.setFillColor(UIColor.white.cgColor) } else { context?.setFillColor(self.cgColor) } context?.fill(rect) // swiftlint:disable:next force_unwrapping let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() if #available(iOS 13.0, *) { return image.withTintColor(self) } else { return image } } }
mit
01f4841156a14b0ff9e7f508ea935105
34.492537
124
0.607864
4.327571
false
false
false
false
NeilNie/Done-
Pods/Eureka/Source/Core/Core.swift
1
44893
// Core.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // 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 // MARK: Row internal class RowDefaults { static var cellUpdate = [String: (BaseCell, BaseRow) -> Void]() static var cellSetup = [String: (BaseCell, BaseRow) -> Void]() static var onCellHighlightChanged = [String: (BaseCell, BaseRow) -> Void]() static var rowInitialization = [String: (BaseRow) -> Void]() static var onRowValidationChanged = [String: (BaseCell, BaseRow) -> Void]() static var rawCellUpdate = [String: Any]() static var rawCellSetup = [String: Any]() static var rawOnCellHighlightChanged = [String: Any]() static var rawRowInitialization = [String: Any]() static var rawOnRowValidationChanged = [String: Any]() } // MARK: FormCells public struct CellProvider<Cell: BaseCell> where Cell: CellType { /// Nibname of the cell that will be created. public private (set) var nibName: String? /// Bundle from which to get the nib file. public private (set) var bundle: Bundle! public init() {} public init(nibName: String, bundle: Bundle? = nil) { self.nibName = nibName self.bundle = bundle ?? Bundle(for: Cell.self) } /** Creates the cell with the specified style. - parameter cellStyle: The style with which the cell will be created. - returns: the cell */ func makeCell(style: UITableViewCell.CellStyle) -> Cell { if let nibName = self.nibName { return bundle.loadNibNamed(nibName, owner: nil, options: nil)!.first as! Cell } return Cell.init(style: style, reuseIdentifier: nil) } } /** Enumeration that defines how a controller should be created. - Callback->VCType: Creates the controller inside the specified block - NibFile: Loads a controller from a nib file in some bundle - StoryBoard: Loads the controller from a Storyboard by its storyboard id */ public enum ControllerProvider<VCType: UIViewController> { /** * Creates the controller inside the specified block */ case callback(builder: (() -> VCType)) /** * Loads a controller from a nib file in some bundle */ case nibFile(name: String, bundle: Bundle?) /** * Loads the controller from a Storyboard by its storyboard id */ case storyBoard(storyboardId: String, storyboardName: String, bundle: Bundle?) func makeController() -> VCType { switch self { case .callback(let builder): return builder() case .nibFile(let nibName, let bundle): return VCType.init(nibName: nibName, bundle:bundle ?? Bundle(for: VCType.self)) case .storyBoard(let storyboardId, let storyboardName, let bundle): let sb = UIStoryboard(name: storyboardName, bundle: bundle ?? Bundle(for: VCType.self)) return sb.instantiateViewController(withIdentifier: storyboardId) as! VCType } } } /** Defines how a controller should be presented. - Show?: Shows the controller with `showViewController(...)`. - PresentModally?: Presents the controller modally. - SegueName?: Performs the segue with the specified identifier (name). - SegueClass?: Performs a segue from a segue class. */ public enum PresentationMode<VCType: UIViewController> { /** * Shows the controller, created by the specified provider, with `showViewController(...)`. */ case show(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) /** * Presents the controller, created by the specified provider, modally. */ case presentModally(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) /** * Performs the segue with the specified identifier (name). */ case segueName(segueName: String, onDismiss: ((UIViewController) -> Void)?) /** * Performs a segue from a segue class. */ case segueClass(segueClass: UIStoryboardSegue.Type, onDismiss: ((UIViewController) -> Void)?) case popover(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) public var onDismissCallback: ((UIViewController) -> Void)? { switch self { case .show(_, let completion): return completion case .presentModally(_, let completion): return completion case .segueName(_, let completion): return completion case .segueClass(_, let completion): return completion case .popover(_, let completion): return completion } } /** Present the view controller provided by PresentationMode. Should only be used from custom row implementation. - parameter viewController: viewController to present if it makes sense (normally provided by makeController method) - parameter row: associated row - parameter presentingViewController: form view controller */ public func present(_ viewController: VCType!, row: BaseRow, presentingController: FormViewController) { switch self { case .show(_, _): presentingController.show(viewController, sender: row) case .presentModally(_, _): presentingController.present(viewController, animated: true) case .segueName(let segueName, _): presentingController.performSegue(withIdentifier: segueName, sender: row) case .segueClass(let segueClass, _): let segue = segueClass.init(identifier: row.tag, source: presentingController, destination: viewController) presentingController.prepare(for: segue, sender: row) segue.perform() case .popover(_, _): guard let porpoverController = viewController.popoverPresentationController else { fatalError() } porpoverController.sourceView = porpoverController.sourceView ?? presentingController.tableView presentingController.present(viewController, animated: true) } } /** Creates the view controller specified by presentation mode. Should only be used from custom row implementation. - returns: the created view controller or nil depending on the PresentationMode type. */ public func makeController() -> VCType? { switch self { case .show(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller case .presentModally(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller case .popover(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() controller.modalPresentationStyle = .popover let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller default: return nil } } } /** * Protocol to be implemented by custom formatters. */ public protocol FormatterProtocol { func getNewPosition(forPosition: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition } // MARK: Predicate Machine enum ConditionType { case hidden, disabled } /** Enumeration that are used to specify the disbaled and hidden conditions of rows - Function: A function that calculates the result - Predicate: A predicate that returns the result */ public enum Condition { /** * Calculate the condition inside a block * * @param Array of tags of the rows this function depends on * @param Form->Bool The block that calculates the result * * @return If the condition is true or false */ case function([String], (Form)->Bool) /** * Calculate the condition using a NSPredicate * * @param NSPredicate The predicate that will be evaluated * * @return If the condition is true or false */ case predicate(NSPredicate) } extension Condition : ExpressibleByBooleanLiteral { /** Initialize a condition to return afixed boolean value always */ public init(booleanLiteral value: Bool) { self = Condition.function([]) { _ in return value } } } extension Condition : ExpressibleByStringLiteral { /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(stringLiteral value: String) { self = .predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(unicodeScalarLiteral value: String) { self = .predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(extendedGraphemeClusterLiteral value: String) { self = .predicate(NSPredicate(format: value)) } } // MARK: Errors /** Errors thrown by Eureka - duplicatedTag: When a section or row is inserted whose tag dows already exist - rowNotInSection: When a row was expected to be in a Section, but is not. */ public enum EurekaError: Error { case duplicatedTag(tag: String) case rowNotInSection(row: BaseRow) } //Mark: FormViewController /** * A protocol implemented by FormViewController */ public protocol FormViewControllerProtocol { var tableView: UITableView! { get } func beginEditing<T>(of: Cell<T>) func endEditing<T>(of: Cell<T>) func insertAnimation(forRows rows: [BaseRow]) -> UITableView.RowAnimation func deleteAnimation(forRows rows: [BaseRow]) -> UITableView.RowAnimation func reloadAnimation(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableView.RowAnimation func insertAnimation(forSections sections: [Section]) -> UITableView.RowAnimation func deleteAnimation(forSections sections: [Section]) -> UITableView.RowAnimation func reloadAnimation(oldSections: [Section], newSections: [Section]) -> UITableView.RowAnimation } /** * Navigation options for a form view controller. */ public struct RowNavigationOptions: OptionSet { private enum NavigationOptions: Int { case disabled = 0, enabled = 1, stopDisabledRow = 2, skipCanNotBecomeFirstResponderRow = 4 } public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue} private init(_ options: NavigationOptions ) { self.rawValue = options.rawValue } /// No navigation. public static let Disabled = RowNavigationOptions(.disabled) /// Full navigation. public static let Enabled = RowNavigationOptions(.enabled) /// Break navigation when next row is disabled. public static let StopDisabledRow = RowNavigationOptions(.stopDisabledRow) /// Break navigation when next row cannot become first responder. public static let SkipCanNotBecomeFirstResponderRow = RowNavigationOptions(.skipCanNotBecomeFirstResponderRow) } /** * Defines the configuration for the keyboardType of FieldRows. */ public struct KeyboardReturnTypeConfiguration { /// Used when the next row is available. public var nextKeyboardType = UIReturnKeyType.next /// Used if next row is not available. public var defaultKeyboardType = UIReturnKeyType.default public init() {} public init(nextKeyboardType: UIReturnKeyType, defaultKeyboardType: UIReturnKeyType) { self.nextKeyboardType = nextKeyboardType self.defaultKeyboardType = defaultKeyboardType } } /** * Options that define when an inline row should collapse. */ public struct InlineRowHideOptions: OptionSet { private enum _InlineRowHideOptions: Int { case never = 0, anotherInlineRowIsShown = 1, firstResponderChanges = 2 } public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue} private init(_ options: _InlineRowHideOptions ) { self.rawValue = options.rawValue } /// Never collapse automatically. Only when user taps inline row. public static let Never = InlineRowHideOptions(.never) /// Collapse qhen another inline row expands. Just one inline row will be expanded at a time. public static let AnotherInlineRowIsShown = InlineRowHideOptions(.anotherInlineRowIsShown) /// Collapse when first responder changes. public static let FirstResponderChanges = InlineRowHideOptions(.firstResponderChanges) } /// View controller that shows a form. open class FormViewController: UIViewController, FormViewControllerProtocol, FormDelegate { @IBOutlet public var tableView: UITableView! private lazy var _form: Form = { [weak self] in let form = Form() form.delegate = self return form }() public var form: Form { get { return _form } set { guard form !== newValue else { return } _form.delegate = nil tableView?.endEditing(false) _form = newValue _form.delegate = self if isViewLoaded { tableView?.reloadData() } } } /// Extra space to leave between between the row in focus and the keyboard open var rowKeyboardSpacing: CGFloat = 0 /// Enables animated scrolling on row navigation open var animateScroll = false /// Accessory view that is responsible for the navigation between rows open var navigationAccessoryView: NavigationAccessoryView! /// Defines the behaviour of the navigation between rows public var navigationOptions: RowNavigationOptions? private var tableViewStyle: UITableView.Style = .grouped public init(style: UITableView.Style) { super.init(nibName: nil, bundle: nil) tableViewStyle = style } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func viewDidLoad() { super.viewDidLoad() navigationAccessoryView = NavigationAccessoryView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44.0)) navigationAccessoryView.autoresizingMask = .flexibleWidth if tableView == nil { tableView = UITableView(frame: view.bounds, style: tableViewStyle) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] if #available(iOS 9.0, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } } if tableView.superview == nil { view.addSubview(tableView) } if tableView.delegate == nil { tableView.delegate = self } if tableView.dataSource == nil { tableView.dataSource = self } tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = BaseRow.estimatedRowHeight tableView.allowsSelectionDuringEditing = true } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) animateTableView = true let selectedIndexPaths = tableView.indexPathsForSelectedRows ?? [] if !selectedIndexPaths.isEmpty { tableView.reloadRows(at: selectedIndexPaths, with: .none) } selectedIndexPaths.forEach { tableView.selectRow(at: $0, animated: false, scrollPosition: .none) } let deselectionAnimation = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in selectedIndexPaths.forEach { self?.tableView.deselectRow(at: $0, animated: context.isAnimated) } } let reselection = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in if context.isCancelled { selectedIndexPaths.forEach { self?.tableView.selectRow(at: $0, animated: false, scrollPosition: .none) } } } if let coordinator = transitionCoordinator { coordinator.animate(alongsideTransition: deselectionAnimation, completion: reselection) } else { selectedIndexPaths.forEach { tableView.deselectRow(at: $0, animated: false) } } NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) if form.containsMultivaluedSection && (isBeingPresented || isMovingToParent) { tableView.setEditing(true, animated: false) } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } open override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) let baseRow = sender as? BaseRow baseRow?.prepare(for: segue) } /** Returns the navigation accessory view if it is enabled. Returns nil otherwise. */ open func inputAccessoryView(for row: BaseRow) -> UIView? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard row.baseCell.cellCanBecomeFirstResponder() else { return nil} navigationAccessoryView.previousButton.isEnabled = nextRow(for: row, withDirection: .up) != nil navigationAccessoryView.doneButton.target = self navigationAccessoryView.doneButton.action = #selector(FormViewController.navigationDone(_:)) navigationAccessoryView.previousButton.target = self navigationAccessoryView.previousButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.target = self navigationAccessoryView.nextButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.isEnabled = nextRow(for: row, withDirection: .down) != nil return navigationAccessoryView } // MARK: FormViewControllerProtocol /** Called when a cell becomes first responder */ public final func beginEditing<T>(of cell: Cell<T>) { cell.row.isHighlighted = true cell.row.updateCell() RowDefaults.onCellHighlightChanged["\(type(of: cell.row!))"]?(cell, cell.row) cell.row.callbackOnCellHighlightChanged?() guard let _ = tableView, (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.FirstResponderChanges) else { return } let row = cell.baseRow let inlineRow = row?._inlineRow for row in form.allRows.filter({ $0 !== row && $0 !== inlineRow && $0._inlineRow != nil }) { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } /** Called when a cell resigns first responder */ public final func endEditing<T>(of cell: Cell<T>) { cell.row.isHighlighted = false cell.row.wasBlurred = true RowDefaults.onCellHighlightChanged["\(type(of: cell.row!))"]?(cell, cell.row) cell.row.callbackOnCellHighlightChanged?() if cell.row.validationOptions.contains(.validatesOnBlur) || (cell.row.wasChanged && cell.row.validationOptions.contains(.validatesOnChangeAfterBlurred)) { cell.row.validate() } cell.row.updateCell() } /** Returns the animation for the insertion of the given rows. */ open func insertAnimation(forRows rows: [BaseRow]) -> UITableView.RowAnimation { return .fade } /** Returns the animation for the deletion of the given rows. */ open func deleteAnimation(forRows rows: [BaseRow]) -> UITableView.RowAnimation { return .fade } /** Returns the animation for the reloading of the given rows. */ open func reloadAnimation(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableView.RowAnimation { return .automatic } /** Returns the animation for the insertion of the given sections. */ open func insertAnimation(forSections sections: [Section]) -> UITableView.RowAnimation { return .automatic } /** Returns the animation for the deletion of the given sections. */ open func deleteAnimation(forSections sections: [Section]) -> UITableView.RowAnimation { return .automatic } /** Returns the animation for the reloading of the given sections. */ open func reloadAnimation(oldSections: [Section], newSections: [Section]) -> UITableView.RowAnimation { return .automatic } // MARK: TextField and TextView Delegate open func textInputShouldBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputDidBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) { if let row = cell.row as? KeyboardReturnHandler { let next = nextRow(for: cell.row, withDirection: .down) if let textField = textInput as? UITextField { textField.returnKeyType = next != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } else if let textView = textInput as? UITextView { textView.returnKeyType = next != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } } } open func textInputShouldEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputDidEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) { } open func textInput<T>(_ textInput: UITextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String, cell: Cell<T>) -> Bool { return true } open func textInputShouldClear<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputShouldReturn<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { if let nextRow = nextRow(for: cell.row, withDirection: .down) { if nextRow.baseCell.cellCanBecomeFirstResponder() { nextRow.baseCell.cellBecomeFirstResponder() return true } } tableView?.endEditing(true) return true } // MARK: FormDelegate open func valueHasBeenChanged(for: BaseRow, oldValue: Any?, newValue: Any?) {} // MARK: UITableViewDelegate @objc open func tableView(_ tableView: UITableView, willBeginReorderingRowAtIndexPath indexPath: IndexPath) { // end editing if inline cell is first responder let row = form[indexPath] if let inlineRow = row as? BaseInlineRowType, row._inlineRow != nil { inlineRow.collapseInlineRow() } } // MARK: FormDelegate open func sectionsHaveBeenAdded(_ sections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.insertSections(indexes, with: insertAnimation(forSections: sections)) tableView?.endUpdates() } open func sectionsHaveBeenRemoved(_ sections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.deleteSections(indexes, with: deleteAnimation(forSections: sections)) tableView?.endUpdates() } open func sectionsHaveBeenReplaced(oldSections: [Section], newSections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.reloadSections(indexes, with: reloadAnimation(oldSections: oldSections, newSections: newSections)) tableView?.endUpdates() } open func rowsHaveBeenAdded(_ rows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.insertRows(at: indexes, with: insertAnimation(forRows: rows)) tableView?.endUpdates() } open func rowsHaveBeenRemoved(_ rows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.deleteRows(at: indexes, with: deleteAnimation(forRows: rows)) tableView?.endUpdates() } open func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.reloadRows(at: indexes, with: reloadAnimation(oldRows: oldRows, newRows: newRows)) tableView?.endUpdates() } // MARK: Private var oldBottomInset: CGFloat? var animateTableView = false /** Calculates the height needed for a header or footer. */ fileprivate func height(specifiedHeight: (() -> CGFloat)?, sectionView: UIView?, sectionTitle: String?) -> CGFloat { if let height = specifiedHeight { return height() } if let sectionView = sectionView { let height = sectionView.bounds.height if height == 0 { return UITableView.automaticDimension } return height } if let sectionTitle = sectionTitle, sectionTitle != "" { return UITableView.automaticDimension } // Fix for iOS 11+. By returning 0, we ensure that no section header or // footer is shown when self-sizing is enabled (i.e. when // tableView.estimatedSectionHeaderHeight or tableView.estimatedSectionFooterHeight // == UITableView.automaticDimension). if tableView.style == .plain { return 0 } return UITableView.automaticDimension } } extension FormViewController : UITableViewDelegate { // MARK: UITableViewDelegate open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return indexPath } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard tableView == self.tableView else { return } let row = form[indexPath] // row.baseCell.cellBecomeFirstResponder() may be cause InlineRow collapsed then section count will be changed. Use orignal indexPath will out of section's bounds. if !row.baseCell.cellCanBecomeFirstResponder() || !row.baseCell.cellBecomeFirstResponder() { self.tableView?.endEditing(true) } row.didSelect() } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.rowHeight } open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.estimatedRowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.estimatedRowHeight } open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return form[section].header?.viewForSection(form[section], type: .header) } open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return form[section].footer?.viewForSection(form[section], type:.footer) } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return height(specifiedHeight: form[section].header?.height, sectionView: self.tableView(tableView, viewForHeaderInSection: section), sectionTitle: self.tableView(tableView, titleForHeaderInSection: section)) } open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return height(specifiedHeight: form[section].footer?.height, sectionView: self.tableView(tableView, viewForFooterInSection: section), sectionTitle: self.tableView(tableView, titleForFooterInSection: section)) } open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { let row = form[indexPath] guard !row.isDisabled else { return false } if row.trailingSwipe.actions.count > 0 { return true } if #available(iOS 11,*), row.leadingSwipe.actions.count > 0 { return true } guard let section = form[indexPath.section] as? MultivaluedSection else { return false } guard !(indexPath.row == section.count - 1 && section.multivaluedOptions.contains(.Insert) && section.showInsertIconInAddButton) else { return true } if indexPath.row > 0 && section[indexPath.row - 1] is BaseInlineRowType && section[indexPath.row - 1]._inlineRow != nil { return false } return true } open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let row = form[indexPath] let section = row.section! if let _ = row.baseCell.findFirstResponder() { tableView.endEditing(true) } section.remove(at: indexPath.row) DispatchQueue.main.async { tableView.isEditing = !tableView.isEditing tableView.isEditing = !tableView.isEditing } } else if editingStyle == .insert { guard var section = form[indexPath.section] as? MultivaluedSection else { return } guard let multivaluedRowToInsertAt = section.multivaluedRowToInsertAt else { fatalError("Multivalued section multivaluedRowToInsertAt property must be set up") } let newRow = multivaluedRowToInsertAt(max(0, section.count - 1)) section.insert(newRow, at: max(0, section.count - 1)) DispatchQueue.main.async { tableView.isEditing = !tableView.isEditing tableView.isEditing = !tableView.isEditing } tableView.scrollToRow(at: IndexPath(row: section.count - 1, section: indexPath.section), at: .bottom, animated: true) if newRow.baseCell.cellCanBecomeFirstResponder() { newRow.baseCell.cellBecomeFirstResponder() } else if let inlineRow = newRow as? BaseInlineRowType { inlineRow.expandInlineRow() } } } open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { guard let section = form[indexPath.section] as? MultivaluedSection, section.multivaluedOptions.contains(.Reorder) && section.count > 1 else { return false } if section.multivaluedOptions.contains(.Insert) && (section.count <= 2 || indexPath.row == (section.count - 1)) { return false } if indexPath.row > 0 && section[indexPath.row - 1] is BaseInlineRowType && section[indexPath.row - 1]._inlineRow != nil { return false } return true } open func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { guard let section = form[sourceIndexPath.section] as? MultivaluedSection else { return sourceIndexPath } guard sourceIndexPath.section == proposedDestinationIndexPath.section else { return sourceIndexPath } let destRow = form[proposedDestinationIndexPath] if destRow is BaseInlineRowType && destRow._inlineRow != nil { return IndexPath(row: proposedDestinationIndexPath.row + (sourceIndexPath.row < proposedDestinationIndexPath.row ? 1 : -1), section:sourceIndexPath.section) } if proposedDestinationIndexPath.row > 0 { let previousRow = form[IndexPath(row: proposedDestinationIndexPath.row - 1, section: proposedDestinationIndexPath.section)] if previousRow is BaseInlineRowType && previousRow._inlineRow != nil { return IndexPath(row: proposedDestinationIndexPath.row + (sourceIndexPath.row < proposedDestinationIndexPath.row ? 1 : -1), section:sourceIndexPath.section) } } if section.multivaluedOptions.contains(.Insert) && proposedDestinationIndexPath.row == section.count - 1 { return IndexPath(row: section.count - 2, section: sourceIndexPath.section) } return proposedDestinationIndexPath } open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { guard var section = form[sourceIndexPath.section] as? MultivaluedSection else { return } if sourceIndexPath.row < section.count && destinationIndexPath.row < section.count && sourceIndexPath.row != destinationIndexPath.row { let sourceRow = form[sourceIndexPath] animateTableView = false section.remove(at: sourceIndexPath.row) section.insert(sourceRow, at: destinationIndexPath.row) animateTableView = true // update the accessory view let _ = inputAccessoryView(for: sourceRow) } } open func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { guard let section = form[indexPath.section] as? MultivaluedSection else { if form[indexPath].trailingSwipe.actions.count > 0 { return .delete } return .none } if section.multivaluedOptions.contains(.Insert) && indexPath.row == section.count - 1 { return section.showInsertIconInAddButton ? .insert : .none } if section.multivaluedOptions.contains(.Delete) { return .delete } return .none } open func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return self.tableView(tableView, editingStyleForRowAt: indexPath) != .none } @available(iOS 11,*) open func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { guard !form[indexPath].leadingSwipe.actions.isEmpty else { return nil } return form[indexPath].leadingSwipe.contextualConfiguration } @available(iOS 11,*) open func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { guard !form[indexPath].trailingSwipe.actions.isEmpty else { return nil } return form[indexPath].trailingSwipe.contextualConfiguration } open func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?{ guard let actions = form[indexPath].trailingSwipe.contextualActions as? [UITableViewRowAction], !actions.isEmpty else { return nil } return actions } } extension FormViewController : UITableViewDataSource { // MARK: UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { return form.count } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return form[section].count } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { form[indexPath].updateCell() return form[indexPath].baseCell } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return form[section].header?.title } open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return form[section].footer?.title } open func sectionIndexTitles(for tableView: UITableView) -> [String]? { return nil } open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return 0 } } extension FormViewController : UIScrollViewDelegate { // MARK: UIScrollViewDelegate open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard let tableView = tableView, scrollView === tableView else { return } tableView.endEditing(true) } } extension FormViewController { // MARK: KeyBoard Notifications /** Called when the keyboard will appear. Adjusts insets of the tableView and scrolls it if necessary. */ @objc open func keyboardWillShow(_ notification: Notification) { guard let table = tableView, let cell = table.findFirstResponder()?.formCell() else { return } let keyBoardInfo = notification.userInfo! let endFrame = keyBoardInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue let keyBoardFrame = table.window!.convert(endFrame.cgRectValue, to: table.superview) let newBottomInset = table.frame.origin.y + table.frame.size.height - keyBoardFrame.origin.y + rowKeyboardSpacing var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets oldBottomInset = oldBottomInset ?? tableInsets.bottom if newBottomInset > oldBottomInset! { tableInsets.bottom = newBottomInset scrollIndicatorInsets.bottom = tableInsets.bottom UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration((keyBoardInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double)) UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: (keyBoardInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int))!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets if let selectedRow = table.indexPath(for: cell) { table.scrollToRow(at: selectedRow, at: .none, animated: animateScroll) } UIView.commitAnimations() } } /** Called when the keyboard will disappear. Adjusts insets of the tableView. */ @objc open func keyboardWillHide(_ notification: Notification) { guard let table = tableView, let oldBottom = oldBottomInset else { return } let keyBoardInfo = notification.userInfo! var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets tableInsets.bottom = oldBottom scrollIndicatorInsets.bottom = tableInsets.bottom oldBottomInset = nil UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration((keyBoardInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double)) UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: (keyBoardInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int))!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets UIView.commitAnimations() } } public enum Direction { case up, down } extension FormViewController { // MARK: Navigation Methods @objc func navigationDone(_ sender: UIBarButtonItem) { tableView?.endEditing(true) } @objc func navigationAction(_ sender: UIBarButtonItem) { navigateTo(direction: sender == navigationAccessoryView.previousButton ? .up : .down) } public func navigateTo(direction: Direction) { guard let currentCell = tableView?.findFirstResponder()?.formCell() else { return } guard let currentIndexPath = tableView?.indexPath(for: currentCell) else { assertionFailure(); return } guard let nextRow = nextRow(for: form[currentIndexPath], withDirection: direction) else { return } if nextRow.baseCell.cellCanBecomeFirstResponder() { tableView?.scrollToRow(at: nextRow.indexPath!, at: .none, animated: animateScroll) nextRow.baseCell.cellBecomeFirstResponder(withDirection: direction) } } func nextRow(for currentRow: BaseRow, withDirection direction: Direction) -> BaseRow? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard let next = direction == .down ? form.nextRow(for: currentRow) : form.previousRow(for: currentRow) else { return nil } if next.isDisabled && options.contains(.StopDisabledRow) { return nil } if !next.baseCell.cellCanBecomeFirstResponder() && !next.isDisabled && !options.contains(.SkipCanNotBecomeFirstResponderRow) { return nil } if !next.isDisabled && next.baseCell.cellCanBecomeFirstResponder() { return next } return nextRow(for: next, withDirection:direction) } } extension FormViewControllerProtocol { // MARK: Helpers func makeRowVisible(_ row: BaseRow, destinationScrollPosition: UITableView.ScrollPosition) { guard let cell = row.baseCell, let indexPath = row.indexPath, let tableView = tableView else { return } if cell.window == nil || (tableView.contentOffset.y + tableView.frame.size.height <= cell.frame.origin.y + cell.frame.size.height) { tableView.scrollToRow(at: indexPath, at: destinationScrollPosition, animated: true) } } }
apache-2.0
f2af4e285d1e7e5c669c58b3655ef5b1
39.663949
185
0.672421
5.23839
false
false
false
false
mozilla-mobile/firefox-ios
Storage/SQL/SQLiteHistoryRecommendations.swift
2
2638
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared private let log = Logger.syncLogger extension SQLiteHistory: HistoryRecommendations { static let MaxHistoryRowCount: UInt = 200000 static let PruneHistoryRowCount: UInt = 10000 public func cleanupHistoryIfNeeded() { DispatchQueue.global(qos: .background).async { self.checkIfCleanupIsNeeded(maxHistoryRows: SQLiteHistory.MaxHistoryRowCount) >>== { doCleanup in if doCleanup { _ = self.database.run(self.cleanupOldHistory(numberOfRowsToPrune: SQLiteHistory.PruneHistoryRowCount)) } } } } // Checks if there are more than the specified number of rows in the // `history` table. This is used as an indicator that `cleanupOldHistory()` // needs to run. func checkIfCleanupIsNeeded(maxHistoryRows: UInt) -> Deferred<Maybe<Bool>> { let sql = "SELECT COUNT(rowid) > \(maxHistoryRows) AS cleanup FROM \(TableHistory)" return self.database.runQueryConcurrently(sql, args: nil, factory: IntFactory) >>== { cursor in guard let cleanup = cursor[0], cleanup > 0 else { return deferMaybe(false) } return deferMaybe(true) } } // Deletes the specified number of items from the `history` table and // their corresponding items in the `visits` table. This only gets run // when the `checkIfCleanupIsNeeded()` method returns `true`. It is possible // that a single clean-up operation may not remove enough rows to drop below // the threshold used in `checkIfCleanupIsNeeded()` and therefore, this may // end up running several times until that threshold is crossed. func cleanupOldHistory(numberOfRowsToPrune: UInt) -> [(String, Args?)] { log.debug("Cleaning up \(numberOfRowsToPrune) rows of history.") let sql = """ DELETE FROM \(TableHistory) WHERE id IN ( SELECT siteID FROM \(TableVisits) GROUP BY siteID ORDER BY max(date) ASC LIMIT \(numberOfRowsToPrune) ) """ return [(sql, nil)] } public func repopulate(invalidateTopSites shouldInvalidateTopSites: Bool) -> Success { if shouldInvalidateTopSites { return database.run(refreshTopSitesQuery()) } else { return succeed() } } }
mpl-2.0
6cd6ad236ec9b104c699ddfe18bb5daf
38.373134
122
0.637983
4.796364
false
false
false
false
codefellows/sea-d40-iOS
Sample Code/Week3Github/GithubClient/GithubClient/TestAnimationsViewController.swift
1
3286
// // TestAnimationsViewController.swift // GithubClient // // Created by Bradley Johnson on 8/19/15. // Copyright (c) 2015 CF. All rights reserved. // import UIKit class TestAnimationsViewController: UIViewController { @IBOutlet weak var greenView: UIView! @IBOutlet weak var redView: UIView! @IBAction func animate(sender: AnyObject) { //self.greenView.transform = CGAffineTransformScale(self.greenView.transform, 1.5, 1.5) UIView.animateWithDuration(0.3, animations: { () -> Void in //self.redView.center = CGPoint(x: 200, y: 400) //self.greenView.transform = CGAffineTransformScale(self.greenView.transform, 0.75, 0.75) self.greenView.alpha = 1 self.greenView.transform = CGAffineTransformRotate(self.greenView.transform, CGFloat(M_PI * 45.0 / 180.0)) // self.greenView.frame = CGRect(origin: self.greenView.frame.origin, size: CGSize(width: self.greenView.frame.width * 2, height: self.greenView.frame.height * 2)) }) // UIView.animateWithDuration(0.3, animations: { () -> Void in // self.greenView.center = CGPoint(x: 100, y: 400) // self.greenView.alpha = 0 // }) { (finished) -> Void in // if finished { // self.greenView.alpha = 1 // } // } // UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in // self.greenView.center = CGPoint(x: 100, y: 400) // }, completion: nil) // UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1.4, options: .Autoreverse | .Repeat, animations: { () -> Void in // self.greenView.center = CGPoint(x: 100, y: 400) // }, completion: {(finished) -> Void in // println("finished") // // }) // UIView.animateKeyframesWithDuration(3.0, delay: 0.0, options: nil, animations: { () -> Void in // UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.25, animations: { () -> Void in // self.greenView.center = CGPoint(x: 100, y: 400) // }) // UIView.addKeyframeWithRelativeStartTime(0.25, relativeDuration: 0.5, animations: { () -> Void in // self.redView.center = CGPoint(x: 300, y: 400) // }) // UIView.addKeyframeWithRelativeStartTime(0.75, relativeDuration: 0.25, animations: { () -> Void in // self.greenView.center = CGPoint(x: -300, y: 400) // self.redView.center = CGPoint(x: 600, y: 400) // }) // }, completion: nil) } override func viewDidLoad() { super.viewDidLoad() greenView.alpha = 0 //redView.alpha = 0 // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
e5f60d554c3838541b8f15d08ee4bd53
36.770115
168
0.635119
3.978208
false
false
false
false
malaonline/iOS
mala-ios/Extension/Extension+UIImageView.swift
1
4579
// // Extension+UIImageView.swift // mala-ios // // Created by Elors on 1/7/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit import Kingfisher import SKPhotoBrowser // MARK: - Class Method extension UIImageView { /// Convenience to Create a UIImageView that prepare to display image /// /// - returns: UIImageView class func placeHolder() -> UIImageView { let placeHolder = UIImageView() placeHolder.contentMode = .scaleAspectFill placeHolder.clipsToBounds = true return placeHolder } } // MARK: - Convenience extension UIImageView { /// Convenience to Create a UIImageView whit a image name /// /// - Parameter name: String of image resource name convenience init(imageName name: String) { self.init() self.image = UIImage(named: name) } /// Convenience to Create a UIImageView that /// /// - Parameters: /// - frame: The size of UIImageView. /// - cornerRadius: The cornerRadius of UIImageView. /// - image: The target image name. /// - contentMode: The ContentMode of UIImageView. convenience init(frame: CGRect? = nil, cornerRadius: CGFloat? = nil, image: String? = nil, contentMode: UIViewContentMode = .scaleAspectFill) { self.init() if let frame = frame { self.frame = frame } if let cornerRadius = cornerRadius { self.layer.cornerRadius = cornerRadius self.layer.masksToBounds = true } if let imageName = image { self.image = UIImage(named: imageName) } self.contentMode = contentMode } } // MARK: - Instance Method extension UIImageView { /// Set an image with resource name. /// /// - Parameter name: The target image name. func setImage(withImageName name: String?) { image = UIImage(named: name ?? "") } /// Activate one tap to launch photo browser func enableOneTapToLaunchPhotoBrowser() { self.addTapEvent(target: self, action: #selector(UIImageView.launchPhotoBrowser)) } /// Launch photo browser when UIImage has image func launchPhotoBrowser() { guard let originImage = self.image else { return } let image = SKPhoto.photoWithImage(originImage) image.shouldCachePhotoURLImage = true let images: [SKPhoto] = [image] let browser = SKPhotoBrowser(originImage: originImage, photos: images, animatedFromView: self) browser.navigationController?.isNavigationBarHidden = true self.viewController()?.navigationController?.present(browser, animated: true, completion: nil) } /// Set an image with url, a placeholder image, progress handler and completion handler. /// /// - Parameters: /// - url: The target image URL. /// - placeholderImage: A placeholder image when retrieving the image at URL. /// - progressBlock: Called when the image downloading progress gets updated. /// - completionHandler: Called when the image retrieved and set. func setImage(withURL url: String? = nil, placeholderImage: String? = "avatar_placeholder", progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) { // use absoluteURL(without sign) as a key to cache the image resource guard let url = url, let URL = URL(string: url) else { println(#function); return } let splitArray = URL.absoluteString.components(separatedBy: "?") guard let pureURL = splitArray.first, !pureURL.isEmpty else { return } // setup the resource let resource = ImageResource(downloadURL: URL, cacheKey: pureURL) if let placeholderImage = placeholderImage, let placeholder = Image(named: placeholderImage) { self.kf.setImage( with: resource, placeholder: placeholder, options: [.transition(.fade(0.25)), .targetCache(ImageCache(name: pureURL))], progressBlock: progressBlock, completionHandler: completionHandler ) }else { self.kf.setImage( with: resource, options: [.transition(.fade(0.25)), .targetCache(ImageCache(name: pureURL))], progressBlock: progressBlock, completionHandler: completionHandler ) } } }
mit
979e26828064381a568b159705a7f9e4
35.624
147
0.616645
5.04185
false
false
false
false
ludoded/PineFinders
Pine Finders/ViewModel/VanViewModel.swift
1
2249
// // VanViewModel.swift // Pine Finders // // Created by Haik Ampardjian on 5/26/16. // Copyright © 2016 Aztech Films. All rights reserved. // import Foundation enum VanFilter: Int { case Manufacturer case Model case Years case Edition } class VanViewModel { private var vans = [VansObject]() private var filteredVans = [VansObject]() var oneResultRemains: ((VansObject) -> ())? var filteredManufacturer: [String]? var filteredModels: [String]? var filteredYears: [String]? var filteredEdition: [String]? var selectedVan: VansObject? var manufacturerFilter: String? var modelFilter: String? var yearsFilter: String? var editionFilter: String? func loadData(completionHandler: () -> ()) { FirebaseManager.sharedInstance.vans { (vans) in self.vans = vans self.filteredVans = vans completionHandler() } } func retrieveManufacturers() { filteredManufacturer = uniq(allFilteredCars().map({ $0.van.manufacturer })) } func retrieveModels() { filteredModels = uniq(allFilteredCars().map({ $0.van.model })) } func retrieveYears() { filteredYears = uniq(allFilteredCars().map({ $0.van.yearsProduces })) } func retrieveEditions() { filteredEdition = uniq(allFilteredCars().map({ $0.van.edition })) } private func allFilteredCars() -> [VansObject] { var allFiltered = filteredVans if let safeManufacturerFilter = manufacturerFilter { allFiltered = allFiltered.filter({ $0.van.manufacturer == safeManufacturerFilter }) } if let safeModelFilter = modelFilter { allFiltered = allFiltered.filter({ $0.van.model == safeModelFilter }) } if let safeYearsFilter = yearsFilter { allFiltered = allFiltered.filter({ $0.van.yearsProduces == safeYearsFilter }) } if let safeEditionFilter = editionFilter { allFiltered = allFiltered.filter({ $0.van.edition == safeEditionFilter }) } if allFiltered.count == 1 { oneResultRemains?(allFiltered.first!) selectedVan = allFiltered.first } return allFiltered } }
mit
cc26456037abec8df745f50da1eea3b4
28.986667
146
0.632562
4.314779
false
false
false
false
mjmsmith/starredsearch
App/Repo.swift
1
6319
import Foundation // # title private let TitleRegex = try! NSRegularExpression(pattern: "^#+(.*)$", options: .anchorsMatchLines) // ======= private let TitleEqualRegex = try! NSRegularExpression(pattern: "^=+ *$", options: .anchorsMatchLines) // ------- private let TitleUnderlineRegex = try! NSRegularExpression(pattern: "^=+ *$", options: .anchorsMatchLines) // ``` private let CodeBlockRegex = try! NSRegularExpression(pattern: "^```.*$", options: .anchorsMatchLines) // [example]: http://example.com private let FootnoteRegex = try! NSRegularExpression(pattern: "^ *\\[.+?\\]: *.*$", options: .anchorsMatchLines) // ![example](http://example.com/image.png) private let ImageRegex = try! NSRegularExpression(pattern: "!\\[(.*?)\\] *\\(.*?\\)", options: .dotMatchesLineSeparators) // [example](http://example.com) private let LinkRegex = try! NSRegularExpression(pattern: "\\[(.*?)\\] *\\(.*?\\)", options: .dotMatchesLineSeparators) // [example][example] private let FootnoteLinkRegex = try! NSRegularExpression(pattern: "\\[(.+?)\\]\\[.*?\\]", options: .dotMatchesLineSeparators) // <a href="http://example.com">example</a> private let AnchorRegex = try! NSRegularExpression(pattern: "<a .*?>(.*?)</a>", options: .dotMatchesLineSeparators) // <img src="http://example.com/image.png"> private let ImgRegex = try! NSRegularExpression(pattern: "<img .*?/?>", options: .dotMatchesLineSeparators) // <!-- example --> private let CommentRegex = try! NSRegularExpression(pattern: "<!--.*?-->", options: .dotMatchesLineSeparators) // __example__ private let BoldUnderlineRegex = try! NSRegularExpression(pattern: "__([^ ].*?[^ ])__", options: []) // **example** private let BoldAsteriskRegex = try! NSRegularExpression(pattern: "\\*\\*([^ ].*?[^ ])\\*\\*", options: []) // _example_ private let ItalicUnderlineRegex = try! NSRegularExpression(pattern: "_([^ ].*?[^ ])_", options: []) // *example* private let ItalicAsteriskRegex = try! NSRegularExpression(pattern: "\\*([^ ].*?[^ ])\\*", options: []) // `example` private let CodeRegex = try! NSRegularExpression(pattern: "`(.*?)`", options: []) class Repo { private static let readmeQueue = DispatchQueue(label: "readme", attributes: .concurrent) let id: Int let name: String let ownerId: Int let ownerName: String let forksCount: Int let starsCount: Int let starredAt: Date let timeStamp = Date() private(set) var readme: [String]? { get { var value: [String]?; Repo.readmeQueue.sync() { value = self._readme }; return value! } set { Repo.readmeQueue.sync(flags: .barrier) { self._readme = newValue } } } var url: URL? { get { return URL(string: "https://github.com/\(self.ownerName)/\(self.name)") } } var ownerUrl: URL? { get { return URL(string: "https://github.com/\(self.ownerName)") } } var readmeUrl: URL? { get { return URL(string: "https://api.github.com/repos/\(self.ownerName)/\(self.name)/readme") } } private var _readme: [String]? init(id: Int, name: String, ownerId: Int, ownerName: String, forksCount: Int, starsCount: Int, starredAt: Date) { self.id = id self.name = name self.ownerId = ownerId self.forksCount = forksCount self.starsCount = starsCount self.ownerName = ownerName self.starredAt = starredAt } func linesMatching(query: String) -> [String] { return self.readme?.filter { $0.localizedCaseInsensitiveContains(query) } ?? [] } func setReadme(withMarkdown markdown: String) { self.readme = Repo.stripped(markdown: markdown).components(separatedBy: "\n").filter { !$0.isEmpty } } private static func stripped(markdown: String) -> String { var text = markdown text = TitleRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "$1") text = TitleEqualRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "") text = TitleUnderlineRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "") text = CodeBlockRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "") text = FootnoteRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "") text = ImageRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "") text = LinkRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "$1") text = FootnoteLinkRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "$1") text = AnchorRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "") text = ImgRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "") text = CommentRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "") text = BoldUnderlineRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "$1") text = BoldAsteriskRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "$1") text = ItalicUnderlineRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "$1") text = ItalicAsteriskRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "$1") text = CodeRegex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), withTemplate: "$1") return text } } extension Repo: Hashable { var hashValue: Int { return self.id } } func ==(left: Repo, right: Repo) -> Bool { return left === right }
mit
2e90114c0dd6f5f4c1a0196a7ba8f102
45.124088
159
0.687609
4.022279
false
false
false
false
nab0y4enko/PrettyKeyboardHelper
PrettyKeyboardHelper/NSLayoutConstraint+PrettyKeyboardHelper.swift
1
1221
// // NSLayoutConstraint+PrettyKeyboardHelper.swift // PrettyKeyboardHelper // // Created by Oleksii Naboichenko on 11/29/16. // Copyright © 2016 Oleksii Naboichenko. All rights reserved. // import UIKit public extension NSLayoutConstraint { final func updateConstant(with keyboardInfo: PrettyKeyboardInfo, defaultConstant: CGFloat = 0.0, safeAreaInsets: UIEdgeInsets? = nil, completion: ((Bool) -> Swift.Void)? = nil) { if let bottomSafeAreaInset = safeAreaInsets?.bottom, keyboardInfo.keyboardState == .willBeShown { constant = keyboardInfo.estimatedKeyboardHeight + defaultConstant - bottomSafeAreaInset } else { constant = keyboardInfo.estimatedKeyboardHeight + defaultConstant } guard let view = (firstItem ?? secondItem) as? UIView, let superview = view.superview else { completion?(false) return } UIView.animate( withDuration: keyboardInfo.duration, delay: 0, options: keyboardInfo.animationOptions, animations: { superview.layoutIfNeeded() }, completion: completion ) } }
mit
b8c01e66608fde5f48206260b502697d
32.888889
183
0.633607
5.213675
false
false
false
false
KiiPlatform/thing-if-iOSSample
SampleProject/AppDelegate.swift
1
4442
// // AppDelegate.swift // SampleProject // // Created by Yongping on 8/5/15. // Copyright © 2015 Kii Corporation. All rights reserved. // import KiiSDK import UIKit import ThingIFSDK @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // init Kii with the values from Properties.plist, so please make sure to set the correct value var propertiesDict: NSDictionary? if let path = NSBundle.mainBundle().pathForResource("Properties", ofType: "plist") { propertiesDict = NSDictionary(contentsOfFile: path) } if let dict = propertiesDict { let appHost:String = dict["appHost"] as! String; let url:String = "https://" + appHost + "/api" Kii.beginWithID((dict["appID"] as! String), andKey: (dict["appKey"] as! String), andCustomURL: url) }else { print("please make sure the Properties.plist file exists") } // define schema let smartLightDemoSchema = IoTSchema(name: "SmartLight-Demo", version: 1) smartLightDemoSchema.addStatus("power", statusType: StatusType.BoolType) smartLightDemoSchema.addStatus("brightness", statusType: StatusType.IntType, minValue: 0, maxvalue: 100) smartLightDemoSchema.addStatus("color", statusType: StatusType.IntType, minValue: 0, maxvalue: 16777215) smartLightDemoSchema.addAction("turnPower", statusName: "power") smartLightDemoSchema.addAction("setBrightness", statusName: "brightness") smartLightDemoSchema.addAction("setColor", statusName: "color") // save schema NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(smartLightDemoSchema), forKey: "schema") NSUserDefaults.standardUserDefaults().synchronize() //register for remote notification // this line does not ask for user permission application.registerForRemoteNotifications() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { //save device token in nsuserdefault NSUserDefaults.standardUserDefaults().setObject(deviceToken, forKey: "deviceToken") NSUserDefaults.standardUserDefaults().synchronize() } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { //TODO : implementations } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { //TODO : implementations } }
mit
25d71cb5f0509b2cad0637ef1d52cff5
48.898876
285
0.729565
5.331333
false
false
false
false
nanthi1990/Typhoon-Swift-Example
PocketForecast/Model/ForecastConditions.swift
3
2245
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import Foundation public class ForecastConditions : NSObject, NSCoding { private(set) var date : NSDate? private(set) var low : Temperature? private(set) var high : Temperature? private(set) var summary : String? private(set) var imageUri : String? public init(date : NSDate, low : Temperature?, high : Temperature?, summary : String, imageUri : String) { self.date = date self.low = low self.high = high self.summary = summary self.imageUri = imageUri } public required init(coder : NSCoder) { self.date = coder.decodeObjectForKey("date") as? NSDate self.low = coder.decodeObjectForKey("low") as? Temperature self.high = coder.decodeObjectForKey("high") as? Temperature self.summary = coder.decodeObjectForKey("summary") as? String self.imageUri = coder.decodeObjectForKey("imageUri") as? String } public func longDayOfTheWeek() -> String? { let formatter = NSDateFormatter() formatter.dateFormat = "EEEE" return formatter.stringFromDate(self.date!) } public override var description: String { if self.low != nil && self.high != nil { return String(format: "Forecast : day=%@, low=%@, high=%@", self.longDayOfTheWeek()!, self.low!, self.high!) } else { return String(format: "Forecast : day=%@, low=%@, high=%@", self.longDayOfTheWeek()!, "", "") } } public func encodeWithCoder(coder : NSCoder) { coder.encodeObject(self.date!, forKey:"date") coder.encodeObject(self.low, forKey:"low") coder.encodeObject(self.high, forKey:"high") coder.encodeObject(self.summary!, forKey:"summary") coder.encodeObject(self.imageUri!, forKey:"imageUri") } }
apache-2.0
1016825c87e65f57a0c601753f80f0e0
35.803279
120
0.591537
4.619342
false
false
false
false
LoopKit/LoopKit
LoopKit/DailyQuantitySchedule.swift
1
6518
// // DailyQuantitySchedule.swift // Naterade // // Created by Nathan Racklyeft on 2/12/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit public struct DailyQuantitySchedule<T: RawRepresentable>: DailySchedule { public typealias RawValue = [String: Any] public let unit: HKUnit var valueSchedule: DailyValueSchedule<T> public init?(unit: HKUnit, dailyItems: [RepeatingScheduleValue<T>], timeZone: TimeZone? = nil) { guard let valueSchedule = DailyValueSchedule<T>(dailyItems: dailyItems, timeZone: timeZone) else { return nil } self.unit = unit self.valueSchedule = valueSchedule } init(unit: HKUnit, valueSchedule: DailyValueSchedule<T>) { self.unit = unit self.valueSchedule = valueSchedule } public init?(rawValue: RawValue) { guard let rawUnit = rawValue["unit"] as? String, let valueSchedule = DailyValueSchedule<T>(rawValue: rawValue) else { return nil } self.unit = HKUnit(from: rawUnit) self.valueSchedule = valueSchedule } public var items: [RepeatingScheduleValue<T>] { return valueSchedule.items } public var timeZone: TimeZone { get { return valueSchedule.timeZone } set { valueSchedule.timeZone = newValue } } public var rawValue: RawValue { var rawValue = valueSchedule.rawValue rawValue["unit"] = unit.unitString return rawValue } public func between(start startDate: Date, end endDate: Date) -> [AbsoluteScheduleValue<T>] { return valueSchedule.between(start: startDate, end: endDate) } public func value(at time: Date) -> T { return valueSchedule.value(at: time) } } extension DailyQuantitySchedule: Codable where T: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.unit = HKUnit(from: try container.decode(String.self, forKey: .unit)) self.valueSchedule = try container.decode(DailyValueSchedule<T>.self, forKey: .valueSchedule) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(unit.unitString, forKey: .unit) try container.encode(valueSchedule, forKey: .valueSchedule) } private enum CodingKeys: String, CodingKey { case unit case valueSchedule } } extension DailyQuantitySchedule: CustomDebugStringConvertible { public var debugDescription: String { return String(reflecting: rawValue) } } public typealias SingleQuantitySchedule = DailyQuantitySchedule<Double> public extension DailyQuantitySchedule where T == Double { func quantity(at time: Date) -> HKQuantity { return HKQuantity(unit: unit, doubleValue: valueSchedule.value(at: time)) } func averageValue() -> Double { var total: Double = 0 for (index, item) in valueSchedule.items.enumerated() { var endTime = valueSchedule.maxTimeInterval if index < valueSchedule.items.endIndex - 1 { endTime = valueSchedule.items[index + 1].startTime } total += (endTime - item.startTime) * item.value } return total / valueSchedule.repeatInterval } func averageQuantity() -> HKQuantity { return HKQuantity(unit: unit, doubleValue: averageValue()) } func lowestValue() -> Double? { return valueSchedule.items.min(by: { $0.value < $1.value } )?.value } var quantities: [RepeatingScheduleValue<HKQuantity>] { return self.items.map { RepeatingScheduleValue<HKQuantity>(startTime: $0.startTime, value: HKQuantity(unit: unit, doubleValue: $0.value)) } } func quantities(using unit: HKUnit) -> [RepeatingScheduleValue<HKQuantity>] { return self.items.map { RepeatingScheduleValue<HKQuantity>(startTime: $0.startTime, value: HKQuantity(unit: unit, doubleValue: $0.value)) } } init?(unit: HKUnit, dailyQuantities: [RepeatingScheduleValue<HKQuantity>], timeZone: TimeZone? = nil) { guard let valueSchedule = DailyValueSchedule( dailyItems: dailyQuantities.map { RepeatingScheduleValue(startTime: $0.startTime, value: $0.value.doubleValue(for: unit)) }, timeZone: timeZone) else { return nil } self.unit = unit self.valueSchedule = valueSchedule } } public extension DailyQuantitySchedule where T == DoubleRange { init?(unit: HKUnit, dailyQuantities: [RepeatingScheduleValue<ClosedRange<HKQuantity>>], timeZone: TimeZone? = nil) { guard let valueSchedule = DailyValueSchedule( dailyItems: dailyQuantities.map { RepeatingScheduleValue(startTime: $0.startTime, value: $0.value.doubleRange(for: unit)) }, timeZone: timeZone) else { return nil } self.unit = unit self.valueSchedule = valueSchedule } } extension DailyQuantitySchedule: Equatable where T: Equatable { public static func == (lhs: DailyQuantitySchedule<T>, rhs: DailyQuantitySchedule<T>) -> Bool { return lhs.valueSchedule == rhs.valueSchedule && lhs.unit.unitString == rhs.unit.unitString } } extension DailyQuantitySchedule where T: Numeric { public static func * (lhs: DailyQuantitySchedule, rhs: DailyQuantitySchedule) -> DailyQuantitySchedule { let unit = lhs.unit.unitMultiplied(by: rhs.unit) let schedule = DailyValueSchedule.zip(lhs.valueSchedule, rhs.valueSchedule).map(*) return DailyQuantitySchedule(unit: unit, valueSchedule: schedule) } } extension DailyQuantitySchedule where T: FloatingPoint { public static func / (lhs: DailyQuantitySchedule, rhs: DailyQuantitySchedule) -> DailyQuantitySchedule { let unit = lhs.unit.unitDivided(by: rhs.unit) let schedule = DailyValueSchedule.zip(lhs.valueSchedule, rhs.valueSchedule).map(/) return DailyQuantitySchedule(unit: unit, valueSchedule: schedule) } }
mit
85339d3b620d7f01c532aa127dc87bc8
31.103448
108
0.638177
4.71222
false
false
false
false
LoopKit/LoopKit
LoopKitUI/Views/LevelMaskView.swift
1
2737
// // LevelMaskView.swift // Loop // // Created by Nate Racklyeft on 8/28/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit // Displays a variable-height level indicator, masked by an image. // Inspired by https://github.com/carekit-apple/CareKit/blob/master/CareKit/CareCard/OCKHeartView.h public class LevelMaskView: UIView { var firstDataUpdate = true var value: Double = 1.0 { didSet { animateFill(duration: firstDataUpdate ? 0 : 1.25) firstDataUpdate = false } } private var clampedValue: Double { return value.clamped(to: 0...1.0) } @IBInspectable var maskImage: UIImage? { didSet { fillView?.removeFromSuperview() mask?.removeFromSuperview() maskImageView?.removeFromSuperview() guard let maskImage = maskImage else { fillView = nil mask = nil maskImageView = nil return } mask = UIView() maskImageView = UIImageView(image: maskImage) maskImageView!.frame = CGRect(origin: .zero, size: frame.size) maskImageView!.contentMode = .scaleAspectFit mask!.addSubview(maskImageView!) clipsToBounds = true fillView = UIView() fillView!.backgroundColor = tintColor addSubview(fillView!) } } private var fillView: UIView? private var maskImageView: UIView? override public func layoutSubviews() { super.layoutSubviews() guard let maskImageView = maskImageView else { return } let maskImageViewSize = maskImageView.frame.size mask?.frame = CGRect(origin: .zero, size: maskImageViewSize) mask?.center = CGPoint(x: bounds.midX, y: bounds.midY) self.maskImageView?.frame = mask?.bounds ?? bounds if (fillView?.layer.animationKeys()?.count ?? 0) == 0 { updateFillViewFrame() } } override public func tintColorDidChange() { super.tintColorDidChange() fillView?.backgroundColor = tintColor } private func animateFill(duration: TimeInterval) { UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState, animations: { self.updateFillViewFrame() }, completion: nil) } private func updateFillViewFrame() { guard let maskViewFrame = mask?.frame else { return } var fillViewFrame = maskViewFrame fillViewFrame.origin.y = maskViewFrame.maxY fillViewFrame.size.height = -CGFloat(clampedValue) * maskViewFrame.height fillView?.frame = fillViewFrame } }
mit
47c4cc8a3739af1cdd056b75874f38eb
27.5
103
0.61769
4.983607
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/Components/PXSummaryComposer+AddRow.swift
1
2558
import Foundation extension PXSummaryComposer { func chargesRow() -> PXOneTapSummaryRowData { let amount = getChargesAmount() let shouldDisplayHelper = shouldDisplayChargesHelp let helperImage = shouldDisplayHelper ? helpIcon(color: UIColor.Andes.blueMP500) : nil let amountToShow = Utils.getAmountFormated(amount: amount, forCurrency: currency) let defaultChargeText = "Cargos".localized let chargeText = getChargesLabel() ?? additionalInfoSummary?.charges ?? defaultChargeText let row = PXOneTapSummaryRowData(title: chargeText, value: amountToShow, highlightedColor: UIColor.Andes.gray550, alpha: textTransparency, isTotal: false, image: helperImage, type: .charges) return row } func discountRow() -> PXOneTapSummaryRowData? { guard let discount = getDiscount() else { printError("Discount is required to add the discount row") return nil } let discountToShow = Utils.getAmountFormated(amount: discount.couponAmount, forCurrency: currency) let helperImage = helpIcon(color: discountColor()) let row = PXOneTapSummaryRowData( title: discount.getDiscountDescription(), value: "- \(discountToShow)", highlightedColor: discountColor(), alpha: textTransparency, isTotal: false, image: helperImage, type: .discount, discountOverview: getDiscountOverview(), briefColor: discountBriefColor() ) return row } func purchaseRow(haveDiscount: Bool) -> PXOneTapSummaryRowData { let title = "total_row_title_default".localized let row = PXOneTapSummaryRowData( title: haveDiscount ? title : yourPurchaseSummaryTitle(), value: yourPurchaseToShow(), highlightedColor: summaryColor(), alpha: textTransparency, isTotal: haveDiscount, image: nil, type: .generic ) return row } func totalToPayRow() -> PXOneTapSummaryRowData { let totalAmountToShow = Utils.getAmountFormated(amount: amountHelper.amountToPay, forCurrency: currency) let row = PXOneTapSummaryRowData( title: "total_row_title_default".localized, value: totalAmountToShow, highlightedColor: summaryColor(), alpha: textTransparency, isTotal: true, image: nil, type: .generic ) return row } }
mit
53a58f8607549a9006e5d943e366bde6
38.96875
198
0.639171
4.863118
false
false
false
false
chenyun122/StepIndicator
StepIndicatorDemo/ViewController.swift
1
4457
// // ViewController.swift // StepIndicator // // Created by Yun Chen on 2017/7/14. // Copyright © 2017 Yun CHEN. All rights reserved. // import UIKit class ViewController: UIViewController,UIScrollViewDelegate { @IBOutlet weak var stepIndicatorView:StepIndicatorView! @IBOutlet weak var scrollView:UIScrollView! private var isScrollViewInitialized = false override func viewDidLoad() { super.viewDidLoad() // In this demo, the customizations have been done in Storyboard. // Customization by coding: //self.stepIndicatorView.numberOfSteps = 5 //self.stepIndicatorView.currentStep = 0 //self.stepIndicatorView.circleColor = UIColor(red: 179.0/255.0, green: 189.0/255.0, blue: 194.0/255.0, alpha: 1.0) //self.stepIndicatorView.circleTintColor = UIColor(red: 0.0/255.0, green: 180.0/255.0, blue: 124.0/255.0, alpha: 1.0) //self.stepIndicatorView.circleStrokeWidth = 3.0 //self.stepIndicatorView.circleRadius = 10.0 //self.stepIndicatorView.lineColor = self.stepIndicatorView.circleColor //self.stepIndicatorView.lineTintColor = self.stepIndicatorView.circleTintColor //self.stepIndicatorView.lineMargin = 4.0 //self.stepIndicatorView.lineStrokeWidth = 2.0 //self.stepIndicatorView.displayNumbers = false //indicates if it displays numbers at the center instead of the core circle //self.stepIndicatorView.direction = .leftToRight //self.stepIndicatorView.showFlag = true // Example for apply constraints programmatically, enable it for test. //self.applyNewConstraints() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !isScrollViewInitialized { isScrollViewInitialized = true self.initScrollView() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func initScrollView() { self.scrollView.contentSize = CGSize(width: self.scrollView.frame.width * CGFloat(self.stepIndicatorView.numberOfSteps + 1), height: self.scrollView.frame.height) let labelHeight = self.scrollView.frame.height / 2.0 let halfScrollViewWidth = self.scrollView.frame.width / 2.0 for i in 1 ... self.stepIndicatorView.numberOfSteps + 1 { let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 100)) if i<=self.stepIndicatorView.numberOfSteps { label.text = "\(i)" } else{ label.text = "You're done!" } label.textAlignment = NSTextAlignment.center label.font = UIFont.systemFont(ofSize: 35) label.textColor = UIColor.lightGray label.center = CGPoint(x: halfScrollViewWidth * (CGFloat(i - 1) * 2.0 + 1.0), y:labelHeight) self.scrollView.addSubview(label) } } // MARK: - UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let pageIndex = scrollView.contentOffset.x / scrollView.frame.size.width stepIndicatorView.currentStep = Int(pageIndex) } // MARK: - More Examples // Example for applying constraints programmatically func applyNewConstraints() { // Hold the weak object guard let stepIndicatorView = self.stepIndicatorView else { return } // Remove the constraints made in Storyboard before stepIndicatorView.removeFromSuperview() stepIndicatorView.removeConstraints(stepIndicatorView.constraints) self.view.addSubview(stepIndicatorView) // Add new constraints programmatically stepIndicatorView.widthAnchor.constraint(equalToConstant: 263.0).isActive = true stepIndicatorView.heightAnchor.constraint(equalToConstant: 80.0).isActive = true stepIndicatorView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true stepIndicatorView.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor, constant:30.0).isActive = true self.scrollView.topAnchor.constraint(equalTo: stepIndicatorView.bottomAnchor, constant: 8.0).isActive = true } }
mit
74e292f3b3aba65f8a0e7d2431c496d5
39.880734
170
0.665395
4.827736
false
false
false
false
Arthraim/ENIL
ENIL/AppDelegate.swift
1
2113
// // AppDelegate.swift // ENIL // // Created by Arthur Wang on 2/20/17. // Copyright © 2017 YANGAPP. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var viewController: ViewController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) viewController = ViewController() window?.rootViewController = UINavigationController.init(rootViewController: viewController!) window?.makeKeyAndVisible() if let url: URL = launchOptions?[UIApplication.LaunchOptionsKey.url] as? URL { updateUI(content: extractTextFromURL(url: url), shouldDelay: true) } else { updateUI(content: "NO AVAILABLE LINK\n\nClick link below to go back to MONSTER STRIKE, then send invitation link via LINE. It will automatically go back to this app.", shouldDelay: true) } return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { updateUI(content: extractTextFromURL(url: url), shouldDelay: false) return true } func extractTextFromURL(url: URL) -> String { return url.path.replacingOccurrences(of: "/text/", with: "") } // IMPORTANT // by the time didFinishLaunchingWithOptions invoked, self.viewController might not created yet // so add a delay here before update text if needed func updateUI(content: String, shouldDelay: Bool) { let deadline = shouldDelay ? DispatchTime.now() + 1 : DispatchTime.now() DispatchQueue.main.asyncAfter(deadline: deadline) { [unowned self] in self.viewController?.updateText(text: content) if let presented = self.viewController?.presentedViewController { presented.dismiss(animated: false, completion: nil) } } } }
mit
fefc9ba278336965cf7f9f9e926e103a
36.052632
179
0.668087
4.900232
false
false
false
false
jay18001/brickkit-ios
Example/Source/Examples/HorizontalScroll/BlockHorizontalViewController.swift
1
1741
// // BlockHorizontalViewController.swift // BrickKit // // Created by Ruben Cagnie on 9/13/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import BrickKit class BlockHorizontalViewController: BrickViewController { override class var brickTitle: String { return "1:1 Horizontal Scroll" } override class var subTitle: String { return "Scroll images as cubes" } let numberOfImages = 9 override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .brickBackground self.layout.scrollDirection = .horizontal self.brickCollectionView.registerBrickClass(ImageBrick.self) let section = BrickSection(backgroundColor: .brickGray1, bricks: [ ImageBrick(BrickIdentifiers.repeatLabel, width: .ratio(ratio: 1/4), height: .ratio(ratio: 1), backgroundColor: .brickGray3, dataSource: self), ], inset: 10, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)) section.repeatCountDataSource = self self.setSection(section) } } extension BlockHorizontalViewController: BrickRepeatCountDataSource { func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int { if identifier == BrickIdentifiers.repeatLabel { return numberOfImages } else { return 1 } } } extension BlockHorizontalViewController: ImageBrickDataSource { func imageForImageBrickCell(cell: ImageBrickCell) -> UIImage? { return UIImage(named: "image\(cell.index)") } func contentModeForImageBrickCell(imageBrickCell: ImageBrickCell) -> UIViewContentMode { return .scaleAspectFill } }
apache-2.0
140be6cd3e64f42d3f25e9f6a3c9fba4
28.491525
154
0.687931
4.846797
false
false
false
false
daniel-barros/TV-Calendar
TV Calendar/DetailShowTableViewCell.swift
1
2978
// // DetailShowTableViewCell.swift // TV Calendar // // Created by Daniel Barros López on 10/22/16. // Copyright © 2016 Daniel Barros. All rights reserved. // import ExtendedUIKit // TODO: Hide rating if title has two lines? /// Displays info for a show displayed by a ShowDetailViewController. class DetailShowTableViewCell: ShowTrackerTableViewCell, Reusable { @IBOutlet weak var networkLabel: UILabel! @IBOutlet weak var numberOfSeasonsLabel: UILabel! @IBOutlet weak var ratingLabel: UILabel! @IBOutlet weak var airingDateOrStatusOrPeriodLabel: UILabel! @IBOutlet weak var networkAndSeasonsStackView: UIStackView! override func configure(with show: Show, animated: Bool = false) { super.configure(with: show, animated: animated) updateLabelsText() updateLabelsVisibility(animated: animated) } } // MARK: - Helpers fileprivate extension DetailShowTableViewCell { func updateLabelsText() { guard let show = show else { return } let formatter = ShowFormatter(source: show) networkLabel.text = show.network numberOfSeasonsLabel.text = formatter.string(for: .numberOfSeasons) ratingLabel.text = formatter.string(for: .rating)?.prepending("Rating: ") switch show.status { case .airing?: airingDateOrStatusOrPeriodLabel.text = formatter.string(for: .airDayAndTime(usingPlurals: true))?.prepending("Airs ") case .waitingForNewSeason?: // Next season premiere if let premiereDate = show.currentSeasonPremiereDate as Date?, premiereDate.isInFuture, let nextSeason = show.currentSeason.value, let premiereString = formatter.string(for: .nextSeasonPremiereDate(appendingPremieresOnString: false)) { airingDateOrStatusOrPeriodLabel.text = "Season \(nextSeason) premieres on \(premiereString)" } // Status else { airingDateOrStatusOrPeriodLabel.text = formatter.string(for: .status(capitalization: .title)) } case .ended?: airingDateOrStatusOrPeriodLabel.text = formatter.string(for: .airPeriod) ?? formatter.string(for: .status(capitalization: .title)) case nil: airingDateOrStatusOrPeriodLabel.text = nil } } func updateLabelsVisibility(animated: Bool) { func performUpdates() { networkAndSeasonsStackView.isHidden = networkLabel.isHidden && numberOfSeasonsLabel.isHidden ratingLabel.isHidden = ratingLabel.text == nil } networkLabel.isHidden = networkLabel.text == nil numberOfSeasonsLabel.isHidden = numberOfSeasonsLabel.text == nil if animated { layoutIfNeeded() ShowTableViewCell.animateContentUpdate(updates: performUpdates) } else { performUpdates() } } }
gpl-3.0
fdb0b869d9ded90ff39f9118295ff80d
36.670886
142
0.65961
4.701422
false
false
false
false
sugarso/WWDC
WWDC/AboutTableViewController.swift
2
2696
// // AboutTableViewController.swift // SFParties // // Created by Genady Okrain on 3/24/15. // Copyright © 2016 Okrain. All rights reserved. // import UIKit import SafariServices import Smooch class AboutTableViewController: UITableViewController { func openTwitter(_ username: String) { let urls = ["tweetbot://current/user_profile/\(username)", "twitterrific://current/profile?screen_name=\(username)", "twitter://user?screen_name=\(username)"] for url in urls { if let url = URL(string: url), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) return } } openURL("https://twitter.com/\(username)") } func openURL(_ string: String) { if let url = URL(string: string) { let safariViewController = SFSafariViewController(url: url) present(safariViewController, animated: true, completion: nil) } } @IBAction func close(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } @IBAction func share(_ sender: AnyObject) { let text = "Never miss a cool party with Parties for WWDC 🎉" if let url = URL(string: "https://itunes.apple.com/us/app/parties-for-wwdc/id879924066?ls=1&mt=8") { let activityItems = [text, url] as [Any] let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) present(activityViewController, animated: true, completion: nil) } } // MARK: UITableViewControllerDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if indexPath.section == 0 { if indexPath.row == 0 { if let url = URL(string: "itms-apps://itunes.apple.com/app/id879924066?action=write-review"), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } else if indexPath.row == 1 { openTwitter("genadyo") } else if indexPath.row == 2 { Smooch.show() } } else if indexPath.section == 1 { if indexPath.row == 0 { openURL("https://github.com/joeldev/JLRoutes") } else if indexPath.row == 1 { openURL("https://useiconic.com/open/") } else if indexPath.row == 2 { openURL("https://github.com/pinterest/PINRemoteImage") } } } }
mit
7deff5bb783e90c5109152da747c556d
37.457143
166
0.602526
4.427632
false
false
false
false
SheffieldKevin/MovingImagesDemo
Zukini Demo/ZukiniRendererView.swift
1
1969
// ZukiniRendererView.swift // MovingImages Demo // // Copyright (c) 2015 Zukini Ltd. import Cocoa import MovingImages class ZukiniRendererView: NSView { var drawDictionary:[String:AnyObject]? var drawWidth:CGFloat { get { let theWidth = self.frame.width - 8.0 if theWidth < 0.0 { return 0 } else { return theWidth } } } var drawHeight:CGFloat { get { let theHeight = self.frame.height - 8.0 if theHeight < 0.0 { return 0 } else { return theHeight } } } func makeNewRenderer(miContext miContext:MIContext) { simpleRenderer = MISimpleRenderer(MIContext: miContext) } override func drawRect(dirtyRect: NSRect) { let theContext = NSGraphicsContext.currentContext()!.CGContext CGContextSetTextMatrix(theContext, CGAffineTransformIdentity) drawOutlineAndInsetDrawing(theContext) if let drawDict = self.drawDictionary, let theRenderer = self.simpleRenderer { theRenderer.drawDictionary(drawDict, intoCGContext: theContext) } } private var simpleRenderer:MISimpleRenderer? // Only call from within drawRect. private func drawOutlineAndInsetDrawing(context: CGContextRef) -> Void { let insetRect = CGRectInset(self.bounds, 1.0, 1.0) NSColor.lightGrayColor().setStroke() CGContextSetLineWidth(context, 2.0) CGContextStrokeRect(context, insetRect) let innerInsetRect = CGRectInset(insetRect, 1.0, 1.0) NSColor(deviceWhite: 0.9, alpha: 1.0).setFill() CGContextFillRect(context, innerInsetRect) let clipRect = CGRectInset(self.bounds, 4.0, 4.0) CGContextClipToRect(context, clipRect) CGContextTranslateCTM(context, 4.0, 4.0) } }
mit
697f84a9a3b7edb7c275b19e1f94074e
28.38806
76
0.607415
4.547344
false
false
false
false
BelledonneCommunications/linphone-iphone
Classes/Swift/FileUtil.swift
1
4152
/* * Copyright (c) 2010-2020 Belledonne Communications SARL. * * This file is part of linphone-iphone * * 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 import linphonesw @objc class FileUtil: NSObject { public class func bundleFilePath(_ file: NSString) -> String? { return Bundle.main.path(forResource: file.deletingPathExtension, ofType: file.pathExtension) } public class func bundleFilePathAsUrl(_ file: NSString) -> URL? { if let bPath = bundleFilePath(file) { return URL.init(fileURLWithPath: bPath) } return nil } public class func documentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } public class func libraryDirectory() -> URL { let paths = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } public class func sharedContainerUrl(appGroupName:String) -> URL { return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupName)! } @objc public class func ensureDirectoryExists(path:String) { if !FileManager.default.fileExists(atPath: path) { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) } catch { print(error) } } } public class func ensureFileExists(path:String) { if !FileManager.default.fileExists(atPath: path) { FileManager.default.createFile(atPath: path, contents: nil, attributes: nil) } } public class func fileExists(path:String) -> Bool { return FileManager.default.fileExists(atPath: path) } public class func fileExistsAndIsNotEmpty(path:String) -> Bool { guard FileManager.default.fileExists(atPath: path) else {return false} do { let attribute = try FileManager.default.attributesOfItem(atPath: path) if let size = attribute[FileAttributeKey.size] as? NSNumber { return size.doubleValue > 0 } else { return false } } catch { print(error) return false } } public class func write(string:String, toPath:String) { do { try string.write(to: URL(fileURLWithPath:toPath), atomically: true, encoding: String.Encoding.utf8) } catch { print(error) } } public class func delete(path:String) { do { try FileManager.default.removeItem(atPath: path) print("FIle \(path) was removed") } catch { print("Error deleting file at path \(path) error is \(error)") } } public class func mkdir(path:String) { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) print("Dir \(path) was created") } catch { print("Error creating dir at path \(path) error is \(error)") } } public class func copy(_ fromPath:String, _ toPath: String, overWrite:Bool) { do { if (overWrite && fileExists(path: toPath)) { delete(path: toPath) } try FileManager.default.copyItem(at: URL(fileURLWithPath:fromPath), to: URL(fileURLWithPath:toPath)) } catch { print(error) } } // For debugging public class func showListOfFilesInSharedDir(appGroupName:String) { let fileManager = FileManager.default do { let fileURLs = try fileManager.contentsOfDirectory(at: FileUtil.sharedContainerUrl(appGroupName: appGroupName), includingPropertiesForKeys: nil) fileURLs.forEach{print($0)} } catch { print("Error while enumerating files \(error.localizedDescription)") } } }
gpl-3.0
55ac6371e801df041495a0d437671324
28.870504
148
0.723025
3.77798
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/QiscusCore.swift
1
11311
// // QiscusCore.swift // Qiscus // // Created by Qiscus on 07/03/18. // Copyright © 2018 Qiscus Pte Ltd. All rights reserved. // import Foundation // MARK: TODO Remove realm here import RealmSwift extension Qiscus { // Public class API to get room @objc public class func clearMessages(inChannels channels:[String], onSuccess:@escaping ([QRoom],[String])->Void, onError:@escaping (Int)->Void){ QRoomService.clearMessages(inRoomsChannel: channels, onSuccess: { (rooms, channels) in onSuccess(rooms,channels) }) { (statusCode) in onError(statusCode) } } @objc public class func prepareView(witCompletion completion: @escaping (([QiscusChatVC])->Void)){ if Thread.isMainThread { let allRoom = QRoom.all() var allView = [QiscusChatVC]() for room in allRoom { if Qiscus.chatRooms[room.id] == nil { Qiscus.chatRooms[room.id] = room } if Qiscus.shared.chatViews[room.id] == nil { let chatView = QiscusChatVC() chatView.chatRoom = room chatView.prefetch = true chatView.viewDidLoad() chatView.viewWillAppear(false) chatView.viewDidAppear(false) chatView.view.layoutSubviews() chatView.inputBar.layoutSubviews() chatView.inputText.commonInit() Qiscus.shared.chatViews[room.id] = chatView allView.append(chatView) } } completion(allView) }else{ completion([QiscusChatVC]()) } } @objc public class func prepareView(){ if Thread.isMainThread { let allRoom = QRoom.all() for room in allRoom { if Qiscus.chatRooms[room.id] == nil { Qiscus.chatRooms[room.id] = room } if Qiscus.shared.chatViews[room.id] == nil { let chatView = QiscusChatVC() chatView.chatRoom = room chatView.prefetch = true chatView.viewDidLoad() chatView.viewWillAppear(false) chatView.viewDidAppear(false) chatView.view.layoutSubviews() chatView.inputBar.layoutSubviews() chatView.inputText.commonInit() Qiscus.shared.chatViews[room.id] = chatView } } } } @objc public class func room(withId roomId:String, onSuccess:@escaping ((QRoom)->Void),onError:@escaping ((String)->Void)){ let service = QChatService() var needToLoad = true func loadRoom(){ service.room(withId: roomId, onSuccess: { (room) in if !room.isInvalidated { onSuccess(room) }else{ Qiscus.printLog(text: "localRoom has been deleted") onError("localRoom has been deleted") } }) { (error) in onError(error) } } if let room = QRoom.room(withId: roomId){ if room.comments.count > 0 { onSuccess(room) }else{ loadRoom() } }else{ loadRoom() } } @objc public class func room(withChannel channelName:String, title:String = "", avatarURL:String, onSuccess:@escaping ((QRoom)->Void),onError:@escaping ((String)->Void)){ let service = QChatService() var needToLoad = true var room:QRoom? if QRoom.room(withUniqueId: channelName) != nil{ room = QRoom.room(withUniqueId: channelName) if room!.comments.count > 0 { needToLoad = false } } if !needToLoad { onSuccess(room!) }else{ service.room(withUniqueId: channelName, title: title, avatarURL: avatarURL, onSuccess: { (room) in onSuccess(room) }, onError: { (error) in onError(error) }) } } @objc public class func newRoom(withUsers usersId:[String], roomName: String, avatarURL:String = "", onSuccess:@escaping ((QRoom)->Void),onError:@escaping ((String)->Void)){ let service = QChatService() if roomName.trimmingCharacters(in: .whitespacesAndNewlines) != "" { service.createRoom(withUsers: usersId, roomName: roomName, avatarURL: avatarURL, onSuccess: onSuccess, onError: onError) }else{ onError("room name can not be empty string") } } @objc public class func room(withUserId userId:String, onSuccess:@escaping ((QRoom)->Void),onError:@escaping ((String)->Void)){ let service = QChatService() var needToLoad = true var room:QRoom? if QRoom.room(withUser: userId) != nil{ room = QRoom.room(withUser: userId) if room!.comments.count > 0 { needToLoad = false } } if !needToLoad { onSuccess(room!) }else{ service.room(withUser: userId, onSuccess: { (room) in onSuccess(room) }, onError: { (error) in onError(error) }) } } // MARK: - Room List @objc public class func roomList(withLimit limit:Int, page:Int, onSuccess:@escaping (([QRoom], Int, Int, Int)->Void),onError:@escaping ((String)->Void)){ QChatService.roomList(onSuccess: { (rooms, totalRoom, currentPage, limit) in onSuccess(rooms, totalRoom, currentPage, limit) }, onFailed: {(error) in onError(error) }) } @objc public class func fetchAllRoom(loadLimit:Int = 0, onSuccess:@escaping (([QRoom])->Void),onError:@escaping ((String)->Void), onProgress: ((Double,Int,Int)->Void)? = nil){ var page = 1 var limit = 100 if loadLimit > 0 { limit = loadLimit } func load(onPage:Int) { QChatService.roomList(withLimit: limit, page: page, showParticipant: true, onSuccess: { (rooms, totalRoom, currentPage, limit) in if totalRoom > (limit * (currentPage - 1)) + rooms.count{ page += 1 load(onPage: page) }else{ let rooms = QRoom.all() onSuccess(rooms) } }, onFailed: { (error) in onError(error) }) { (progress, loadedRoomm, totalRoom) in onProgress?(progress,loadedRoomm,totalRoom) } } load(onPage: 1) } @objc public class func fetchAllRoomWithLimit(loadLimit:Int = 30,page:Int = 1, onSuccess:@escaping (([QRoom]?,Bool)->Void),onError:@escaping ((String)->Void), onProgress: ((Double,Int,Int)->Void)? = nil){ func load(onPage:Int) { QChatService.roomList(withLimit: loadLimit, page: page, showParticipant: true, onSuccess: { (rooms, totalRoom, currentPage, limit) in if totalRoom > (limit * (currentPage - 1)) + rooms.count{ let rooms = QRoom.all() onSuccess(rooms,true) }else{ onSuccess(rooms,false) } }, onFailed: { (error) in onError(error) }) { (progress, loadedRoomm, totalRoom) in onProgress?(progress,loadedRoomm,totalRoom) } } load(onPage: page) } @objc public class func roomInfo(withId id:String, lastCommentUpdate:Bool = true, onSuccess:@escaping ((QRoom)->Void), onError: @escaping ((String)->Void)){ QChatService.roomInfo(withId: id, lastCommentUpdate: lastCommentUpdate, onSuccess: { (room) in onSuccess(room) }) { (error) in onError(error) } } @objc public class func roomsInfo(withIds ids:[String], onSuccess:@escaping (([QRoom])->Void), onError: @escaping ((String)->Void)){ QChatService.roomsInfo(withIds: ids, onSuccess: { (rooms) in onSuccess(rooms) }) { (error) in onError(error) } } @objc public class func channelInfo(withName name:String, onSuccess:@escaping ((QRoom)->Void), onError: @escaping ((String)->Void)){ QChatService.roomInfo(withUniqueId: name, onSuccess: { (room) in if !room.isInvalidated { onSuccess(room) }else{ Qiscus.channelInfo(withName: name, onSuccess: onSuccess, onError: onError) } }) { (error) in onError(error) } } @objc public class func channelsInfo(withNames names:[String], onSuccess:@escaping (([QRoom])->Void), onError: @escaping ((String)->Void)){ QChatService.roomsInfo(withUniqueIds: names, onSuccess: { (rooms) in onSuccess(rooms) }) { (error) in onError(error) } } public class func removeAllFile(){ let filemanager = FileManager.default let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString let destinationPath = documentsPath.appendingPathComponent("Qiscus") do { try filemanager.removeItem(atPath: destinationPath) } catch { Qiscus.printLog(text: "Could not clear Qiscus folder: \(error.localizedDescription)") } } public class func cancellAllRequest(){ let sessionManager = QiscusService.session sessionManager.session.getAllTasks { (allTask) in allTask.forEach({ (task) in task.cancel() }) } } public class func removeDB(){ let realm = try! Realm(configuration: Qiscus.dbConfiguration) realm.refresh() try! realm.write { realm.deleteAll() } let filemanager = FileManager.default do { try filemanager.removeItem(at: Qiscus.dbConfiguration.fileURL!) } catch { Qiscus.printLog(text: "Could not clear Qiscus folder: \(error.localizedDescription)") } } internal class func logFile()->String{ let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString let logPath = documentsPath.appendingPathComponent("Qiscus.log") return logPath } public class func removeLogFile(){ let filemanager = FileManager.default let logFilePath = Qiscus.logFile() do { try filemanager.removeItem(atPath: logFilePath) } catch { Qiscus.printLog(text: "Could not clear Qiscus folder: \(error.localizedDescription)") } } public class func backgroundSync(){ QChatService.backgroundSync() } public class func syncEvent(){ QChatService.syncEvent() } }
mit
421cc481824bab882ac8fc490bed9106
37.469388
208
0.54863
4.786289
false
false
false
false
JaCaLla/ArchTemp
ArchTemp/ArchTemp/DataLayer/Model/Place.swift
1
1261
// // Place.swift // ArchTemp // // Created by 08APO0516 on 28/08/2017. // Copyright © 2017 08APO0516ja. All rights reserved. // import Foundation import RealmSwift class Place:Object { dynamic var urlPicture:String = "" dynamic var name:String = "" dynamic var country:String = "" var imgPicture:UIImage? // MARK: - Initializers convenience init(name: String, country:String, urlPicture: String) { self.init() self.name = name self.country = country self.urlPicture = urlPicture } override class func primaryKey() -> String? { return "name" } override class func indexedProperties() -> [String] { return ["name"] } override static func ignoredProperties() -> [String] { return ["imgPicture"] } func getImage(completion:((UIImage,Bool) -> Void)) { guard imgPicture == nil else { completion(self.imgPicture!,false) return } if let _data = NSData(contentsOf: URL(string: self.urlPicture)!), let _image = UIImage(data: _data as Data) { self.imgPicture = _image completion(self.imgPicture!, true) } } }
mit
e0bcdf8ec84a6ec10c4059efa59926e5
20.724138
73
0.574603
4.228188
false
false
false
false
BENMESSAOUD/RSS
News/Utils/UIAlertController.Helper.swift
1
1548
// // UIAlertController.Helper.swift // DudeChat // // Created by Mahmoud ben messaoud on 01/12/2016. // Copyright © 2016 Pixit Technology. All rights reserved. // import Foundation import UIKit extension UIAlertController{ public func addCancelActionWithTitle(_ title:String){ let cancelAction = UIAlertAction(title: title, style: .cancel, handler: { (alertAction) in self.dismiss(animated: true, completion: nil) }) self.addAction(cancelAction) } func show() { present(animated: true, completion: nil) } func present(animated: Bool, completion: (() -> Void)?) { if let rootVC = UIApplication.shared.keyWindow?.rootViewController { presentFromController(controller: rootVC, animated: animated, completion: completion) } } private func presentFromController(controller: UIViewController, animated: Bool, completion: (() -> Void)?) { if let navVC = controller as? UINavigationController, let visibleVC = navVC.visibleViewController { presentFromController(controller: visibleVC, animated: animated, completion: completion) } else if let tabVC = controller as? UITabBarController, let selectedVC = tabVC.selectedViewController { presentFromController(controller: selectedVC, animated: animated, completion: completion) } else { controller.present(self, animated: animated, completion: completion); } } }
mit
5ea7a3db3470627bb68ee27086951684
35.833333
113
0.657401
5.072131
false
false
false
false
divljiboy/IOSChatApp
Quick-Chat/MagicChat/UI/ViewController/BaseViewControllerV.swift
1
2357
// // BaseViewControllerV.swift // MagicChat // // Created by Ivan Divljak on 5/17/18. // Copyright © 2018 Mexonis. All rights reserved. // import UIKit class BaseViewController: UIViewController { let colors: [UIColor] = [UIColor.mtsNavigationBarColor, UIColor.mtsSecondNavigationBarColor] let locations: [NSNumber] = [0.0, 1] weak var appDelegate: AppDelegate! let progressHUD = ProgressHUD(text: "Please wait") override func viewDidLoad() { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } self.appDelegate = appDelegate super.viewDidLoad() self.navigationController?.navigationBar.barTintColor = UIColor(red: 177 / 255, green: 13 / 255, blue: 40 / 255, alpha: 1) self.navigationController?.navigationBar.tintColor = UIColor.white self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow") self.navigationController?.navigationBar.isTranslucent = false self.navigationController?.navigationBar.prefersLargeTitles = false self.view.addSubview(progressHUD) self.setVisibleNavigation() stopActivityIndicatorSpinner() } /** Show spinner. */ func startActivityIndicatorSpinner() { DispatchQueue.main.async { self.progressHUD.show() } } /** Set visible navigation bar and it's style. - Parameter color: Navigation bar color. - Parameter borderColor: Navigation bar border color. */ func setVisibleNavigation() { navigationController?.navigationBar.setGradientBackground(colors: colors, locations: locations) } /** Hide spinner. */ func stopActivityIndicatorSpinner() { DispatchQueue.main.async { self.progressHUD.hide() } } } extension UIColor { class var mtsNavigationBarColor: UIColor { return UIColor(red: 5 / 255, green: 117 / 255, blue: 230 / 255, alpha: 1) } class var mtsSecondNavigationBarColor: UIColor { return UIColor(red: 38 / 255, green: 208 / 255, blue: 206 / 255, alpha: 1) } }
mit
cf4674c9f789923c1f91a0f7b80bf429
29.597403
130
0.65365
4.887967
false
false
false
false
swift-gtk/SwiftGTK
Sources/UIKit/Adjustment.swift
1
6776
public class Adjustment: Object { /* internal var n_Adjustment: UnsafeMutablePointer<GtkAdjustment> internal init(n_Adjustment: UnsafeMutablePointer<GtkAdjustment>) { self.n_Adjustment = n_Adjustment super.init(n_Object: UnsafeMutablePointer<GObject>(n_Adjustment)) } */ /// Creates a new `Adjustment`. /// /// - Parameter value: the initial value /// - Parameter lower: the minimum value /// - Parameter upper: the maximum value /// - Parameter stepIncrement: the step increment /// - Parameter pageIncrement: pageIncrement /// - Parameter pageSize: the page size /* public convenience init(value: Double, lower: Double, upper: Double, stepIncrement: Double, pageIncrement: Double, pageSize: Double) { self.init(n_Adjustment: UnsafeMutablePointer<GtkAdjustment>( gtk_adjustment_new(gdouble(value), gdouble(lower), gdouble(upper), gdouble(stepIncrement), gdouble(pageIncrement), gdouble(pageSize)))) } */ /// The value of the adjustment. public var value: Double { set { gtk_adjustment_set_value(object.asGObject(), gdouble(newValue)) } get { return Double(gtk_adjustment_get_value(object.asGObject())) } } /// Updates the `value` property to ensure that the range between `lower` and /// `upper` is in the current page (i.e. between `value` and `value` + /// `pageSize`). If the range is larger than the page size, then only the /// start of it will be in the current page. /// /// A `valueChangedSignal` will be emitted if the value is changed. /// /// - Parameter lower: the lower value /// - Parameter upper: the upper value public func clampPage(lower: Double, upper: Double) { gtk_adjustment_clamp_page(object.asGObject(), gdouble(lower), gdouble(upper)) } /// Sets all properties of the adjustment at once. /// /// Use this function to avoid multiple emissions of the `changedSignal`. See /// `lower` property for an alternative way of compressing multiple emissions /// of `changedSignal` into one. /// /// - Parameter value: the new value /// - Parameter lower: the new minimum value /// - Parameter upper: the new maximum value /// - Parameter stepIncrement: the new step increment /// - Parameter pageIncrement: the new page increment /// - Parameter pageSize: the new page size public func configure(value: Double, lower: Double, upper: Double, stepIncrement: Double, pageIncrement: Double, pageSize: Double) { gtk_adjustment_configure(object.asGObject(), gdouble(value), gdouble(lower), gdouble(upper), gdouble(stepIncrement), gdouble(pageIncrement), gdouble(pageSize)) } /// The minimum value of the adjustment. public var lower: Double { set { gtk_adjustment_set_lower(object.asGObject(), gdouble(newValue)) } get { return Double(gtk_adjustment_get_lower(object.asGObject())) } } /// The page increment of the adjustment. public var pageIncrement: Double { set { gtk_adjustment_set_page_increment(object.asGObject(), gdouble(newValue)) } get { return Double(gtk_adjustment_get_page_increment(object.asGObject())) } } /// The page size of the adjustment. Note that the page-size is irrelevant and /// should be set to zero if the adjustment is used for a simple scalar value, /// e.g. in a `SpinButton`. public var pageSize: Double { set { gtk_adjustment_set_page_size(object.asGObject(), gdouble(newValue)) } get { return Double(gtk_adjustment_get_page_size(object.asGObject())) } } /// The step increment of the adjustment. public var stepIncrement: Double { set { gtk_adjustment_set_step_increment(object.asGObject(), gdouble(newValue)) } get { return Double(gtk_adjustment_get_step_increment(object.asGObject())) } } /// The maximum value of the adjustment. Note that values will be restricted /// by `upper - pageSize` if the page-size property is nonzero. public var upper: Double { set { gtk_adjustment_set_upper(object.asGObject(), gdouble(newValue)) } get { return Double(gtk_adjustment_get_upper(object.asGObject())) } } /// The smaller of step increment and page increment. public var minimumIncrement: Double { return Double(gtk_adjustment_get_minimum_increment(object.asGObject())) } // MARK: - Signals /// - Parameter box: the object which received the signal public typealias ChangedCallback = (_ adjustment: Adjustment) -> Void public typealias ChangedNative = ( UnsafeMutablePointer<GtkAdjustment>, UnsafeMutablePointer<gpointer>) -> Void /// Emitted when one or more of the `Adjustment` properties have been changed, /// other than the `value` property. public lazy var changedSignal: Signal<ChangedCallback, Adjustment, ChangedNative> = Signal(obj: self, signal: "changed", c_handler: { _, user_data in let data = unsafeBitCast(user_data, to: SignalData<Adjustment, ChangedCallback>.self) let adjustment = data.obj let action = data.function action(adjustment) }) /// - Parameter box: the object which received the signal public typealias ValueChangedCallback = (_ adjustment: Adjustment) -> Void public typealias ValueChangedNative = ( UnsafeMutablePointer<GtkAdjustment>, UnsafeMutablePointer<gpointer>) -> Void /// Emitted when the `value` property has been changed. public lazy var valueChangedSignal: Signal<ValueChangedCallback, Adjustment, ValueChangedNative> = Signal(obj: self, signal: "value-changed", c_handler: { _, user_data in let data = unsafeBitCast(user_data, to: SignalData<Adjustment, ValueChangedCallback>.self) let adjustment = data.obj let action = data.function action(adjustment) }) }
gpl-2.0
7944d9ea3768ec1eca27ab9980abbfd1
37.5
85
0.594008
4.741777
false
false
false
false
forwk1990/PropertyExchange
PropertyExchange/YPGestureVerifyViewController.swift
1
6875
// // YPGestureVerifyViewController.swift // PropertyExchange // // Created by itachi on 16/10/13. // Copyright © 2016年 com.itachi. All rights reserved. // import UIKit extension YPGestureVerifyViewController:CircleViewDelegate{ func circleView(_ view: PCCircleView, type: CircleViewType, didCompleteLoginGesture gesture: String, result equal: Bool) { if type == .verify { if equal { self.dismiss(animated: true, completion: { }) }else{ self.lockLabel.alpha = 1.0 self.lockLabel.showWarnMsgAndShake("手势密码不正确") UIView.animate(withDuration: 2.5, animations: { self.lockLabel.alpha = 0 }) } } } } class YPGestureVerifyViewController: UIViewController { fileprivate let lockPassword = "1235789" override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setupNavigationBar() } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.createSubviews() self.createLayoutSubviews() // 保存手势密码 PCCircleViewConst.saveGesture(self.lockPassword, key: gestureFinalSaveKey) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // 设置导航 private func setupNavigationBar(){ // 亮状态栏 UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: false) self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() } fileprivate func createSubviews(){ self.view.addSubview(self.weekLabel) self.view.addSubview(self.dateLabel) self.view.addSubview(self.userLogoImageView) self.view.addSubview(self.helloMessageLabel) self.view.addSubview(self.lockView) self.view.addSubview(self.lockLabel) self.view.addSubview(self.forgetGesturePasswordButton) self.view.addSubview(self.separatorLineView) self.view.addSubview(self.otherLoginButton) } fileprivate func createLayoutSubviews(){ self.weekLabel.snp.makeConstraints { (make) in make.left.equalTo(self.view).offset(18) make.top.equalTo(self.view).offset(28) } self.dateLabel.snp.makeConstraints { (make) in make.left.equalTo(self.weekLabel) make.top.equalTo(self.weekLabel.snp.bottom).offset(6) } self.userLogoImageView.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.width.height.equalTo(64) make.top.equalTo(self.view).offset(143) } self.helloMessageLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self.userLogoImageView) make.top.equalTo(self.userLogoImageView.snp.bottom).offset(10) } self.lockView.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.width.height.equalTo(250) make.top.equalTo(self.helloMessageLabel.snp.bottom).offset(35) } self.lockLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.top.equalTo(self.helloMessageLabel.snp.bottom).offset(15) } self.separatorLineView.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.height.equalTo(14) make.width.equalTo(1) make.bottom.equalTo(self.view).offset(-40) } self.forgetGesturePasswordButton.snp.makeConstraints { (make) in make.height.equalTo(14) make.right.equalTo(self.separatorLineView.snp.left).offset(-15) make.bottom.equalTo(self.separatorLineView) } self.otherLoginButton.snp.makeConstraints { (make) in make.height.equalTo(14) make.left.equalTo(self.separatorLineView.snp.right).offset(15) make.bottom.equalTo(self.separatorLineView) } } fileprivate lazy var weekLabel:UILabel = { let weekFormatter:DateFormatter = DateFormatter() weekFormatter.locale = Locale(identifier: "zh_CN") weekFormatter.dateFormat = "cccc" let _weekLabel = UILabel(); _weekLabel.textAlignment = .left _weekLabel.text = weekFormatter.string(from: Date()) _weekLabel.font = UIFont.boldSystemFont(ofSize: 18) _weekLabel.textColor = UIColor.colorWithHex(hex: 0x39404D) return _weekLabel }() fileprivate lazy var dateLabel:UILabel = { let dateFormatter:DateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "zh_CN") dateFormatter.dateFormat = "yyyy.MM.dd" let _dateLabel = UILabel() _dateLabel.font = UIFont.systemFont(ofSize: 12) _dateLabel.text = dateFormatter.string(from: Date()) _dateLabel.textColor = UIColor.colorWithHex(hex: 0x39404D) _dateLabel.textAlignment = .left return _dateLabel }() fileprivate lazy var userLogoImageView:UIImageView = { let _logoImageView = UIImageView() _logoImageView.image = UIImage(named: "userLogo") _logoImageView.layer.cornerRadius = 32 _logoImageView.clipsToBounds = true return _logoImageView }() fileprivate lazy var helloMessageLabel:UILabel = { let dateString = NSDate().hour >= 12 ? "下午" : "上午" let _helloMessageLabel = UILabel() _helloMessageLabel.text = "\(dateString)好!万先生" _helloMessageLabel.font = UIFont.systemFont(ofSize: 12) _helloMessageLabel.textColor = UIColor.colorWithHex(hex: 0x39404D) return _helloMessageLabel }() fileprivate lazy var lockView:PCCircleView = { let _lockView = PCCircleView(type: CircleViewType.verify, clip: true, arrow: false) _lockView.delegate = self return _lockView }() fileprivate lazy var lockLabel:PCLockLabel = { let _lockLabel = PCLockLabel() return _lockLabel }() fileprivate lazy var forgetGesturePasswordButton:UIButton = { let _forgetGesturePasswordButton = UIButton(type: .custom) _forgetGesturePasswordButton.setTitleColor(UIColor.colorWithHex(hex: 0x999999), for: .normal) _forgetGesturePasswordButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) _forgetGesturePasswordButton.setTitle("忘记手势密码", for: .normal) return _forgetGesturePasswordButton }() fileprivate lazy var separatorLineView:UIView = { let _separatorLineView = UIView() _separatorLineView.backgroundColor = UIColor.colorWithHex(hex: 0x999999) return _separatorLineView }() fileprivate lazy var otherLoginButton:UIButton = { let _otherLoginButton = UIButton(type: .custom) _otherLoginButton.setTitleColor(UIColor.colorWithHex(hex: 0x999999), for: .normal) _otherLoginButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) _otherLoginButton.setTitle("用其它帐号登陆", for: .normal) return _otherLoginButton }() }
mit
7770acd487f653bbae844588f2dfb3ed
30.71028
124
0.701592
4.158088
false
false
false
false
myfamilycooks/recipe.ios
recipe.ios/Services/TokenService.swift
1
1849
// // TokenService.swift // recipe.ios // // Created by Shaun Sargent on 3/11/18. // Copyright © 2018 My Family Cooks. All rights reserved. // import Foundation import Alamofire public struct TokenService{ var baseUrl:String init(){ self.baseUrl = Configuration.webUrl } func getToken(userName:String, password:String, completed:@escaping(_ succeeded:Bool, _ errorMessage:String?, _ token:TokenResponse?) ->()){ let url = "\(self.baseUrl)/token" let postDictionary = self.createPostDictionary(userName: userName, password: password) Alamofire.request(url, method: .post, parameters: postDictionary, encoding: JSONEncoding.default) .responseJSON { (responseData) in switch responseData.result{ case.success(let val): do{ let token = try JSONDecoder().decode(TokenResponse.self, from: responseData.data!) if let token = token.token{ SecurityService.currentToken = token } completed(true,nil,token) } catch(let serializationError){ completed(false,"Serialization error: \(serializationError.localizedDescription)", nil) } case .failure(let error): completed(false, error.localizedDescription, nil) } } } private func createPostDictionary(userName:String, password:String)->Parameters { var postData = [String:Any]() postData["userName"] = userName postData["password"] = password return postData } }
apache-2.0
7304986e0fe921568733af7edd47f881
31.421053
144
0.541667
5.5
false
false
false
false
WINKgroup/WinkKit
WinkKit/Core/Presentation/Views/WKCollectionView/WKCollectionViewDataSource.swift
1
5885
// // WKCollectionViewDataSource.swift // BuyBack // // Created by Rico Crescenzio on 22/11/17. // Copyright © 2017 Wink srl. All rights reserved. // import UIKit /// A concrete `UICollectionViewDataSource` that has some common method already implemented. /// /// - Important: This data source handles only 1 section. open class WKCollectionViewDataSource<T>: NSObject, UICollectionViewDataSource { // - MARK: Properties /// The array of item that managed by this dataSource. internal(set) open var items = [T]() /// The collection view that owns this dataSource. internal(set) public weak var collectionView: UICollectionView! // - MARK: Initializers /// Create the dataSource and attach it to the given collection view. public init(collectionView: UICollectionView) { self.collectionView = collectionView super.init() collectionView.dataSource = self } // - MARK: Methods /// Asks your data source object for the number of items in the specified section. /// Default returns items count. /// /// - Parameters: /// - collectionView: The collection view requesting this information.. /// - section: An index number identifying a section in collectionView. This index value is 0-based. /// - Returns: The number of rows in section. open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } /// Asks your data source object for the cell that corresponds to the specified item in the collection view. /// Your implementation of this method is responsible for creating, configuring, and returning the appropriate cell for the given item. You do this by calling the dequeueReusableCell(withReuseIdentifier:for:) method of the collection view and passing the reuse identifier that corresponds to the cell type you want. That method always returns a valid cell object. Upon receiving the cell, you should set any properties that correspond to the data of the corresponding item, perform any additional needed configuration, and return the cell. /// You do not need to set the location of the cell inside the collection view’s bounds. The collection view sets the location of each cell automatically using the layout attributes provided by its layout object. /// If isPrefetchingEnabled on the collection view is set to true then this method is called in advance of the cell appearing. Use the collectionView(_:willDisplay:forItemAt:) delegate method to make any changes to the appearance of the cell to reflect its visual state such as selection. /// This method must always return a valid view object. /// /// - Parameters: /// - collectionView: The collection view requesting this information. /// - indexPath: The index path that specifies the location of the item. /// - Returns: A configured cell object. A fatal error is thrown if this method is not overriden. open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { fatalError("collectionView(_:cellForItemAt:) not implemented") } /// Add an item into data source and update the collection view. /// /// - Parameters: /// - item: The new item that will be inserted in data source. open func add(_ item: T) { items.append(item) collectionView.insertItems(at: [IndexPath(row: items.count - 1, section: 0)]) } /// Remove item at index from data source and update the collection view. /// /// - Parameter index: The index of the item to be removed. open func remove(at index: Int) { items.remove(at: index) collectionView.deleteItems(at: [IndexPath(row: index, section: 0)]) } /// Replce the item in data source at specified index with new one. /// /// - Parameters: /// - item: The new item that will replace the old one. /// - index: The index of the old item. open func replace(_ item: T, at index: Int) { if items.count > index && index >= 0 { items[index] = item collectionView.reloadItems(at: [IndexPath(row: index, section: 0)]) } } /// Replace multiple items at the specified indexes and update collection view`. /// /// - Parameter items: Array of tuple of item & index. open func replace(items: [(item: T, index: Int)]) { var indexes = [Int]() items.forEach { (row: (item: T, index: Int)) -> Void in if self.items.count > row.index && row.index >= 0 { self.items[row.index] = row.item indexes.append(row.index) } } collectionView.reloadItems(at: indexes.map({ IndexPath(row: $0, section: 0) })) } /// Empty the data source and reload the collection view. open func clear() { let indexPaths = items.enumerated().map { (arg: (offset: Int, element: T)) in return IndexPath(row: arg.offset, section: 0) } items.removeAll() collectionView.deleteItems(at: indexPaths) } /// Clear and set new items to data source and call `reladData()` on collection view. /// /// - Parameter items: The new array of items. open func replaceAll(_ items: [T]) { self.items = items collectionView.reloadData() } } public extension WKCollectionViewDataSource where T: Equatable { /// Remove the item from the data source. /// /// - Parameter item: The item that will removed if found in data source. public func remove(_ item: T) { if let index = items.index(of: item) { remove(at: index) } } }
mit
365e9aae1d784c407ed39f57972dfd58
40.716312
543
0.655049
4.751212
false
false
false
false
EyreFree/EFQRCode
Examples/iOS/CGFloat+Example.swift
1
2261
// // CGFloat+.swift // EFQRCode // // Created by EyreFree on 2017/10/29. // // Copyright (c) 2017 EyreFree <[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 extension CGFloat { static let zeroHeight: CGFloat = leastNonzeroMagnitude // ~= 20 static func statusBar() -> CGFloat { #if os(iOS) // debugPrint("statusBar: \(UIApplication.shared.statusBarFrame.height)") return UIApplication.shared.statusBarFrame.height #else return 0 #endif } // ~= 44 static func navigationBar(_ controller: UIViewController?) -> CGFloat { if let navi = controller?.navigationController { // debugPrint("navigationBar: \(navi.navigationBar.frame.height)") return navi.navigationBar.frame.height } // debugPrint("navigationBar: 0") return 0 } // ~= 49 static func tabBar(_ controller: UIViewController?) -> CGFloat { if let tabBar = controller?.tabBarController { // debugPrint("tabBar: \(tabBar.tabBar.frame.height)") return tabBar.tabBar.frame.height } // debugPrint("tabBar: 0") return 0 } }
mit
ca0ca0c4f7b387f5b1f644b0b32875df
35.467742
81
0.678903
4.595528
false
false
false
false
jordane-quincy/M2_DevMobileIos
testDatabase/demoFA_storage_test/FileServices.swift
1
1549
// // FileServices.swift // demoFA_storage_test // // Created by MAC ISTV on 11/04/2017. // Copyright © 2017 DeptInfo. All rights reserved. // import Foundation import UIKit // Class that manage files class FileServices: UIViewController { public func createJSONFileFromString(JSONStringified: String) { let file = "exportJSON.json" //let data = JSONStringify.data(using: .utf8)! if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let path = dir.appendingPathComponent(file) //writing the file in the app directory do { try JSONStringified.write(to: path, atomically: false, encoding: String.Encoding.utf8) } catch {/* error handling here */} //reading do { let text2 = try String(contentsOf: path, encoding: String.Encoding.utf8) print(text2); // Trying to move the file in the app directory to iCloud using Document Picker let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(url: path, in: UIDocumentPickerMode.moveToService) documentPicker.modalPresentationStyle = UIModalPresentationStyle.fullScreen self.present(documentPicker, animated: true, completion: nil) } catch {/* error handling here */} } } }
mit
263e2b1021f03a9ac8375796a1521b46
33.4
150
0.593669
5.125828
false
false
false
false
kellanburket/franz
Sources/Franz/Group.swift
1
3932
// // Group.swift // Pods // // Created by Kellan Cummings on 1/26/16. // // import Foundation /** Base class for all Client Groups. */ class Group { fileprivate var _broker: Broker fileprivate var _clientId: String fileprivate var _groupProtocol: GroupProtocol fileprivate var _groupId: String fileprivate var _generationId: Int32 fileprivate var _version: ApiVersion = 0 private var _state: GroupState? /** Group Protocol */ var groupProtocol: String { return _groupProtocol.value } /** Generation Id */ var generationId: Int32 { return _generationId } /** Group Id */ var id: String { return _groupId } internal init( broker: Broker, clientId: String, groupProtocol: GroupProtocol, groupId: String, generationId: Int32 ) { _broker = broker _clientId = clientId _groupProtocol = groupProtocol _groupId = groupId _generationId = generationId } /** Retreive the state of the current group. - Parameter callback: a closure which takes a group id and a state of that group as its parameters */ func getState(_ callback: @escaping (String, GroupState) -> ()) { _broker.describeGroups(self.id, clientId: _clientId) { id, state in self._state = state callback(id, state) } } var topics = Set<TopicName>() internal(set) var assignedPartitions = [TopicName: [PartitionId]]() } /** A Consumer Group */ class ConsumerGroup: Group { internal init( broker: Broker, clientId: String, groupId: String, generationId: Int32 ) { super.init( broker: broker, clientId: clientId, groupProtocol: GroupProtocol.consumer, groupId: groupId, generationId: generationId ) } } /** An abstraction of a Broker's relationship to a group. */ class GroupMembership { var _group: Group var _memberId: String let members: [Member] /** A Group */ var group: Group { return _group } /** The Broker's id */ var memberId: String { return _memberId } init(group: Group, memberId: String, members: [Member]) { self._group = group self._memberId = memberId self.members = members } /** Sync the broker with the Group Coordinator */ func sync( _ topics: [TopicName: [PartitionId]], data: Data = Data(), callback: (() -> ())? = nil ) { group._broker.syncGroup( group.id, generationId: group.generationId, memberId: memberId, topics: topics, userData: data, version: group._version) { membership in for assignment in membership.partitionAssignment { self.group.assignedPartitions[assignment.topic] = assignment.partitions.map { $0 } } self.group.topics = Set(membership.partitionAssignment.map { $0.topic }) callback?() } } /** Leave the group - Parameter callback: called when the group has successfully been left */ func leave(_ callback: (() -> ())? = nil) { group._broker.leaveGroup( _group.id, memberId: memberId, clientId: _group._clientId, callback: callback ) } /** Issue a heartbeat request. - Parameter callback: called when the heartbeat request has successfully completed */ func heartbeat(_ callback: (() -> ())? = nil) { group._broker.heartbeatRequest( _group.id, generationId:_group._generationId, memberId: memberId, callback: callback ) } }
mit
b4daebaae83909171ee44ceb9a2bb499
21.468571
108
0.561038
4.483466
false
false
false
false
Sharelink/Bahamut
Bahamut/BahamutUIKit/SimpleBrowser.swift
1
3914
// // Browser.swift // Bahamut // // Created by AlexChow on 15/10/30. // Copyright © 2015年 GStudio. All rights reserved. // import Foundation import UIKit class SimpleBrowser: UIViewController,UIWebViewDelegate { var webView: UIWebView!{ didSet{ webView.delegate = self if url != nil{ loadUrl() } } } var useCustomTitle = true var url:String!{ didSet{ if url != nil && webView != nil { loadUrl() } } } override func viewDidLoad() { super.viewDidLoad() webView = UIWebView(frame: self.view.bounds) self.view.addSubview(webView) self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.stop, target: self, action: #selector(SimpleBrowser.back(_:))) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.action, target: self, action: #selector(SimpleBrowser.action(_:))) let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(SimpleBrowser.swipeLeft(_:))) leftSwipe.direction = .left let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(SimpleBrowser.swipeRight(_:))) rightSwipe.direction = .right self.webView.addGestureRecognizer(leftSwipe) self.webView.addGestureRecognizer(rightSwipe) } @objc func swipeLeft(_:UISwipeGestureRecognizer) { self.webView.goForward() } @objc func swipeRight(_:UISwipeGestureRecognizer) { if webView.canGoBack { self.webView.goBack() }else{ self.navigationController?.dismiss(animated: true, completion: nil) } } @objc func back(_ sender: AnyObject) { self.navigationController?.dismiss(animated: true, completion: nil) } @objc func action(_ sender: AnyObject) { var items = [Any]() if let u = url,let ul = URL(string: u) { items.append(ul) } let ac = UIActivityViewController(activityItems:items, applicationActivities: nil) ac.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem ac.excludedActivityTypes = [.airDrop,.addToReadingList,.print,.assignToContact] if #available(iOS 9.0, *) { ac.excludedActivityTypes?.append(.openInIBooks) } self.present(ac, animated: true) } fileprivate func loadUrl() { webView.loadRequest(URLRequest(url: URL(string: url)!)) } func webViewDidFinishLoad(_ webView: UIWebView) { if useCustomTitle { if let title = webView.stringByEvaluatingJavaScript(from: "document.title"){ self.title = title } } } //"SimpleBrowser" @discardableResult static func openUrl(_ currentViewController:UIViewController,url:String,title:String?,callback:((_:SimpleBrowser)->Void)? = nil) -> SimpleBrowser { let controller = SimpleBrowser() let navController = UINavigationController(rootViewController: controller) controller.useCustomTitle = String.isNullOrWhiteSpace(title) DispatchQueue.main.async { () -> Void in if let cnvc = currentViewController as? UINavigationController{ navController.navigationBar.barStyle = cnvc.navigationBar.barStyle } controller.title = title currentViewController.present(navController, animated: true, completion: { controller.url = url; if let cb = callback{ cb(controller) } }) } return controller } }
mit
cd7cfdb6eb2ede92c3eb2559fc7aad22
31.322314
179
0.609818
5.292287
false
false
false
false
BranchMetrics/Segment-Branch-iOS
Examples/Fortune/Fortune/UIImage+AP.swift
1
3153
// // UIImage+AP.swift // Fortune // // Created by Edward on 2/12/18. // Copyright © 2018 Branch. All rights reserved. // import UIKit extension CGRect { func rectCenteredOver(rect: CGRect) -> CGRect { return CGRect( x: rect.origin.x + ((rect.size.width - self.size.width)/2.0), y: rect.origin.y + ((rect.size.height - self.size.height)/2.0), width: self.size.width, height: self.size.height ) } func rectAspectFitIn(rect: CGRect) -> CGRect { if rect.width <= 0 || rect.height <= 0 || self.width <= 0 || self.height <= 0 { return CGRect.zero.rectCenteredOver(rect: rect) } var r: CGRect = .zero if self.width < self.height { r = CGRect( x: 0.0, y: 0.0, width: rect.width * rect.height / self.height, height: rect.height ) } else { r = CGRect( x: 0.0, y: 0.0, width: rect.width, height: rect.height * rect.width / self.width ) } return r.rectCenteredOver(rect: rect) } } extension UIImage { class func imageWith(color: UIColor, size: CGSize) -> UIImage? { let rect = CGRect( origin: .zero, size: size ) var image: UIImage? = nil UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) if let context: CGContext = UIGraphicsGetCurrentContext() { context.setFillColor(color.cgColor); context.fill(rect); image = UIGraphicsGetImageFromCurrentImageContext(); } UIGraphicsEndImageContext(); return image; } func imageWithAspectFit(size: CGSize) -> UIImage? { if size.height <= 0.0 || size.width <= 0.0 { return nil } let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale); guard let context = UIGraphicsGetCurrentContext() else { return nil } // Orient the image correctly -- context.scaleBy(x: 1.0, y: -1.0) context.translateBy(x: 0.0, y: -rect.size.height) // Set the color -- context.setFillColor(UIColor.clear.cgColor) context.fill(rect) // d.w / d.h = s.w / s.h // d.h / d.w = s.h / s.w var destRect = CGRect.zero if size.width < size.height { destRect.size.width = size.width; destRect.size.height = self.size.height / self.size.width * destRect.size.width; } else { destRect.size.height = size.height; destRect.size.width = self.size.width / self.size.height * destRect.size.height; } destRect = destRect.rectCenteredOver(rect: rect) if let image = self.cgImage { context.draw(image, in: destRect) } let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } }
mit
149a44dd7174ebd039c86753d18541df
30.207921
93
0.545368
3.99493
false
false
false
false
MilitiaSoftworks/MSAlertController
MSAlertControllerExampleSwift/ViewController.swift
1
4296
// // ViewController.swift // MSAlertControllerExampleSwift // // Created by Jacob King on 13/01/2017. // Copyright © 2017 Militia Softworks Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import MSAlertController class ViewController: UIViewController { // DEMO of most basic alert view, using pre-built convenience method and no animation. @IBAction func demo1(_ sender: Any) { let alert = MSAlertController.basicOneButton(title: "Error", body: "The server cannot be reached, please try again later.", buttonTitle: "Okay") { (sender, alert) in print("Dismissing") // Executed when button is pressed. } alert.showAlert(withAnimation: .none) } // DEMO of text input alert view, with 2 buttons and a fade animation. Uses convenience builder. @IBAction func demo2(_ sender: Any) { let alert = MSAlertController.basicTextInput(title: "Reset my password", body: "Enter the mobile number or email address you used when creating your account. Then hit the send button and we will send you a text or email with instructions on how to reset your password.", textfieldPlaceholder: "Mobile or email", buttonOneTitle: "Send", buttonOneAction: { (sender, alert) in alert.dismissAlert(withAnimation: .fade) // Executed when button is pressed. }, buttonTwoTitle: "Cancel") { (sender, alert) in print("Dismissing") // Executed when button is pressed. } alert.showAlert(withAnimation: .fade) } // DEMO of totally custom built alert view with no convenience builder. @IBAction func demo3(_ sender: Any) { let alert = MSAlertController.empty() let title = MSAlertControllerTitleComponent.withTitleText("Licence Required") let body = MSAlertControllerBodyComponent.withBodyText("You must purchase a licence to continually use this software.") let box = MSAlertControllerCheckboxComponent.withText("Don't remind me", defaultStateIsTicked: false) { (button, ticket) in // Executed when checkbox is toggled. } let button1 = MSAlertControllerButtonComponent.submissiveButtonWithText("Continue with evaluation") { (sender) in alert.dismissAlert(withAnimation: .slideCentre) // Executed when button is pressed. } let button2 = MSAlertControllerButtonComponent.standardButtonWithText("Purchase a licence") { (sender) in alert.dismissAlert(withAnimation: .slideCentre) // Executed when button is pressed. } let button3 = MSAlertControllerButtonComponent.standardButtonWithText("Cancel") { (sender) in alert.dismissAlert(withAnimation: .slideCentre) // Executed when button is pressed. } // As this is custom, apply custom spacing to components. title.applyConstraintMap(MSAlertControllerConstraintMap(top: 16, bottom: 8, left: 16, right: 16)) body.applyConstraintMap(MSAlertControllerConstraintMap(top: 8, bottom: 8, left: 16, right: 16)) box.applyConstraintMap(MSAlertControllerConstraintMap(top: 8, bottom: 16, left: 16, right: 16, height: 20)) alert.components = [title, body, box, button1, button2, button3] alert.showAlert(withAnimation: .slideCentre) } }
apache-2.0
1e9ea734a55651a9a1dacb12a0354354
45.182796
343
0.629802
4.936782
false
false
false
false
joearms/joearms.github.io
includes/swift/experiment3.swift
1
1002
// experiment3.swift // run with: // $ swift experiment3.swift import Cocoa class AppDelegate: NSObject, NSApplicationDelegate { let window = NSWindow() func applicationDidFinishLaunching(aNotification: NSNotification) { window.setContentSize(NSSize(width:600, height:200)) window.styleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask window.opaque = false window.center(); window.title = "Experiment 3" let button = NSButton(frame: NSMakeRect(20, 100, 180, 30)) button.bezelStyle = .ThickSquareBezelStyle button.title = "Click Me" button.target = NSApp window.contentView!.addSubview(button) window.makeKeyAndOrderFront(window) window.level = 1 } } let app = NSApplication.sharedApplication() let controller = AppDelegate() app.delegate = controller app.run()
mit
8eb7cda21a293102d652883ed41724e6
26.081081
70
0.647705
4.84058
false
false
false
false
abstractmachine/Automatic.Writer
AutomaticWriter/Views/OutlineView/MyTextField.swift
1
1717
// // MyTextField.swift // AutomaticWriter // // Created by Raphael on 21.01.15. // Copyright (c) 2015 HEAD Geneva. All rights reserved. // import Cocoa class MyTextField: NSTextField { override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) // Drawing code here. } override func becomeFirstResponder() -> Bool { // look for NSSplitView var splitview = superview while splitview?.className != "NSSplitView" { splitview = splitview?.superview } // look for MyTextView if var clipView = splitview?.subviews[1] as NSView? { while clipView.className != "NSClipView" { if clipView.subviews.count > 0 { if let subview = clipView.subviews[0] as NSView? { clipView = subview } else { break } } else { break } } //println("became first responder. looking for clipView: \(clipView)") // when trying, stops at the NSClipView just before the TextView if let actualClipView = clipView as? NSClipView { if let textView = actualClipView.documentView as? MyTextView { Swift.print("became first responder. looking for textView: \(textView)") // we found it!! nextResponder = textView // textView.nextResponder = self // make the app crash } } } //println("became first responder. looking for textview: \(textView)") return true } }
mit
81fd083456bc5f150061dd27afd55d98
31.396226
147
0.528247
5.110119
false
false
false
false
PedroTrujilloV/TIY-Assignments
11--Raiders-of-the-Lost-App/TheGrailDiary/TheGrailDiary/FamousHistoricalSitesTableViewController.swift
1
5241
// // FamousHistoricalSitesTableViewController.swift // TheGrailDiary // // Created by Pedro Trujillo on 10/19/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit class FamousHistoricalSitesTableViewController: UITableViewController { var filePath = "sites" var formatFile = "json" var sitesArray = Array<SiteModel>() var siteData: NSArray! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() title = "World Wonders 🗿" loadSites() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return siteData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SiteTableViewCell", forIndexPath: indexPath) as! SiteTableViewCell // Configure the cell... let aSite = sitesArray[indexPath.row] cell.setLabelsValues(aSite) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let selectedSite = sitesArray[indexPath.row] let detailSiteVC = storyboard?.instantiateViewControllerWithIdentifier("SiteDescriptionViewController") as! SiteDescriptionViewController detailSiteVC.site = selectedSite navigationController?.pushViewController(detailSiteVC, animated: true) } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ //MARK: Load Json File: func loadSites() { do { let siteFilePath = NSBundle.mainBundle().pathForResource(filePath, ofType: formatFile) let siteDataFromFile = NSData(contentsOfFile: siteFilePath!) siteData = try NSJSONSerialization.JSONObjectWithData(siteDataFromFile!, options:[]) as! NSArray for site in siteData { let newSite = SiteModel(siteDictionary: site as! NSDictionary) sitesArray.append(newSite) } sitesArray.sortInPlace({$0.name > $1.name}) } catch let error as NSError { print("Error loading file \(filePath).\(formatFile) error information: \(error)") } } }
cc0-1.0
5fc0a4754b0ba194e5dcf87443317b2a
32.14557
157
0.667749
5.51844
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/gas-station.swift
2
1018
/** * https://leetcode.com/problems/gas-station/ * * */ // Date: Wed Sep 23 15:37:58 PDT 2020 /// The idea is /// 1. If the total gas - cost is greater or equal to 0, there will be a solution for sure. /// 2. Then, to find the start station, /// 2.1 Start from station 0, sum all the gas - cost would be available in tank. /// 2.2 If at station `index`, the gas in tank is smaller than 0, then next station is not reachable. /// 2.3 Thus, from start to `index` is not a reachable path. /// 2.4 So, we start with next index, which is `index + 1`. class Solution { func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int { var tank = 0 var total = 0 var start = 0 for index in stride(from: 0, to: cost.count, by: 1) { tank += gas[index] - cost[index] if tank < 0 { total += tank tank = 0 start = index + 1 } } return (total + tank) < 0 ? -1 : start } }
mit
6a42eff4bcc140fb128e358b6d272b96
34.103448
105
0.543222
3.474403
false
false
false
false
Virpik/T
src/Foundation/[String].swift
1
2693
// // TString.swift // TDemo // // Created by Virpik on 08/08/2017. // Copyright © 2017 Virpik. All rights reserved. // import Foundation public extension String { public var int: Int { return Int(self) ?? 0 } public var uInt32: UInt32 { if let int = UInt32(self) { return int } return 0 } public var float: Float { if let int = Float(self) { return int } return 0 } public var double: Double { if let int = Double(self) { return int } return 0 } public var int16: Int16 { if let int = Int16(self) { return int } return 0 } } public extension StringProtocol where Index == String.Index { /// range to NSRange public func nsRange(from range: Range<Index>) -> NSRange { return NSRange(range, in: self) } } public extension String { subscript (i: Int) -> Character { return self[index(startIndex, offsetBy: i)] } subscript (i: Int) -> String { return String(self[i] as Character) } /// Подстрока по диапазону subscript (r: Range<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(startIndex, offsetBy: r.upperBound) return String(self[start ..< end]) } /// Большая первая буква public var capitalizingFirstLetter: String { let first = self.prefix(1).capitalized let other = self.dropFirst() return first + other } } /// Набор методов по работе с путями из NSString (Это было удобно) public extension String { public var lastPathComponent: String { return (self as NSString).lastPathComponent } public var deletingLastPathComponent: String { return (self as NSString).deletingLastPathComponent } public var deletingPathExtension: String { return (self as NSString).deletingPathExtension } public var pathExtension: String { return (self as NSString).pathExtension } public var abbreviatingWithTildeInPath: String { return (self as NSString).abbreviatingWithTildeInPath } public func appendingPathComponent(_ str: String) -> String { return (self as NSString).appendingPathComponent(str) } public func appendingPathExtension(_ str: String) -> String { return (self as NSString).appendingPathExtension(str) ?? self+"."+str } }
mit
ff22a1f089e075dbf3b6911cd2dc6000
22.115044
77
0.585375
4.519031
false
false
false
false
bsmith11/ScoreReporter
ScoreReporter/Team Details/TeamDetailsHeaderView.swift
1
3506
// // TeamDetailsHeaderView.swift // ScoreReporter // // Created by Brad Smith on 1/17/17. // Copyright © 2017 Brad Smith. All rights reserved. // import UIKit import ScoreReporterCore import Anchorage class TeamDetailsHeaderView: UIView, Sizable { fileprivate let backgroundImageView = UIImageView(frame: .zero) fileprivate let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) fileprivate let separatorView = TableViewCellSeparatorView(frame: .zero) fileprivate let infoView = TeamDetailsInfoView(frame: .zero) fileprivate var backgroundImageViewTop: NSLayoutConstraint? var backgroundAnimator: UIViewPropertyAnimator? var fractionComplete: CGFloat = 1.0 { didSet { let scaledValue = Double(fractionComplete).scaled(from: 0.0 ... 1.0, to: 0.5 ... 1.0, clamp: true) backgroundAnimator?.fractionComplete = CGFloat(scaledValue) } } var verticalOffset: CGFloat { get { return backgroundImageViewTop?.constant ?? 0.0 } set { let offset = min(0.0, newValue) let currentOffset = backgroundImageViewTop?.constant ?? 0.0 if !offset.isEqual(to: currentOffset) { backgroundImageViewTop?.constant = offset } } } weak var delegate: EventDetailsHeaderViewDelegate? override init(frame: CGRect) { super.init(frame: frame) clipsToBounds = false configureViews() configureLayout() resetBlurAnimation() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Public extension TeamDetailsHeaderView { func configure(with viewModel: TeamViewModel) { backgroundImageView.pin_setImage(from: viewModel.logoURL) infoView.configure(with: viewModel) } func resetBlurAnimation() { backgroundAnimator?.stopAnimation(true) visualEffectView.effect = UIBlurEffect(style: .light) backgroundAnimator = UIViewPropertyAnimator(duration: 0.5, curve: .linear, animations: { [weak self] in self?.visualEffectView.effect = nil }) backgroundAnimator?.startAnimation() backgroundAnimator?.pauseAnimation() fractionComplete = 0.0 } } // MARK: - Private private extension TeamDetailsHeaderView { func configureViews() { backgroundImageView.contentMode = .scaleAspectFill backgroundImageView.clipsToBounds = true addSubview(backgroundImageView) addSubview(visualEffectView) addSubview(separatorView) addSubview(infoView) } func configureLayout() { backgroundImageViewTop = backgroundImageView.topAnchor == topAnchor backgroundImageView.horizontalAnchors == horizontalAnchors backgroundImageView.bottomAnchor == infoView.centerYAnchor visualEffectView.edgeAnchors == backgroundImageView.edgeAnchors separatorView.horizontalAnchors == backgroundImageView.horizontalAnchors separatorView.bottomAnchor == backgroundImageView.bottomAnchor infoView.topAnchor == topAnchor + 96.0 infoView.horizontalAnchors == horizontalAnchors + 16.0 infoView.bottomAnchor == bottomAnchor - 16.0 } }
mit
20aed906716cb2d4554ea602e61f691d
29.215517
111
0.648787
5.616987
false
true
false
false
Mioke/PlanB
PlanB/PlanB/Base/Kits/SystemLog/SystemLog.swift
1
1424
// // SystemLog.swift // swiftArchitecture // // Created by jiangkelan on 3/7/16. // Copyright © 2016 KleinMioke. All rights reserved. // import UIKit class SystemLog: NSObject { static let instance = SystemLog() private let writter = SystemLogFileWritter() private var enabled: Bool = true class func setEnable(enable: Bool) -> Void { instance.enabled = enable if enable { NSSetUncaughtExceptionHandler({ (exception: NSException) -> Void in SystemLog.write("\(exception)") }) } } class func write(obj: AnyObject?) -> Void { if instance.enabled { if obj is String { instance.writter.writeText(obj as! String) } else { let text = "\(obj)" instance.writter.writeText(text) } } } class func allLogFiles() -> [String]? { return instance.writter.allLogFiles() } class func contentsOfFile(fileName: String) -> String? { return instance.writter.textOfFile(fileName) } class func activeDevelopUI() { let nav = UINavigationController(rootViewController: SystemLogFilesBrowser()) UIApplication.sharedApplication().windows.first?.rootViewController?.presentViewController(nav, animated: true, completion: nil) } }
gpl-3.0
769ee8b7358a9cca72e0232873efcdf3
24.872727
136
0.585383
4.759197
false
false
false
false
codingforentrepreneurs/30-Days-of-Swift
Simple_Final/Simple/LocationCollectionViewCell.swift
1
983
// // LocationCollectionViewCell.swift // Simple // // Created by Justin Mitchel on 12/18/14. // Copyright (c) 2014 Coding for Entrepreneurs. All rights reserved. // import UIKit class LocationCollectionViewCell: UICollectionViewCell { var textView:UITextView! required init(coder aDecoder:NSCoder) { super.init(coder: aDecoder) } override init(frame:CGRect) { super.init(frame:frame) let tvFrame = CGRectMake(10, 0, frame.size.width - 20, frame.size.height) textView = UITextView(frame: tvFrame) textView.font = UIFont.systemFontOfSize(20.0) textView.backgroundColor = UIColor(white: 1.0, alpha: 0.3) textView.textAlignment = .Left textView.scrollEnabled = false textView.userInteractionEnabled = true textView.editable = false textView.dataDetectorTypes = UIDataDetectorTypes.All contentView.addSubview(textView) } }
apache-2.0
21d79a619260b6560ef40edcab99db4e
27.085714
81
0.657172
4.447964
false
false
false
false
kbelter/SnazzyList
Example/Pods/KMPlaceholderTextView/KMPlaceholderTextView/KMPlaceholderTextView.swift
1
5712
// // KMPlaceholderTextView.swift // // Copyright (c) 2016 Zhouqi Mo (https://github.com/MoZhouqi) // // 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 @IBDesignable open class KMPlaceholderTextView: UITextView { private struct Constants { static let defaultiOSPlaceholderColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22) } public let placeholderLabel: UILabel = UILabel() private var placeholderLabelConstraints = [NSLayoutConstraint]() @IBInspectable open var placeholder: String = "" { didSet { placeholderLabel.text = placeholder } } @IBInspectable open var placeholderColor: UIColor = KMPlaceholderTextView.Constants.defaultiOSPlaceholderColor { didSet { placeholderLabel.textColor = placeholderColor } } override open var font: UIFont! { didSet { if placeholderFont == nil { placeholderLabel.font = font } } } open var placeholderFont: UIFont? { didSet { let font = (placeholderFont != nil) ? placeholderFont : self.font placeholderLabel.font = font } } override open var textAlignment: NSTextAlignment { didSet { placeholderLabel.textAlignment = textAlignment } } override open var text: String! { didSet { textDidChange() } } override open var attributedText: NSAttributedString! { didSet { textDidChange() } } override open var textContainerInset: UIEdgeInsets { didSet { updateConstraintsForPlaceholderLabel() } } override public init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { #if swift(>=4.2) let notificationName = UITextView.textDidChangeNotification #else let notificationName = NSNotification.Name.UITextView.textDidChangeNotification #endif NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: notificationName, object: nil) placeholderLabel.font = font placeholderLabel.textColor = placeholderColor placeholderLabel.textAlignment = textAlignment placeholderLabel.text = placeholder placeholderLabel.numberOfLines = 0 placeholderLabel.backgroundColor = UIColor.clear placeholderLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(placeholderLabel) updateConstraintsForPlaceholderLabel() } private func updateConstraintsForPlaceholderLabel() { var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]", options: [], metrics: nil, views: ["placeholder": placeholderLabel]) newConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(\(textContainerInset.top))-[placeholder]", options: [], metrics: nil, views: ["placeholder": placeholderLabel]) newConstraints.append(NSLayoutConstraint( item: placeholderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0) )) removeConstraints(placeholderLabelConstraints) addConstraints(newConstraints) placeholderLabelConstraints = newConstraints } @objc private func textDidChange() { placeholderLabel.isHidden = !text.isEmpty } open override func layoutSubviews() { super.layoutSubviews() placeholderLabel.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2.0 } deinit { #if swift(>=4.2) let notificationName = UITextView.textDidChangeNotification #else let notificationName = NSNotification.Name.UITextView.textDidChangeNotification #endif NotificationCenter.default.removeObserver(self, name: notificationName, object: nil) } }
apache-2.0
90f314227a72a2b5bcf12ddbfb7ab24a
33.618182
163
0.653711
5.649852
false
false
false
false
TwoRingSoft/SemVer
Vrsnr/File Types/PodspecFile.swift
1
2455
// // PodspecFile.swift // Vrsnr // // Created by Andrew McKnight on 7/10/16. // Copyright © 2016 Two Ring Software. All rights reserved. // import Foundation public struct PodspecFile { public let path: String } extension PodspecFile: File { public func getPath() -> String { return path } public static func defaultKeyForVersionType(_ type: VersionType) -> String { switch(type) { case .Numeric: return "version" case .Semantic: return "version" } } public func defaultKeyForVersionType(_ type: VersionType) -> String { return PodspecFile.defaultKeyForVersionType(type) } public func versionStringForKey(_ key: String?, versionType: VersionType) throws -> String? { let workingKey = chooseWorkingKey(key, versionType: versionType) return try extractVersionStringFromTextFile(self, versionType: versionType, key: workingKey) } public func replaceVersionString<V>(_ original: V, new: V, key: String?) throws where V: Version { let workingKey = chooseWorkingKey(key, versionType: new.type) try replaceVersionStringInTextFile(self, originalVersion: original, newVersion: new, versionOverride: key == nil, key: workingKey) } } extension PodspecFile: TextFile { public static func versionStringFromLine(_ line: String) throws -> String { let assignentExpressionComponents = line.components(separatedBy: "=") if assignentExpressionComponents.count != 2 { throw NSError(domain: errorDomain, code: Int(ErrorCode.couldNotParseVersion.rawValue), userInfo: [ NSLocalizedDescriptionKey: "Could not find an assignment using ‘=’: \(line)" ]) } return assignentExpressionComponents.last! // take right-hand side from assignment expression .components(separatedBy: "#").first! // strip away any comments .replacingOccurrences(of: "\"", with: "") // remove any surrounding double-quotes .replacingOccurrences(of: "\'", with: "") // remove surrounding single-quotes .trimmingCharacters(in: CharacterSet.whitespaces) // trim whitespace } } extension PodspecFile { fileprivate func chooseWorkingKey(_ key: String?, versionType: VersionType) -> String { if key == nil { return defaultKeyForVersionType(versionType) } else { return key! } } }
apache-2.0
3ab5314626a44a33cfff78bde1aae7f7
32.561644
190
0.666122
4.520295
false
false
false
false
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallTrianglePath.swift
8
5261
// // NVActivityIndicatorAnimationBallTrianglePath.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationBallTrianglePath: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize = size.width / 5 let deltaX = size.width / 2 - circleSize / 2 let deltaY = size.height / 2 - circleSize / 2 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let duration: CFTimeInterval = 2 let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) // Animation let animation = CAKeyframeAnimation(keyPath: "transform") animation.keyTimes = [0, 0.33, 0.66, 1] animation.timingFunctions = [timingFunction, timingFunction, timingFunction] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Top-center circle let topCenterCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) changeAnimation(animation, values: ["{0,0}", "{hx,fy}", "{-hx,fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY) topCenterCircle.frame = CGRect(x: x + size.width / 2 - circleSize / 2, y: y, width: circleSize, height: circleSize) topCenterCircle.add(animation, forKey: "animation") layer.addSublayer(topCenterCircle) // Bottom-left circle let bottomLeftCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) changeAnimation(animation, values: ["{0,0}", "{hx,-fy}", "{fx,0}", "{0,0}"], deltaX: deltaX, deltaY: deltaY) bottomLeftCircle.frame = CGRect(x: x, y: y + size.height - circleSize, width: circleSize, height: circleSize) bottomLeftCircle.add(animation, forKey: "animation") layer.addSublayer(bottomLeftCircle) // Bottom-right circle let bottomRightCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) changeAnimation(animation, values: ["{0,0}", "{-fx,0}", "{-hx,-fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY) bottomRightCircle.frame = CGRect(x: x + size.width - circleSize, y: y + size.height - circleSize, width: circleSize, height: circleSize) bottomRightCircle.add(animation, forKey: "animation") layer.addSublayer(bottomRightCircle) } func changeAnimation(_ animation: CAKeyframeAnimation, values rawValues: [String], deltaX: CGFloat, deltaY: CGFloat) { let values = NSMutableArray(capacity: 5) for rawValue in rawValues { let point = CGPointFromString(translateString(rawValue, deltaX: deltaX, deltaY: deltaY)) values.add(NSValue(caTransform3D: CATransform3DMakeTranslation(point.x, point.y, 0))) } animation.values = values as [AnyObject] } func translateString(_ valueString: String, deltaX: CGFloat, deltaY: CGFloat) -> String { let valueMutableString = NSMutableString(string: valueString) let fullDeltaX = 2 * deltaX let fullDeltaY = 2 * deltaY var range = NSMakeRange(0, valueMutableString.length) valueMutableString.replaceOccurrences(of: "hx", with: "\(deltaX)", options: NSString.CompareOptions.caseInsensitive, range: range) range.length = valueMutableString.length valueMutableString.replaceOccurrences(of: "fx", with: "\(fullDeltaX)", options: NSString.CompareOptions.caseInsensitive, range: range) range.length = valueMutableString.length valueMutableString.replaceOccurrences(of: "hy", with: "\(deltaY)", options: NSString.CompareOptions.caseInsensitive, range: range) range.length = valueMutableString.length valueMutableString.replaceOccurrences(of: "fy", with: "\(fullDeltaY)", options: NSString.CompareOptions.caseInsensitive, range: range) return valueMutableString as String } }
apache-2.0
5edcdea7c1636314af1db46bd1a0d799
50.578431
144
0.70709
4.610868
false
false
false
false
andreaperizzato/CoreStore
CoreStoreDemo/CoreStoreDemo/MIgrations Demo/OrganismV1.swift
3
529
// // OrganismV1.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/06/21. // Copyright (c) 2015 John Rommel Estropia. All rights reserved. // import Foundation import CoreData class OrganismV1: NSManagedObject, OrganismProtocol { @NSManaged var dna: Int64 @NSManaged var hasHead: Bool @NSManaged var hasTail: Bool // MARK: OrganismProtocol func mutate() { self.hasHead = arc4random_uniform(2) == 1 self.hasTail = arc4random_uniform(2) == 1 } }
mit
512719d60e3cb71115eef7dae99c0e37
20.16
65
0.654064
3.673611
false
false
false
false
Thongpak21/NongBeer-MVVM-iOS-Demo
NongBeer/Classes/History/ViewController/HistoryViewController.swift
1
3461
// // SecondViewController.swift // NongBeer // // Created by Thongpak on 4/5/2560 BE. // Copyright © 2560 Thongpak. All rights reserved. // import UIKit import IGListKit class HistoryViewController: BaseViewController { lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0) }() lazy var viewModel: HistoryViewModelProtocol = HistoryViewModel(delegate: self) let collectionView: IGListCollectionView = { let layout = UICollectionViewFlowLayout() layout.estimatedItemSize = CGSize(width: 100, height: 60) let collectionView = IGListCollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.clear return collectionView }() override func viewDidLoad() { super.viewDidLoad() setCollectionView() self.viewModel.getListHistoryService() } override func onDataDidLoad() { if self.viewModel.isPullToRefresh == true { self.viewModel.isPullToRefresh = false if #available(iOS 10.0, *) { self.adapter.collectionView?.refreshControl?.endRefreshing() } } adapter.performUpdates(animated: true, completion: nil) } func setCollectionView() { collectionView.frame = view.bounds view.addSubview(collectionView) adapter.collectionView = collectionView if #available(iOS 10.0, *) { adapter.collectionView?.refreshControl = UIRefreshControl() adapter.collectionView?.refreshControl?.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged) } adapter.dataSource = self adapter.scrollViewDelegate = self } func pullToRefresh() { self.viewModel = HistoryViewModel(delegate: self) self.viewModel.isPullToRefresh = true self.viewModel.getListHistoryService() } } extension HistoryViewController: IGListAdapterDataSource { func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { return self.viewModel.history } func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { switch object { case is String: return LoadingSectionController() case is HistoryModel: return HistorySectionController() default: return IGListSectionController() } } func emptyView(for listAdapter: IGListAdapter) -> UIView? { let nibView = Bundle.main.loadNibNamed("EmptyView", owner: nil, options: nil)!.first as! EmptyView return nibView } } extension HistoryViewController: UIScrollViewDelegate { func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let distance = scrollView.contentSize.height - (targetContentOffset.pointee.y + scrollView.bounds.height) let nextOrderAvailable = (self.viewModel.history as? [HistoryModel])?.last?.nextOrderAvailable if nextOrderAvailable == true && distance < 200 { self.viewModel.history.append(LoadingType.loadmore.rawValue as IGListDiffable) self.viewModel.getListHistoryService() adapter.performUpdates(animated: true, completion: nil) } } }
apache-2.0
8e6f5efc5604f6393e20345ea5d35a96
36.204301
148
0.679769
5.397816
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/WikidataDescriptionEditingController.swift
1
4345
public struct WikidataAPIResult: Decodable { public struct APIError: Error, Decodable { public let code, info: String? } let error: APIError? let success: Int? } struct MediaWikiSiteInfoResult: Decodable { struct MediaWikiQueryResult: Decodable { struct MediaWikiGeneralResult: Decodable { let lang: String } let general: MediaWikiGeneralResult } let query: MediaWikiQueryResult } extension WikidataAPIResult { var succeeded: Bool { return success == 1 } } enum WikidataPublishingError: LocalizedError { case invalidArticleURL case apiResultNotParsedCorrectly case notEditable case unknown } @objc public final class WikidataDescriptionEditingController: Fetcher { static let DidMakeAuthorizedWikidataDescriptionEditNotification = NSNotification.Name(rawValue: "WMFDidMakeAuthorizedWikidataDescriptionEdit") /// Publish new wikidata description. /// /// - Parameters: /// - newWikidataDescription: new wikidata description to be published, e.g., "Capital of England and the United Kingdom". /// - source: description source; none, central or local. /// - wikidataID: id for the Wikidata entity including the prefix /// - language: language code of the page's wiki, e.g., "en". /// - completion: completion block called when operation is completed. public func publish(newWikidataDescription: String, from source: ArticleDescriptionSource, forWikidataID wikidataID: String, language: String, completion: @escaping (Error?) -> Void) { guard source != .local else { completion(WikidataPublishingError.notEditable) return } let requestWithCSRFCompletion: (WikidataAPIResult?, URLResponse?, Bool?, Error?) -> Void = { result, response, authorized, error in if let error = error { completion(error) } guard let result = result else { completion(WikidataPublishingError.apiResultNotParsedCorrectly) return } completion(result.error) if let authorized = authorized, authorized, result.error == nil { DispatchQueue.main.async { NotificationCenter.default.post(name: WikidataDescriptionEditingController.DidMakeAuthorizedWikidataDescriptionEditNotification, object: nil) } } } let languageCodeParameters = [ "action": "query", "meta": "siteinfo", "format": "json", "formatversion": "2"] let languageCodeComponents = configuration.mediaWikiAPIURLForWikiLanguage(language, with: languageCodeParameters) session.jsonDecodableTask(with: languageCodeComponents.url) { (siteInfo: MediaWikiSiteInfoResult?, response, error) in let normalizedLanguage = siteInfo?.query.general.lang ?? "en" let queryParameters = ["action": "wbsetdescription", "format": "json", "formatversion": "2"] let components = self.configuration.wikidataAPIURLComponents(with: queryParameters) self.requestMediaWikiAPIAuthToken(for: components.url, type: .csrf) { (result) in switch result { case .failure(let error): completion(error) case .success(let token): let bodyParameters = ["language": normalizedLanguage, "uselang": normalizedLanguage, "id": wikidataID, "value": newWikidataDescription, "token": token.value] self.session.jsonDecodableTask(with: components.url, method: .post, bodyParameters: bodyParameters, bodyEncoding: .form) { (result: WikidataAPIResult?, response, error) in requestWithCSRFCompletion(result, response, token.isAuthorized, error) } } } } } } public extension MWKArticle { @objc var isWikidataDescriptionEditable: Bool { return wikidataId != nil && descriptionSource != .local } }
mit
5286a3f7ce414491b3441a59dd000479
42.019802
191
0.613349
5.117786
false
false
false
false
sonnygauran/trailer
Shared/DataManager.swift
1
18526
import CoreData #if os(iOS) import UIKit #endif final class DataManager : NSObject { static var postMigrationRepoPrPolicy: RepoDisplayPolicy? static var postMigrationRepoIssuePolicy: RepoDisplayPolicy? class func checkMigration() { if Settings.lastRunVersion != versionString() { DLog("VERSION UPDATE MAINTENANCE NEEDED") #if os(iOS) migrateDatabaseToShared() #endif DataManager.performVersionChangedTasks() Settings.lastRunVersion = versionString() } ApiServer.ensureAtLeastGithubInMoc(mainObjectContext) } private class func performVersionChangedTasks() { let d = NSUserDefaults.standardUserDefaults() if let legacyAuthToken = d.objectForKey("GITHUB_AUTH_TOKEN") as? String { var legacyApiHost = d.objectForKey("API_BACKEND_SERVER") as? String ?? "" if legacyApiHost.isEmpty { legacyApiHost = "api.github.com" } let legacyApiPath = d.objectForKey("API_SERVER_PATH") as? String ?? "" var legacyWebHost = d.objectForKey("API_FRONTEND_SERVER") as? String ?? "" if legacyWebHost.isEmpty { legacyWebHost = "github.com" } let actualApiPath = (legacyApiHost + "/" + legacyApiPath).stringByReplacingOccurrencesOfString("//", withString:"/") let newApiServer = ApiServer.addDefaultGithubInMoc(mainObjectContext) newApiServer.apiPath = "https://" + actualApiPath newApiServer.webPath = "https://" + legacyWebHost newApiServer.authToken = legacyAuthToken newApiServer.lastSyncSucceeded = true d.removeObjectForKey("API_BACKEND_SERVER") d.removeObjectForKey("API_SERVER_PATH") d.removeObjectForKey("API_FRONTEND_SERVER") d.removeObjectForKey("GITHUB_AUTH_TOKEN") d.synchronize() } else { ApiServer.ensureAtLeastGithubInMoc(mainObjectContext) } DLog("Marking all repos as dirty") ApiServer.resetSyncOfEverything() DLog("Migrating display policies") for r in DataItem.allItemsOfType("Repo", inMoc:mainObjectContext) as! [Repo] { if let markedAsHidden = r.hidden?.boolValue where markedAsHidden == true { r.displayPolicyForPrs = RepoDisplayPolicy.Hide.rawValue r.displayPolicyForIssues = RepoDisplayPolicy.Hide.rawValue } else { if let prDisplayPolicy = postMigrationRepoPrPolicy where r.displayPolicyForPrs == nil { r.displayPolicyForPrs = prDisplayPolicy.rawValue } if let issueDisplayPolicy = postMigrationRepoIssuePolicy where r.displayPolicyForIssues == nil { r.displayPolicyForIssues = issueDisplayPolicy.rawValue } } if r.hidden != nil { r.hidden = nil } } } private class func migrateDatabaseToShared() { do { let oldDocumentsDirectory = legacyFilesDirectory().path! let newDocumentsDirectory = sharedFilesDirectory().path! let fm = NSFileManager.defaultManager() let files = try fm.contentsOfDirectoryAtPath(oldDocumentsDirectory) DLog("Migrating DB files into group container from %@ to %@", oldDocumentsDirectory, newDocumentsDirectory) for file in files { if file.rangeOfString("Trailer.sqlite") != nil { DLog("Moving database file: %@",file) let oldPath = oldDocumentsDirectory.stringByAppendingPathComponent(file) let newPath = newDocumentsDirectory.stringByAppendingPathComponent(file) if fm.fileExistsAtPath(newPath) { try! fm.removeItemAtPath(newPath) } try! fm.moveItemAtPath(oldPath, toPath: newPath) } } try! fm.removeItemAtPath(oldDocumentsDirectory) } catch { /* No legacy directory */ } } class func sendNotificationsAndIndex() { let newPrs = PullRequest.newItemsOfType("PullRequest", inMoc: mainObjectContext) as! [PullRequest] for p in newPrs { if !p.createdByMe() && !(p.isNewAssignment?.boolValue ?? false) && p.isVisibleOnMenu() { app.postNotificationOfType(PRNotificationType.NewPr, forItem: p) } } let updatedPrs = PullRequest.updatedItemsOfType("PullRequest", inMoc: mainObjectContext) as! [PullRequest] for p in updatedPrs { if let reopened = p.reopened?.boolValue where reopened == true { if !p.createdByMe() && p.isVisibleOnMenu() { app.postNotificationOfType(PRNotificationType.PrReopened, forItem: p) } p.reopened = false } } let newIssues = Issue.newItemsOfType("Issue", inMoc: mainObjectContext) as! [Issue] for i in newIssues { if !i.createdByMe() && !(i.isNewAssignment?.boolValue ?? false) && i.isVisibleOnMenu() { app.postNotificationOfType(PRNotificationType.NewIssue, forItem: i) } } let updatedIssues = Issue.updatedItemsOfType("Issue", inMoc: mainObjectContext) as! [Issue] for i in updatedIssues { if let reopened = i.reopened?.boolValue where reopened == true { if !i.createdByMe() && i.isVisibleOnMenu() { app.postNotificationOfType(PRNotificationType.IssueReopened, forItem: i) } i.reopened = false } } let allTouchedPrs = newPrs + updatedPrs for p in allTouchedPrs { if let newAssignment = p.isNewAssignment?.boolValue where newAssignment == true { app.postNotificationOfType(PRNotificationType.NewPrAssigned, forItem: p) p.isNewAssignment = false } } let allTouchedIssues = newIssues + updatedIssues for i in allTouchedIssues { if let newAssignment = i.isNewAssignment?.boolValue where newAssignment == true { app.postNotificationOfType(PRNotificationType.NewIssueAssigned, forItem: i) i.isNewAssignment = false } } let latestComments = PRComment.newItemsOfType("PRComment", inMoc: mainObjectContext) as! [PRComment] for c in latestComments { if let i = c.pullRequest ?? c.issue { processNotificationsForComment(c, ofItem: c.pullRequest ?? i) } c.postSyncAction = PostSyncAction.DoNothing.rawValue } let latestStatuses = PRStatus.newItemsOfType("PRStatus", inMoc: mainObjectContext) as! [PRStatus] if Settings.notifyOnStatusUpdates { var coveredPrs = Set<NSManagedObjectID>() for s in latestStatuses { let pr = s.pullRequest if pr.isVisibleOnMenu() && (Settings.notifyOnStatusUpdatesForAllPrs || pr.createdByMe() || pr.assignedToParticipated() || pr.assignedToMySection()) { if !coveredPrs.contains(pr.objectID) { coveredPrs.insert(pr.objectID) if let s = pr.displayedStatuses().first { let displayText = s.descriptionText if pr.lastStatusNotified != displayText && pr.postSyncAction?.integerValue != PostSyncAction.NoteNew.rawValue { app.postNotificationOfType(PRNotificationType.NewStatus, forItem: s) pr.lastStatusNotified = displayText } } else { pr.lastStatusNotified = nil } } } } } for s in latestStatuses { s.postSyncAction = PostSyncAction.DoNothing.rawValue } for p in allTouchedPrs { p.postSyncAction = PostSyncAction.DoNothing.rawValue #if os(iOS) p.indexForSpotlight() #endif } for i in allTouchedIssues { i.postSyncAction = PostSyncAction.DoNothing.rawValue #if os(iOS) i.indexForSpotlight() #endif } } class func processNotificationsForComment(c: PRComment, ofItem: ListableItem) { if ofItem.postSyncAction?.integerValue == PostSyncAction.NoteUpdated.rawValue && ofItem.isVisibleOnMenu() { if c.refersToMe() { app.postNotificationOfType(PRNotificationType.NewMention, forItem: c) } else if !Settings.disableAllCommentNotifications && ofItem.showNewComments() && !c.isMine() { notifyNewComment(c) } } } class func notifyNewComment(c: PRComment) { if let authorName = c.userName { var blocked = false for blockedAuthor in Settings.commentAuthorBlacklist as [String] { if authorName.compare(blockedAuthor, options: [NSStringCompareOptions.CaseInsensitiveSearch, NSStringCompareOptions.DiacriticInsensitiveSearch])==NSComparisonResult.OrderedSame { blocked = true break } } if blocked { DLog("Blocked notification for user '%@' as their name is on the blacklist",authorName) } else { DLog("User '%@' not on blacklist, can post notification",authorName) app.postNotificationOfType(PRNotificationType.NewComment, forItem:c) } } } class func saveDB() -> Bool { if mainObjectContext.hasChanges { DLog("Saving DB") do { try mainObjectContext.save() } catch { DLog("Error while saving DB: %@", (error as NSError).localizedDescription) } } return true } class func tempContext() -> NSManagedObjectContext { let c = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) c.parentContext = mainObjectContext c.undoManager = nil return c } class func infoForType(type: PRNotificationType, item: DataItem) -> [String : AnyObject] { switch type { case .NewMention: fallthrough case .NewComment: return [COMMENT_ID_KEY : item.objectID.URIRepresentation().absoluteString] case .NewPr: fallthrough case .PrReopened: fallthrough case .NewPrAssigned: fallthrough case .PrClosed: fallthrough case .PrMerged: return [NOTIFICATION_URL_KEY : (item as! PullRequest).webUrl!, PULL_REQUEST_ID_KEY: item.objectID.URIRepresentation().absoluteString] case .NewRepoSubscribed: fallthrough case .NewRepoAnnouncement: return [NOTIFICATION_URL_KEY : (item as! Repo).webUrl!] case .NewStatus: let pr = (item as! PRStatus).pullRequest return [NOTIFICATION_URL_KEY : pr.webUrl!, STATUS_ID_KEY: pr.objectID.URIRepresentation().absoluteString] case .NewIssue: fallthrough case .IssueReopened: fallthrough case .NewIssueAssigned: fallthrough case .IssueClosed: return [NOTIFICATION_URL_KEY : (item as! Issue).webUrl!, ISSUE_ID_KEY: item.objectID.URIRepresentation().absoluteString] } } class func postMigrationTasks() { if _justMigrated { ApiServer.resetSyncOfEverything() _justMigrated = false } } class func postProcessAllItems() { for p in DataItem.allItemsOfType("PullRequest", inMoc: mainObjectContext) as! [PullRequest] { p.postProcess() } for i in DataItem.allItemsOfType("Issue", inMoc: mainObjectContext) as! [Issue] { i.postProcess() } } class func reasonForEmptyWithFilter(filterValue: String?) -> NSAttributedString { let openRequests = PullRequest.countOpenRequestsInMoc(mainObjectContext) var color = COLOR_CLASS.lightGrayColor() var message: String = "" if !ApiServer.someServersHaveAuthTokensInMoc(mainObjectContext) { color = MAKECOLOR(0.8, 0.0, 0.0, 1.0) message = "There are no configured API servers in your settings, please ensure you have added at least one server with a valid API token." } else if app.isRefreshing { message = "Refreshing PR information, please wait a moment..." } else if !(filterValue ?? "").isEmpty { message = "There are no PRs matching this filter." } else if openRequests > 0 { message = "\(openRequests) PRs are hidden by your settings." } else if Repo.countVisibleReposInMoc(mainObjectContext)==0 { color = MAKECOLOR(0.8, 0.0, 0.0, 1.0) message = "You have no watched repositories, please add some to your watchlist and refresh after a little while." } else if !Repo.interestedInPrs() && !Repo.interestedInIssues() { color = MAKECOLOR(0.8, 0.0, 0.0, 1.0) message = "All your watched repositories are marked as hidden, please enable issues or PRs for some of them." } else if openRequests==0 { message = "No open PRs in your configured repositories." } return emptyMessage(message, color: color) } class func reasonForEmptyIssuesWithFilter(filterValue: String?) -> NSAttributedString { let openIssues = Issue.countOpenIssuesInMoc(mainObjectContext) var color = COLOR_CLASS.lightGrayColor() var message: String = "" if !ApiServer.someServersHaveAuthTokensInMoc(mainObjectContext) { color = MAKECOLOR(0.8, 0.0, 0.0, 1.0) message = "There are no configured API servers in your settings, please ensure you have added at least one server with a valid API token." } else if app.isRefreshing { message = "Refreshing issue information, please wait a moment..." } else if !(filterValue ?? "").isEmpty { message = "There are no issues matching this filter." } else if openIssues > 0 { message = "\(openIssues) issues are hidden by your settings." } else if Repo.countVisibleReposInMoc(mainObjectContext)==0 { color = MAKECOLOR(0.8, 0.0, 0.0, 1.0) message = "You have no watched repositories, please add some to your watchlist and refresh after a little while." } else if !Repo.interestedInPrs() && !Repo.interestedInIssues() { color = MAKECOLOR(0.8, 0.0, 0.0, 1.0) message = "All your watched repositories are marked as hidden, please enable issues or PRs for some of them." } else if openIssues==0 { message = "No open issues in your configured repositories." } return emptyMessage(message, color: color) } class func emptyMessage(message: String, color: COLOR_CLASS) -> NSAttributedString { let p = NSMutableParagraphStyle() p.lineBreakMode = NSLineBreakMode.ByWordWrapping #if os(OSX) p.alignment = NSTextAlignment.Center return NSAttributedString(string: message, attributes: [NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: p]) #elseif os(iOS) p.alignment = NSTextAlignment.Center return NSAttributedString(string: message, attributes: [ NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: p, NSFontAttributeName: FONT_CLASS.systemFontOfSize(FONT_CLASS.smallSystemFontSize()) ]) #endif } class func idForUriPath(uriPath: String?) -> NSManagedObjectID? { if let up = uriPath, u = NSURL(string: up) { return persistentStoreCoordinator.managedObjectIDForURIRepresentation(u) } return nil } } /////////////////////////////////////// let mainObjectContext = { () -> NSManagedObjectContext in let m = NSManagedObjectContext(concurrencyType:NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) m.undoManager = nil m.persistentStoreCoordinator = persistentStoreCoordinator #if DATA_READONLY m.stalenessInterval = 0.0 #endif DLog("Database setup complete") return m }() var _justMigrated: Bool = false let persistentStoreCoordinator = { ()-> NSPersistentStoreCoordinator in let dataDir = dataFilesDirectory() let sqlStorePath = dataDir.URLByAppendingPathComponent("Trailer.sqlite") let mom = NSManagedObjectModel(contentsOfURL: NSBundle.mainBundle().URLForResource("Trailer", withExtension: "momd")!)! let fileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(sqlStorePath.path!) { let m = try! NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(NSSQLiteStoreType, URL: sqlStorePath, options: nil) _justMigrated = !mom.isConfiguration(nil, compatibleWithStoreMetadata: m) } else { try! fileManager.createDirectoryAtPath(dataDir.path!, withIntermediateDirectories: true, attributes: nil) } var newCoordinator = NSPersistentStoreCoordinator(managedObjectModel:mom) if !addStorePath(sqlStorePath, newCoordinator: newCoordinator) { DLog("Failed to migrate/load DB store - will nuke it and retry") removeDatabaseFiles() newCoordinator = NSPersistentStoreCoordinator(managedObjectModel:mom) if !addStorePath(sqlStorePath, newCoordinator: newCoordinator) { DLog("Catastrophic failure, app is probably corrupted and needs reinstall") abort() } } return newCoordinator }() func dataFilesDirectory() -> NSURL { #if os(iOS) return sharedFilesDirectory() #else return legacyFilesDirectory() #endif } private func legacyFilesDirectory() -> NSURL { let f = NSFileManager.defaultManager() var appSupportURL = f.URLsForDirectory(NSSearchPathDirectory.ApplicationSupportDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last! appSupportURL = appSupportURL.URLByAppendingPathComponent("com.housetrip.Trailer") DLog("Files in %@", appSupportURL) return appSupportURL } private func sharedFilesDirectory() -> NSURL { let appSupportURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.Trailer")! DLog("Shared files in %@", appSupportURL) return appSupportURL } private func addStorePath(sqlStore: NSURL, newCoordinator: NSPersistentStoreCoordinator) -> Bool { #if DATA_READONLY if NSFileManager.defaultManager().fileExistsAtPath(sqlStore.path!) { // may need migration let m = try! NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(NSSQLiteStoreType, URL: sqlStore, options: nil) if newCoordinator.managedObjectModel.isConfiguration(nil, compatibleWithStoreMetadata: m) == false { do { let tempStore = try newCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: sqlStore, options: [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]) try newCoordinator.removePersistentStore(tempStore) } catch { DLog("Error while migrating read/write DB store before mounting readonly %@", (error as NSError).localizedDescription) return false } } } else { // may need creating do { let tempStore = try newCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: sqlStore, options: nil) try newCoordinator.removePersistentStore(tempStore) } catch { DLog("Error while creating read/write DB store before mounting readonly %@", (error as NSError).localizedDescription) return false } } #endif do { var storeOptions = [ NSMigratePersistentStoresAutomaticallyOption: NSNumber(bool: true), NSInferMappingModelAutomaticallyOption: NSNumber(bool: true), NSSQLitePragmasOption: ["synchronous":"OFF", "fullfsync":"0"]] #if DATA_READONLY storeOptions[NSReadOnlyPersistentStoreOption] = NSNumber(bool: true) #endif try newCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: sqlStore, options: storeOptions) } catch { DLog("Error while mounting DB store %@", (error as NSError).localizedDescription) return false } return true } func existingObjectWithID(id: NSManagedObjectID) -> NSManagedObject? { do { return try mainObjectContext.existingObjectWithID(id) } catch { return nil } } func removeDatabaseFiles() { let fm = NSFileManager.defaultManager() let documentsDirectory = dataFilesDirectory().path! do { for file in try fm.contentsOfDirectoryAtPath(documentsDirectory) { if file.rangeOfString("Trailer.sqlite") != nil { DLog("Removing old database file: %@",file) try! fm.removeItemAtPath(documentsDirectory.stringByAppendingPathComponent(file)) } } } catch { /* no directory */ } } ////////////////////////////////
mit
d23ddc621f6b1cc3a04555edcc09ce7b
35.685149
182
0.738584
3.997842
false
false
false
false
BBRick/wp
wp/Scenes/Share/RechageVC/SuccessWithdrawVC.swift
1
2354
// // SuccessWithdrawVC.swift // wp // // Created by sum on 2017/1/6. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit class SuccessWithdrawVC: BaseTableViewController { @IBOutlet weak var bankLogo: UIImageView! // 银行名称 @IBOutlet weak var bankName: UILabel! // 提现金额 @IBOutlet weak var moneyAccount: UILabel! // 状态 @IBOutlet weak var status: UILabel! override func viewDidLoad() { super.viewDidLoad() navLeftBtn() title = "提现状态" let index = ShareModel.share().detailModel.cardNo.index(ShareModel.share().detailModel.cardNo.startIndex, offsetBy: ShareModel.share().detailModel.cardNo.length() - 4) self.bankName.text = ShareModel.share().detailModel.bank + " ( " + ShareModel.share().detailModel.cardNo.substring(from: index) + " )" moneyAccount.text = String.init(format: "%.2f", ShareModel.share().detailModel.amount) self.status.text! = ShareModel.share().detailModel.status == 1 ? "处理中" : (ShareModel.share().detailModel.status == 2 ? "提现成功" : "提现失败") bankLogo.image = BankLogoColor.share().checkLocalBank(string: ShareModel.share().detailModel.bank) ? UIImage.init(named: BankLogoColor.share().checkLocalBankImg(string: ShareModel.share().detailModel.bank)) : UIImage.init(named: "unionPay") } func navLeftBtn(){ let btn : UIButton = UIButton.init(type: UIButtonType.custom) btn.setTitle("", for: UIControlState.normal) btn.setBackgroundImage(UIImage.init(named: "back"), for: UIControlState.normal ) btn.addTarget(self, action: #selector(popself), for: UIControlEvents.touchUpInside) btn.frame = CGRect.init(x: 0, y: 0, width: 20, height: 20) let barItem : UIBarButtonItem = UIBarButtonItem.init(customView: btn) self.navigationItem.leftBarButtonItem = barItem } func popself(){ let _ = self.navigationController?.popToRootViewController(animated: true) } // 请求接口 override func didRequest() { AppAPIHelper.user().creditdetail(rid:1111000011, complete: { (result) -> ()? in // self?.didRequestComplete(result) return nil }, error: errorBlockFunc()) } }
apache-2.0
d6a0054591322344a4c7dfd43a194c6d
35.396825
248
0.649804
4.065603
false
false
false
false
intellum/neeman
Source/WebViewController.swift
1
19571
//import UIKit import WebKit /** Represents an object that can be used to display web page. */ public protocol NeemanViewController { /** The initial URL to display in the web view. Set this in your storyboard in the "User Defined Runtime Attributes" */ var URLString: String? { get set } /** This is called when the initial page needs to be reloaded. */ func refresh() } extension WebViewController: UIScrollViewDelegate { public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if neemanRefreshControl?.isRefreshing ?? false { refresh() } } } /** WebViewController displays the contents of a URL and pushes a new instance of itself once the user clicks on a link that causes an URL change. It also provides support for authentication. It makes injecting Javascript into your webapp easy. */ open class WebViewController: UIViewController, NeemanViewController, WKScriptMessageHandler { // MARK: Outlets /// Shows that the web view is still loading the page. @IBOutlet open var activityIndicator: UIActivityIndicatorView? @IBOutlet open var activityIndicatorHolder: UIView? @IBOutlet weak var closePopupBarButtonItem: UIBarButtonItem? /// Shows the progress toward loading the page. @IBOutlet open var progressView: UIProgressView? /// Displays an error the occured whilst loading the page. internal lazy var errorViewController: ErrorViewController = { return ErrorHandling().viewController() }() // MARK: Properties /// The navigation delegate that will receive changes in loading, estimated progress and further navigation. open var navigationDelegate: WebViewNavigationDelegate? /// The UI delegate that allows us to implement our own code to handle window.open(), alert(), confirm() and prompt(). open var uiDelegate: WebViewUIDelegate? /// This is a popup window that is opened when javascript code calles window.open(). open var uiDelegatePopup: WebViewUIDelegate? /// This is a navigation controller that is used to present a popup webview modally. open var popupNavController: UINavigationController? /// This is the cookie storage we should take the cookies from. By default it is HTTPCookieStorage.shared but this can be overridden to use, for example, a shared cookie store. open var cookieStorage = HTTPCookieStorage.shared /// This is the count of how many web view controllers are currently loading. static var networkActivityCount: Int = 0 { didSet { networkActivityCount = max(0, networkActivityCount) DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = networkActivityCount > 0 } } } /// The initial URL that the web view is loading. Use URLString to set the URL. open var rootURL: URL? { get { return (absoluteURLString != nil) ? URL(string: absoluteURLString!) : nil } } /** The initial URL to display in the web view. Set this in your storyboard in the "User Defined Runtime Attributes" You can set baseURL in Settings if you would like to use relative URLs instead. */ @IBInspectable open var URLString: String? /** If URLString is not an absolute URL and if you have set the baseURL in Settings then this returns the absolute URL by combining the two. */ var absoluteURLString: String? { get { if let urlString = URLString, !urlString.contains("://"), urlString != "about:blank" { return urlString } return URLString } } /** A UIRefreshControl is automatically added to the WKWebView. When you pull down your webView the page will be refreshed. */ open var neemanRefreshControl: UIRefreshControl? /** This is set once the web view has successfully loaded. If for some reason the page doesn't load then we know know when we return we should try again. */ open internal(set) var hasLoadedContent: Bool = false /** The WKWebView in which the content of the URL defined in URLString will be dispayed. */ open var webView: WKWebView! /// A web view that is used to display a window that was opened with window.open(). open var webViewPopup: WKWebView? /// Observes properties of a web view such as loading, estimatedProgress and its title. var webViewObserver: WebViewObserver = WebViewObserver() //MARK: Lifecycle /** Setup the web view, the refresh controll, the activity indicator, progress view and observers. */ override open func viewDidLoad() { super.viewDidLoad() setupWebView() setupRefreshControl() setupActivityIndicator() setupProgressView() addObservers() webViewObserver.delegate = self loadURL(rootURL) } override open func awakeFromNib() { super.awakeFromNib() UIApplication.shared.isNetworkActivityIndicatorVisible = true } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if rootURL == nil { assert(false, "You need to set URLString on WebViewController. Do this in code or in the Attributes Inspector in Interface Builder.") dismiss(animated: false, completion: nil) } } /** Setup the notification handlers and KVO. */ func addObservers() { NotificationCenter.default.addObserver(self, selector: #selector(self.didLogout(_:)), name: NSNotification.Name(rawValue: WebViewControllerDidLogout), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.didLogin(_:)), name: NSNotification.Name(rawValue: WebViewControllerDidLogin), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.didBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.forceReloadOnAppear(_:)), name: NSNotification.Name(rawValue: WebViewControllerForceReloadOnAppear), object: nil) webViewObserver.startObservingWebView(webView) } /** Stop observing notifications and KVO. */ deinit { NotificationCenter.default.removeObserver(self) webViewObserver.stopObservingWebView(webViewPopup) webViewObserver.stopObservingWebView(webView) if webView != nil && webView.isLoading { WebViewController.networkActivityCount -= 1 } } /** In here we check to see if we have previously loaded a page successfully. If not we reload the root URL. - parameter animated: Was the appearence animated. */ override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let rootURL = rootURL, shouldReloadOnViewWillAppear(animated) && !webView.isLoading { loadURL(rootURL) } webView.scrollView.delegate = self } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) webView?.scrollView.delegate = nil } /** This action is called by as a result of a UIApplicationDidBecomeActiveNotification. */ @objc open func didBecomeActive(_ notification: Notification) { if !hasLoadedContent { loadURL(rootURL) } } /** This action is called by as a result of a UIApplicationDidBecomeActiveNotification. */ @objc open func forceReloadOnAppear(_ notification: Notification) { hasLoadedContent = false } /** This is called from viewWillAppear and reloads the page if the page has not yet been successfully loaded. If you want to do something different you can override this method and place additional logic in the viewWill* and viewDid* events. - parameter animated: Whether the appearance is happening with animation or not. - returns: Whether the page should be reloaded. */ open func shouldReloadOnViewWillAppear(_ animated: Bool) -> Bool { if !hasLoadedContent { return true } if webView.url?.absoluteString == "about:blank" { return true } return false } /** Since iOS only automatically adjusts scroll view insets for the main web view we have to do it ourselves for the popup web view. */ override open func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() webViewPopup?.scrollView.contentInset = webView.scrollView.contentInset webViewPopup?.scrollView.scrollIndicatorInsets = webView.scrollView.scrollIndicatorInsets } // MARK: Notification Handlers /** In here we set hasLoadedContent so that we reload the page after returning back. - parameter notification: The notification received. */ @objc open func didLogout(_ notification: Notification) { hasLoadedContent = false } /** This forces an imidiate reload of the page using the rootURL. You can override this method if you would prefer instead just to call any of the web view's methods to reload. - parameter notification: The notification received. */ @objc open func didLogin(_ notification: Notification) { if isViewLoaded && view.window != nil && !webView.isLoading { loadURL(rootURL) } } /** Desides how to handle an error based on its code. - parameter webView: The web view the error came from. - parameter error: The error the web view incountered. */ open func webView(_ webView: WKWebView, didFinishLoadingWithError error: NSError) { assert(error.code != NSURLErrorAppTransportSecurityRequiresSecureConnection, "You need to allow insecure loads in your App Transport Security settings. See https://stackoverflow.com/a/40299837/215748") let networkError = NetworkError(error: error) switch networkError { case .NotConnectedToInternet: showHTTPError(networkError) case .NotReachedServer: showHTTPError(networkError) default:() } } /** Creates a new web view using the Neeman.storyboard. If you would like to load a web view controller from your own storyboard then you should override this method and use your subclass in your storyboard. - returns: A new web view controller. */ open func createNewWebViewController(url: URL) -> NeemanViewController? { let neemanStoryboard = UIStoryboard(name: "Neeman", bundle: Bundle(for: WebViewController.self)) if let webViewController: WebViewController = neemanStoryboard.instantiateViewController( withIdentifier: (NSStringFromClass(WebViewController.self) as NSString).pathExtension) as? WebViewController { webViewController.URLString = url.absoluteString return webViewController } return nil } /** This is called when a message is received from your injected javascript code. You will have to register to receive these script messages. ```swift webView.configuration.userContentController.addScriptMessageHandler(self, name: "yourMessageName") ``` - parameter userContentController: The user content controller that is managing you messages. - parameter message: The script message received from your javascript. */ open func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { } // MARK: WebView /** Load a new URL in the web view. - parameter URL: The URL to laod. */ open func loadURL(_ url: URL?) { guard let url = url else { return } showError(message: nil) hasLoadedContent = false progressView?.setProgress(0, animated: false) loadRequest(NSMutableURLRequest(url: url)) } /** Load a new request in the web view. - parameter request: The request to load. */ open func loadRequest(_ request: NSMutableURLRequest?) { guard let webView = webView else { return } if let url = request?.url, let cookies = cookieStorage.cookies(for: url) { request?.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: cookies) } if let request = request { webView.load(request as URLRequest) } } /** Creates a web view for a popup window. The web view is added onto of the current one. You should override this if you would like to implement something like tabs. - parameter newWebView: The new web view. - parameter url: The URL to load. */ open func popupWebView(_ newWebView: WKWebView, withURL url: URL) { if let webViewPopup = webViewPopup { webViewObserver.stopObservingWebView(webViewPopup) webViewPopup.removeFromSuperview() } webViewPopup = newWebView guard let webViewPopup = webViewPopup else { return } uiDelegatePopup = WebViewUIDelegate(baseURL: url) uiDelegatePopup?.delegate = self webViewPopup.uiDelegate = uiDelegatePopup webViewPopup.allowsBackForwardNavigationGestures = true webViewPopup.translatesAutoresizingMaskIntoConstraints = false webViewPopup.frame = view.bounds if popupNavController == nil { popupNavController = setupPopupNavigationController() } let popupViewController = popupNavController!.viewControllers.first! popupViewController.view.addSubview(webViewPopup) webViewObserver.startObservingWebView(webViewPopup) autolayoutWebView(webViewPopup) if popupNavController?.presentingViewController == nil { popupNavController?.modalPresentationStyle = .fullScreen present(popupNavController!, animated: true, completion: nil) } } open func setupPopupNavigationController(urlString: String? = "about:blank") -> UINavigationController? { let popupViewController = UIViewController() popupNavController = UINavigationController(rootViewController: popupViewController) popupViewController.modalPresentationStyle = .fullScreen if closePopupBarButtonItem == nil { let barButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.didTapDoneButton(_:))) popupViewController.navigationItem.rightBarButtonItem = barButton closePopupBarButtonItem = barButton } return popupNavController } /** Called when the webView updates the value of its loading property. - Parameter webView: The instance of WKWebView that updated its loading property. - Parameter loading: The value that the WKWebView updated its loading property to. */ open func webView(_ webView: WKWebView, didChangeLoading loading: Bool) { updateProgressViewWithWebView(webView: webView) updateActivityIndicatorWithWebView(webView) if !loading { if neemanRefreshControl?.isRefreshing ?? false { self.neemanRefreshControl?.endRefreshing() } if let _ = webView.url { hasLoadedContent = true } } } } extension WebViewController: NeemanNavigationDelegate { //MARK: NeemanNavigationDelegate /** Pushes a new web view onto the navigation stack. - parameter url: The URL to load in the web view. */ @objc open func pushNewWebViewControllerWithURL(_ url: URL) { let urlString = url.absoluteString debugPrint("Pushing: \(urlString)") if let webViewController = createNewWebViewController(url: url) { if let viewController = webViewController as? UIViewController { navigationController?.pushViewController(viewController, animated: true) } } } /** Decide if we should prevent a navigation action from being loading in a new web view. It will instead be loaded in the current one. - parameter navigationAction: The navigation action that will be loaded. - returns: false */ @objc open func shouldPreventPushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return false } /** Decide if we should force the navigation action to be loaded in a new web view. This is useful if a page is setting document.location within a click handler. Web kit does not realise that this was from a "link" click. In this case we can make sure it is handled like a link. - parameter navigationAction: The navigation action that will be loaded. - returns: false */ @objc open func shouldForcePushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return false } /** Decide if we should prevent the navigation action from being loaded. This is useful if, for example, you would like to switch to another tab that is displaying this request. - parameter navigationAction: The navigation action that will be loaded. - returns: Whether we should prevent the request from being loaded. */ @objc open func shouldPreventNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return false } /** Default implementation doesn't do anything. - parameter webView: The web view that finished navigating. - parameter url: The final URL of the web view. */ @objc open func webView(_ webView: WKWebView, didFinishNavigationWithURL url: URL?) { errorViewController.view.removeFromSuperview() } /** Default implementation doesn't do anything. - parameter webView: The web view that finished navigating. - parameter url: The final URL of the web view. */ @objc open func webView(_ webView: WKWebView, didReceiveServerRedirectToURL url: URL?) { } } // MARK: Notifications /** Posting this will cause the didLogout(_:) method to be called. You can post this when you logout so that pages are reloaded after logging back in again. */ public let WebViewControllerDidLogout = "WebViewControllerDidLogout" /** Posting this will cause the didLogin(_:) method to be called. You can post this from your custom native authentication code. */ public let WebViewControllerDidLogin = "WebViewControllerDidLogin" /** Posting this will cause the web view to reload it's content next time the viewDidAppear is called. */ public let WebViewControllerForceReloadOnAppear = "WebViewControllerForceReloadOnAppear" /** Posting this will enable you to show a modal login view controller. */ public let WebViewControllerDidRequestLogin = "WebViewControllerDidRequestLogin"
mit
b59b748c1f4604842583cd2f88fedf3f
37.299413
180
0.670533
5.475937
false
false
false
false
brave/browser-ios
Client/Extensions/JSONSerializationExtensions.swift
2
946
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation extension JSONSerialization { class func jsObject(withNative native: Any?, escaped: Bool = false) -> String? { guard let native = native, let data = try? JSONSerialization.data(withJSONObject: native, options: JSONSerialization.WritingOptions(rawValue: 0)) else { return nil } // Convert to string of JSON data, encode " for JSON to JS conversion var encoded = String(data: data, encoding: String.Encoding.utf8) if escaped { encoded = encoded?.replacingOccurrences(of: "\"", with: "\\\"") } encoded = encoded?.replacingOccurrences(of: "\"null\"", with: "null") return encoded } }
mpl-2.0
f7fd8a8b8044b0f0f555f5793309cf22
36.84
198
0.621564
4.73
false
false
false
false
danielgindi/ios-charts
Source/Charts/Data/Implementations/Standard/ChartData.swift
1
18248
// // ChartData.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class ChartData: NSObject, ExpressibleByArrayLiteral { @objc public internal(set) var xMax = -Double.greatestFiniteMagnitude @objc public internal(set) var xMin = Double.greatestFiniteMagnitude @objc public internal(set) var yMax = -Double.greatestFiniteMagnitude @objc public internal(set) var yMin = Double.greatestFiniteMagnitude var leftAxisMax = -Double.greatestFiniteMagnitude var leftAxisMin = Double.greatestFiniteMagnitude var rightAxisMax = -Double.greatestFiniteMagnitude var rightAxisMin = Double.greatestFiniteMagnitude // MARK: - Accessibility /// When the data entry labels are generated identifiers, set this property to prepend a string before each identifier /// /// For example, if a label is "#3", settings this property to "Item" allows it to be spoken as "Item #3" @objc open var accessibilityEntryLabelPrefix: String? /// When the data entry value requires a unit, use this property to append the string representation of the unit to the value /// /// For example, if a value is "44.1", setting this property to "m" allows it to be spoken as "44.1 m" @objc open var accessibilityEntryLabelSuffix: String? /// If the data entry value is a count, set this to true to allow plurals and other grammatical changes /// **default**: false @objc open var accessibilityEntryLabelSuffixIsCount: Bool = false var _dataSets = [Element]() public override required init() { super.init() } public required init(arrayLiteral elements: Element...) { super.init() self.dataSets = elements } @objc public init(dataSets: [Element]) { super.init() self.dataSets = dataSets } @objc public convenience init(dataSet: Element) { self.init(dataSets: [dataSet]) } /// Call this method to let the ChartData know that the underlying data has changed. /// Calling this performs all necessary recalculations needed when the contained data has changed. @objc open func notifyDataChanged() { calcMinMax() } @objc open func calcMinMaxY(fromX: Double, toX: Double) { forEach { $0.calcMinMaxY(fromX: fromX, toX: toX) } // apply the new data calcMinMax() } /// calc minimum and maximum y value over all datasets @objc open func calcMinMax() { leftAxisMax = -.greatestFiniteMagnitude leftAxisMin = .greatestFiniteMagnitude rightAxisMax = -.greatestFiniteMagnitude rightAxisMin = .greatestFiniteMagnitude yMax = -.greatestFiniteMagnitude yMin = .greatestFiniteMagnitude xMax = -.greatestFiniteMagnitude xMin = .greatestFiniteMagnitude forEach { calcMinMax(dataSet: $0) } // left axis let firstLeft = getFirstLeft(dataSets: dataSets) if firstLeft !== nil { leftAxisMax = firstLeft!.yMax leftAxisMin = firstLeft!.yMin for dataSet in _dataSets where dataSet.axisDependency == .left { if dataSet.yMin < leftAxisMin { leftAxisMin = dataSet.yMin } if dataSet.yMax > leftAxisMax { leftAxisMax = dataSet.yMax } } } // right axis let firstRight = getFirstRight(dataSets: dataSets) if firstRight !== nil { rightAxisMax = firstRight!.yMax rightAxisMin = firstRight!.yMin for dataSet in _dataSets where dataSet.axisDependency == .right { if dataSet.yMin < rightAxisMin { rightAxisMin = dataSet.yMin } if dataSet.yMax > rightAxisMax { rightAxisMax = dataSet.yMax } } } } /// Adjusts the current minimum and maximum values based on the provided Entry object. @objc open func calcMinMax(entry e: ChartDataEntry, axis: YAxis.AxisDependency) { xMax = Swift.max(xMax, e.x) xMin = Swift.min(xMin, e.x) yMax = Swift.max(yMax, e.y) yMin = Swift.min(yMin, e.y) switch axis { case .left: leftAxisMax = Swift.max(leftAxisMax, e.y) leftAxisMin = Swift.min(leftAxisMin, e.y) case .right: rightAxisMax = Swift.max(rightAxisMax, e.y) rightAxisMin = Swift.min(rightAxisMin, e.y) } } /// Adjusts the minimum and maximum values based on the given DataSet. @objc open func calcMinMax(dataSet d: Element) { xMax = Swift.max(xMax, d.xMax) xMin = Swift.min(xMin, d.xMin) yMax = Swift.max(yMax, d.yMax) yMin = Swift.min(yMin, d.yMin) switch d.axisDependency { case .left: leftAxisMax = Swift.max(leftAxisMax, d.yMax) leftAxisMin = Swift.min(leftAxisMin, d.yMin) case .right: rightAxisMax = Swift.max(rightAxisMax, d.yMax) rightAxisMin = Swift.min(rightAxisMin, d.yMin) } } /// The number of LineDataSets this object contains // exists only for objc compatibility @objc open var dataSetCount: Int { return dataSets.count } @objc open func getYMin(axis: YAxis.AxisDependency) -> Double { // TODO: Why does it make sense to return the other axisMin if there is none for the one requested? switch axis { case .left: if leftAxisMin == .greatestFiniteMagnitude { return rightAxisMin } else { return leftAxisMin } case .right: if rightAxisMin == .greatestFiniteMagnitude { return leftAxisMin } else { return rightAxisMin } } } @objc open func getYMax(axis: YAxis.AxisDependency) -> Double { if axis == .left { if leftAxisMax == -.greatestFiniteMagnitude { return rightAxisMax } else { return leftAxisMax } } else { if rightAxisMax == -.greatestFiniteMagnitude { return leftAxisMax } else { return rightAxisMax } } } /// All DataSet objects this ChartData object holds. @objc open var dataSets: [Element] { get { return _dataSets } set { _dataSets = newValue notifyDataChanged() } } /// Get the Entry for a corresponding highlight object /// /// - Parameters: /// - highlight: /// - Returns: The entry that is highlighted @objc open func entry(for highlight: Highlight) -> ChartDataEntry? { guard highlight.dataSetIndex < dataSets.endIndex else { return nil } return self[highlight.dataSetIndex].entryForXValue(highlight.x, closestToY: highlight.y) } /// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.** /// /// - Parameters: /// - label: /// - ignorecase: /// - Returns: The DataSet Object with the given label. Sensitive or not. @objc open func dataSet(forLabel label: String, ignorecase: Bool) -> Element? { guard let index = index(forLabel: label, ignoreCase: ignorecase) else { return nil } return self[index] } @objc(dataSetAtIndex:) open func dataSet(at index: Index) -> Element? { guard dataSets.indices.contains(index) else { return nil } return self[index] } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// - Returns: `true` if a DataSet was removed, `false` ifno DataSet could be removed. @objc @discardableResult open func removeDataSet(_ dataSet: Element) -> Element? { guard let index = firstIndex(where: { $0 === dataSet }) else { return nil } return remove(at: index) } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. @objc(addEntry:dataSetIndex:) open func appendEntry(_ e: ChartDataEntry, toDataSet dataSetIndex: Index) { guard dataSets.indices.contains(dataSetIndex) else { return print("ChartData.addEntry() - Cannot add Entry because dataSetIndex too high or too low.", terminator: "\n") } let set = self[dataSetIndex] if !set.addEntry(e) { return } calcMinMax(entry: e, axis: set.axisDependency) } /// Removes the given Entry object from the DataSet at the specified index. @objc @discardableResult open func removeEntry(_ entry: ChartDataEntry, dataSetIndex: Index) -> Bool { guard dataSets.indices.contains(dataSetIndex) else { return false } // remove the entry from the dataset let removed = self[dataSetIndex].removeEntry(entry) if removed { calcMinMax() } return removed } /// Removes the Entry object closest to the given xIndex from the ChartDataSet at the /// specified index. /// /// - Returns: `true` if an entry was removed, `false` ifno Entry was found that meets the specified requirements. @objc @discardableResult open func removeEntry(xValue: Double, dataSetIndex: Index) -> Bool { guard dataSets.indices.contains(dataSetIndex), let entry = self[dataSetIndex].entryForXValue(xValue, closestToY: .nan) else { return false } return removeEntry(entry, dataSetIndex: dataSetIndex) } /// - Returns: The DataSet that contains the provided Entry, or null, if no DataSet contains this entry. @objc open func getDataSetForEntry(_ e: ChartDataEntry) -> Element? { return first { $0.entryForXValue(e.x, closestToY: e.y) === e } } /// - Returns: The index of the provided DataSet in the DataSet array of this data object, or -1 if it does not exist. @objc open func index(of dataSet: Element) -> Index { // TODO: Return nil instead of -1 return firstIndex(where: { $0 === dataSet }) ?? -1 } /// - Returns: The first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found. @objc open func getFirstLeft(dataSets: [Element]) -> Element? { return first { $0.axisDependency == .left } } /// - Returns: The first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found. @objc open func getFirstRight(dataSets: [Element]) -> Element? { return first { $0.axisDependency == .right } } /// - Returns: All colors used across all DataSet objects this object represents. @objc open var colors: [NSUIColor] { // TODO: Don't return nil return reduce(into: []) { $0 += $1.colors } } /// Sets a custom ValueFormatter for all DataSets this data object contains. @objc open func setValueFormatter(_ formatter: ValueFormatter) { forEach { $0.valueFormatter = formatter } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. @objc open func setValueTextColor(_ color: NSUIColor) { forEach { $0.valueTextColor = color } } /// Sets the font for all value-labels for all DataSets this data object contains. @objc open func setValueFont(_ font: NSUIFont) { forEach { $0.valueFont = font } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. @objc open func setDrawValues(_ enabled: Bool) { forEach { $0.drawValuesEnabled = enabled } } /// Enables / disables highlighting values for all DataSets this data object contains. /// If set to true, this means that values can be highlighted programmatically or by touch gesture. @objc open var isHighlightEnabled: Bool { get { return allSatisfy { $0.isHighlightEnabled } } set { forEach { $0.highlightEnabled = newValue } } } /// Clears this data object from all DataSets and removes all Entries. /// Don't forget to invalidate the chart after this. @objc open func clearValues() { removeAll(keepingCapacity: false) } /// Checks if this data object contains the specified DataSet. /// /// - Returns: `true` if so, `false` ifnot. @objc open func contains(dataSet: Element) -> Bool { return contains { $0 === dataSet } } /// The total entry count across all DataSet objects this data object contains. @objc open var entryCount: Int { return reduce(0) { return $0 + $1.entryCount } } /// The DataSet object with the maximum number of entries or null if there are no DataSets. @objc open var maxEntryCountSet: Element? { return self.max { $0.entryCount > $1.entryCount } } } // MARK: MutableCollection extension ChartData: MutableCollection { public typealias Index = Int public typealias Element = ChartDataSetProtocol public var startIndex: Index { return dataSets.startIndex } public var endIndex: Index { return dataSets.endIndex } public func index(after: Index) -> Index { return dataSets.index(after: after) } public subscript(position: Index) -> Element { get { return dataSets[position] } set { self._dataSets[position] = newValue } } } // MARK: RandomAccessCollection extension ChartData: RandomAccessCollection { public func index(before: Index) -> Index { return dataSets.index(before: before) } } // TODO: Conform when dropping Objective-C support // MARK: RangeReplaceableCollection extension ChartData//: RangeReplaceableCollection { @objc(addDataSet:) public func append(_ newElement: Element) { _dataSets.append(newElement) calcMinMax(dataSet: newElement) } @objc(removeDataSetByIndex:) public func remove(at position: Index) -> Element { let element = _dataSets.remove(at: position) calcMinMax() return element } public func removeFirst() -> Element { assert(!(self is CombinedChartData), "\(#function) not supported for CombinedData") let element = _dataSets.removeFirst() notifyDataChanged() return element } public func removeFirst(_ n: Int) { assert(!(self is CombinedChartData), "\(#function) not supported for CombinedData") _dataSets.removeFirst(n) notifyDataChanged() } public func removeLast() -> Element { assert(!(self is CombinedChartData), "\(#function) not supported for CombinedData") let element = _dataSets.removeLast() notifyDataChanged() return element } public func removeLast(_ n: Int) { assert(!(self is CombinedChartData), "\(#function) not supported for CombinedData") _dataSets.removeLast(n) notifyDataChanged() } public func removeSubrange<R>(_ bounds: R) where R : RangeExpression, Index == R.Bound { assert(!(self is CombinedChartData), "\(#function) not supported for CombinedData") _dataSets.removeSubrange(bounds) notifyDataChanged() } public func removeAll(keepingCapacity keepCapacity: Bool) { assert(!(self is CombinedChartData), "\(#function) not supported for CombinedData") _dataSets.removeAll(keepingCapacity: keepCapacity) notifyDataChanged() } public func replaceSubrange<C>(_ subrange: Swift.Range<Index>, with newElements: C) where C : Collection, Element == C.Element { assert(!(self is CombinedChartData), "\(#function) not supported for CombinedData") _dataSets.replaceSubrange(subrange, with: newElements) newElements.forEach { self.calcMinMax(dataSet: $0) } } } // MARK: Swift Accessors extension ChartData { /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.** /// /// - Parameters: /// - label: The label to search for /// - ignoreCase: if true, the search is not case-sensitive /// - Returns: The index of the DataSet Object with the given label. `nil` if not found public func index(forLabel label: String, ignoreCase: Bool) -> Index? { return ignoreCase ? firstIndex { $0.label?.caseInsensitiveCompare(label) == .orderedSame } : firstIndex { $0.label == label } } public subscript(label label: String, ignoreCase ignoreCase: Bool) -> Element? { guard let index = index(forLabel: label, ignoreCase: ignoreCase) else { return nil } return self[index] } public subscript(entry entry: ChartDataEntry) -> Element? { assert(!(self is CombinedChartData), "\(#function) not supported for CombinedData") guard let index = firstIndex(where: { $0.entryForXValue(entry.x, closestToY: entry.y) === entry }) else { return nil } return self[index] } }
apache-2.0
05558dee3c979ba64a6feef32e253ab1
30.790941
169
0.612067
4.876537
false
false
false
false
SwifterSwift/SwifterSwift
Tests/HealthKitTests/HKActivitySummaryExtensionsTests.swift
1
1984
// HKActivitySummaryExtensionsTests.swift - Copyright 2020 SwifterSwift @testable import SwifterSwift import XCTest #if !os(tvOS) #if canImport(HealthKit) import HealthKit class HKActivitySummaryExtensionsTests: XCTestCase { func testIsStandGoalMet() { let unit = HKUnit.count() let summary = HKActivitySummary() summary.appleStandHoursGoal = HKQuantity(unit: unit, doubleValue: 12) summary.appleStandHours = HKQuantity(unit: unit, doubleValue: 6) XCTAssertFalse(summary.isStandGoalMet) summary.appleStandHours = HKQuantity(unit: unit, doubleValue: 12) XCTAssert(summary.isStandGoalMet) summary.appleStandHours = HKQuantity(unit: unit, doubleValue: 14) XCTAssert(summary.isStandGoalMet) } func testIsExerciseTimeGoalMet() { let unit = HKUnit.minute() let summary = HKActivitySummary() summary.appleExerciseTimeGoal = HKQuantity(unit: unit, doubleValue: 30) summary.appleExerciseTime = HKQuantity(unit: unit, doubleValue: 6) XCTAssertFalse(summary.isExerciseTimeGoalMet) summary.appleExerciseTime = HKQuantity(unit: unit, doubleValue: 30) XCTAssert(summary.isExerciseTimeGoalMet) summary.appleExerciseTime = HKQuantity(unit: unit, doubleValue: 40) XCTAssert(summary.isExerciseTimeGoalMet) } func testIsEnergyBurnedGoalMet() { let unit = HKUnit.jouleUnit(with: .kilo) let summary = HKActivitySummary() summary.activeEnergyBurnedGoal = HKQuantity(unit: unit, doubleValue: 400) summary.activeEnergyBurned = HKQuantity(unit: unit, doubleValue: 200) XCTAssertFalse(summary.isEnergyBurnedGoalMet) summary.activeEnergyBurned = HKQuantity(unit: unit, doubleValue: 400) XCTAssert(summary.isEnergyBurnedGoalMet) summary.activeEnergyBurned = HKQuantity(unit: unit, doubleValue: 600) XCTAssert(summary.isEnergyBurnedGoalMet) } } #endif #endif
mit
b5bb446bd21262d79b35ce1d6f28ea72
33.807018
81
0.718246
4.428571
false
true
false
false
apple/swift
validation-test/compiler_crashers_fixed/01102-resolvetypedecl.swift
65
772
// 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 // RUN: not %target-swift-frontend %s -typecheck func c<e>() -> (e -> e) -> e { e, e -> e) ->)func d(f: b) -> <e>(() -> e) -> b { struct c<d : Sequence> { var b: [c<d>] { } protocol a { } class b: a { } func f<T : Boolean>(b: T) { } func e() { } } protocol c : b { func b otocol A { } struct } } class a<b : b, d : b where b.d == d> { } protocol b { typealias d typealias e = a<c<h>, d> } struct c<d, e: b where d.c == e
apache-2.0
06600c7fcd135d029be6badf9a86149c
21.705882
79
0.619171
2.787004
false
false
false
false
mtsanford/MPGTextField
Swift/MPGTextField-Swift/MPGTextField-Swift/ViewController.swift
5
2017
// // ViewController.swift // MPGTextField-Swift // // Created by Gaurav Wadhwani on 08/06/14. // Copyright (c) 2014 Mappgic. All rights reserved. // import UIKit class ViewController: UIViewController, MPGTextFieldDelegate { var sampleData = Dictionary<String, AnyObject>[]() @IBOutlet var name : MPGTextField_Swift override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.generateData() name.mDelegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func generateData(){ var err : NSErrorPointer? var dataPath = NSBundle.mainBundle().pathForResource("sample_data", ofType: "json") var data = NSData.dataWithContentsOfFile(dataPath, options: NSDataReadingOptions.DataReadingUncached, error: err!) var contents : AnyObject[]! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: err!) as AnyObject[] //println(contents[0]["first_name"]) for var i = 0;i<contents.count;++i{ var name = contents[i]["first_name"] as String var lName = contents[i]["last_name"] as String name += " " + lName var email = contents[i]["email"] as String var dictionary = ["DisplayText":name,"DisplaySubText":email,"CustomObject":contents[i]] sampleData.append(dictionary) } } func dataForPopoverInTextField(textfield: MPGTextField_Swift) -> Dictionary<String, AnyObject>[] { return sampleData } func textFieldShouldSelect(textField: MPGTextField_Swift) -> Bool{ return true } func textFieldDidEndEditing(textField: MPGTextField_Swift, withSelection data: Dictionary<String,AnyObject>){ println("Dictionary received = \(data)") } }
mit
06de68257670bfa5113d6af6263dd2f0
33.186441
156
0.654437
4.701632
false
false
false
false
ornlabs/simpleios
SimpleNetwork/SimpleNetwork/CakeTableViewController.swift
1
2742
import UIKit class CakeTableViewController: UITableViewController { private var tableRows = [String]() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let session = URLSession(configuration: URLSessionConfiguration.default) // todo Customize this url let task = session.dataTask(with: URL(string: "https://httpbin.org/get")!) { (data, response, error) in let json = try? JSONSerialization.jsonObject(with: data!, options: []) if let cakeDataArrayHash = json as? [Any] { cakeDataArrayHash.forEach({ (value) in if let cakeDataHash = value as? [String:Any] { // todo customize this // self.tableRows.append(cakeDataHash["avalue"] as! String) } }) } DispatchQueue.main.async { self.tableView.reloadData() } } task.resume() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableRows.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CakeTableCell", for: indexPath) as! CakeTableViewCell cell.configure(cakeName: tableRows[indexPath.row]) return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ }
mit
aa1fb2205788ada29a474a9b26dd330e
34.153846
136
0.615609
5.303675
false
false
false
false
qianqian2/ocStudy1
weibotext/weibotext/Class/Discover/DiscoverTableViewController.swift
1
3130
// // DiscoverTableViewController.swift // weiboText // // Created by arang on 16/12/2. // Copyright © 2016年 arang. All rights reserved. // import UIKit class DiscoverTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // 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. } */ }
apache-2.0
d42611849a955cefefcf49c330ce63f9
31.915789
136
0.670931
5.327087
false
false
false
false
avaidyam/Parrot
Parrot/DirectoryListViewController.swift
1
14936
import MochaUI import ParrotServiceExtension /* TODO: UISearchController for NSViewControllers. */ public class DirectoryListViewController: NSViewController, WindowPresentable, NSSearchFieldDelegate, NSCollectionViewDataSource, NSCollectionViewDelegate, NSCollectionViewDelegateFlowLayout { private lazy var collectionView: NSCollectionView = { let c = NSCollectionView(frame: .zero)//.modernize(wantsLayer: true) //c.layerContentsRedrawPolicy = .onSetNeedsDisplay // FIXME: causes a random white background c.dataSource = self c.delegate = self c.backgroundColors = [.clear] c.selectionType = .any let l = NSCollectionViewListLayout() l.globalSections = (32, 0) l.layoutDefinition = .global(SizeMetrics(item: CGSize(width: 0, height: 48))) //l.minimumInteritemSpacing = 0.0 //l.minimumLineSpacing = 0.0 //l.sectionInset = NSEdgeInsetsZero c.collectionViewLayout = l c.register(PersonCell.self, forItemWithIdentifier: .personCell) c.register(SearchCell.self, forSupplementaryViewOfKind: .globalHeader, withIdentifier: .searchCell) return c }() private lazy var scrollView: NSScrollView = { NSScrollView(for: self.collectionView).modernize() }() private lazy var indicator: MessageProgressView = { MessageProgressView().modernize(wantsLayer: true) }() private lazy var statusText: NSTextField = { let b = NSTextField(labelWithString: "Create...") b.textColor = .secondaryLabelColor b.controlSize = .small return b }() private lazy var statusButton: NSButton = { let b = LayerButton(title: "Cancel", target: nil, action: nil) .modernize(wantsLayer: true) b.performedAction = { [weak self] in if (self?.selection.count ?? 0) > 0 { self?.selectionHandler?() } else { self?.cancelOperation(nil) } } b.font = NSFont.from(name: .compactRoundedMedium, size: 13.0) b.bezelStyle = .roundRect // height = 18px return b }() private lazy var baseView: NSVisualEffectView = { let v = NSVisualEffectView().modernize() v.blendingMode = .withinWindow v.material = .sidebar v.state = .active v.isHidden = true // initial state v.add(subviews: self.statusText, self.statusButton) { v.heightAnchor == (18.0 + 8.0) v.centerYAnchor == self.statusText.centerYAnchor v.centerYAnchor == self.statusButton.centerYAnchor self.statusText.leadingAnchor == v.leadingAnchor + 4.0 self.statusButton.trailingAnchor == v.trailingAnchor - 4.0 self.statusText.trailingAnchor <= self.statusButton.leadingAnchor - 4.0 } return v }() private lazy var updateInterpolation: Interpolate<Double> = { let indicatorAnim = Interpolate(from: 0.0, to: 1.0, interpolator: EaseInOutInterpolator()) { [weak self] alpha in self?.scrollView.alphaValue = CGFloat(alpha) self?.indicator.alphaValue = CGFloat(1.0 - alpha) } indicatorAnim.add(at: 1.0) { UI { self.indicator.stopAnimation() } } indicatorAnim.handlerRunPolicy = .always let scaleAnim = Interpolate(from: CGAffineTransform(scaleX: 1.5, y: 1.5), to: .identity, interpolator: EaseInOutInterpolator()) { [weak self] scale in self?.scrollView.layer!.setAffineTransform(scale) } let group = AnyInterpolate.group(indicatorAnim, scaleAnim) return group }() // // // var directory: ParrotServiceExtension.Directory? { didSet { DispatchQueue.global(qos: .background).async { self.cachedFavorites = self.directory?.list(25) ?? [] UI { self.collectionView.reloadData() //self.collectionView.animator().scrollToItems(at: [IndexPath(item: 0, section: 0)], // scrollPosition: [.centeredHorizontally, .nearestVerticalEdge]) self.updateInterpolation.animate(duration: 1.5) } } } } public var displaysCloseOptions = false { didSet { self.scrollView.contentInsets = NSEdgeInsetsMake(0, 0, self.displaysCloseOptions ? 32 : 0, 0) self.baseView.isHidden = !self.displaysCloseOptions } } // We should be able to now edit things. public var canSelect: Bool = false { didSet { self.collectionView.selectionType = self.canSelect ? .any : .none //self.collectionView.allowsMultipleSelection = self.canSelect } } public var selectionHandler: (() -> ())? = nil // // // public private(set) var selection: [Person] = [] private var cachedFavorites: [Person] = [] private var currentSearch: [Person]? = nil private var searchQuery: String = "" { // TODO: BINDING HERE didSet { let oldVal = self.currentSource().map { $0.identifier } self.currentSearch = self.searchQuery == "" ? nil : self.directory?.search(by: self.searchQuery, limit: 25) let newVal = self.currentSource().map { $0.identifier } let updates = Changeset.edits(from: oldVal, to: newVal) UI { self.collectionView.update(with: updates, in: 1) {_ in} } } } private func currentSource() -> [Person] { var active = self.currentSearch != nil ? self.currentSearch! : self.cachedFavorites for s in self.selection { guard let idx = (active.index { $0.identifier == s.identifier }) else { continue } active.remove(at: idx) } return active } // // // public override func loadView() { self.title = "Directory" self.view = NSVisualEffectView() self.view.add(subviews: self.scrollView, self.baseView, self.indicator) { self.view.sizeAnchors >= CGSize(width: 128, height: 128) self.view.centerAnchors == self.indicator.centerAnchors self.view.edgeAnchors == self.scrollView.edgeAnchors self.view.bottomAnchor == self.baseView.bottomAnchor self.view.horizontalAnchors == self.baseView.horizontalAnchors } } public func prepare(window: NSWindow) { window.styleMask = [window.styleMask, .unifiedTitleAndToolbar, .fullSizeContentView] window.appearance = InterfaceStyle.current.appearance() if let vev = window.titlebar.view as? NSVisualEffectView { vev.material = .appearanceBased vev.state = .active vev.blendingMode = .withinWindow } window.titleVisibility = .hidden window.installToolbar(self) window.addTitlebarAccessoryViewController(LargeTypeTitleController(title: self.title)) /// Re-synchronizes the conversation name and identifier with the window. /// Center by default, but load a saved frame if available, and autosave. window.center() window.setFrameUsingName(NSWindow.FrameAutosaveName(rawValue: self.title!)) window.setFrameAutosaveName(NSWindow.FrameAutosaveName(rawValue: self.title!)) } /* public override func makeToolbarContainer() -> ToolbarContainer? { let t = ToolbarContainer() t.templateItems = [.windowTitle(viewController: self)] t.itemOrder = [.windowTitle] return t } */ public override func viewDidLoad() { if let service = ServiceRegistry.services.values.first { self.directory = service.directory } NotificationCenter.default.addObserver(forName: ServiceRegistry.didAddService, object: nil, queue: nil) { note in guard let c = note.object as? Service else { return } self.directory = c.directory } Analytics.view(screen: .directory) } public override func viewWillAppear() { PopWindowAnimator.show(self.view.window!) let frame = self.scrollView.layer!.frame self.scrollView.layer!.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.scrollView.layer!.position = CGPoint(x: frame.midX, y: frame.midY) self.scrollView.alphaValue = 0.0 self.indicator.startAnimation() self.visualSubscriptions = [ Settings.observe(\.effectiveInterfaceStyle, options: [.initial, .new]) { _, change in self.view.window?.crossfade() self.view.window?.appearance = InterfaceStyle.current.appearance() }, Settings.observe(\.vibrancyStyle, options: [.initial, .new]) { _, change in (self.view as? NSVisualEffectView)?.state = VibrancyStyle.current.state() }, ] } private var visualSubscriptions: [NSKeyValueObservation] = [] /// If we need to close, make sure we clean up after ourselves, instead of deinit. public override func viewWillDisappear() { self.visualSubscriptions = [] } public override func viewWillLayout() { super.viewWillLayout() let ctx = NSCollectionViewFlowLayoutInvalidationContext() ctx.invalidateFlowLayoutDelegateMetrics = true self.collectionView.collectionViewLayout?.invalidateLayout(with: ctx) } public override func cancelOperation(_ sender: Any?) { if let _ = self.presenting { self.dismiss(sender) } else { PopWindowAnimator.hide(self.view.window!) } } /// /// /// public func numberOfSections(in collectionView: NSCollectionView) -> Int { return 2 // selection, currentSource } public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return section == 0 ? self.selection.count : self.currentSource().count } public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let item = collectionView.makeItem(withIdentifier: .personCell, for: indexPath) item.representedObject = indexPath.section == 0 ? self.selection[indexPath.item] : self.currentSource()[indexPath.item] return item } public func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView { let header = collectionView.makeSupplementaryView(ofKind: .globalHeader, withIdentifier: .searchCell, for: indexPath) as! SearchCell header.searchHandler = { [weak self] in self?.searchQuery = $0 } return header } public func collectionView(_ collectionView: NSCollectionView, shouldSelectItemsAt indexPaths: Set<IndexPath>) -> Set<IndexPath> { let existingSMS = self.selection.first?.locations.contains("OffNetworkPhone") ?? false let ret = indexPaths.filter { $0.section != 0 } // can't select from the selection group return ret.filter { // can't mix'n'match SMS + Hangouts let newSMS = self.currentSource()[$0.item].locations.contains("OffNetworkPhone") return (existingSMS && newSMS) || (!existingSMS && !newSMS) // either both are SMS or both are NOT } } public func collectionView(_ collectionView: NSCollectionView, shouldDeselectItemsAt indexPaths: Set<IndexPath>) -> Set<IndexPath> { return indexPaths.filter { $0.section == 0 } // can't deselect from the currentSource group } public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) { self.editSelection { let indexPaths = indexPaths.filter { $0.section != 0 } // can't select from the selection group self.selection.append(contentsOf: (indexPaths.map { self.currentSource()[$0.item] })) //self.selection = indexPaths.map { self.currentSource()[$0.item] } self.updateStatus() } } public func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) { self.editSelection { let indexPaths = indexPaths.filter { $0.section == 0 }.map { $0.item }.reversed() // can't deselect from the currentSource group for idx in indexPaths { self.selection.remove(at: idx) } self.updateStatus() } } private func editSelection(_ handler: () -> ()) { // Cache the previous dataSource arrangement. let oldSelectionVal = self.selection.map { $0.identifier } let oldSourceVal = self.currentSource().map { $0.identifier } handler() // Create an update list from the new dataSource arrangement. let newSelectionVal = self.selection.map { $0.identifier } let newSourceVal = self.currentSource().map { $0.identifier } let selectionUpdates = Changeset.edits(from: oldSelectionVal, to: newSelectionVal) let sourceUpdates = Changeset.edits(from: oldSourceVal, to: newSourceVal) UI { self.collectionView.update(with: selectionUpdates, in: 0) {_ in} self.collectionView.update(with: sourceUpdates, in: 1) {_ in} // Since we can't do cross-section moves with Changeset, and selection is reset: let selectionSet = self.selection.enumerated().map { IndexPath(item: $0.offset, section: 0) } let sourceSet = self.currentSource().enumerated().map { IndexPath(item: $0.offset, section: 1) } self.collectionView.animator().reloadItems(at: Set(selectionSet + sourceSet)) self.collectionView.animator().selectionIndexPaths = Set(selectionSet) } } private func updateStatus() { if self.selection.count > 1 { let sms = self.selection.first?.locations.contains("OffNetworkPhone") ?? false self.statusText.stringValue = "New group \(sms ? "SMS " : "")conversation..." self.statusButton.title = "Create" } else if self.selection.count == 1 { let sms = self.selection.first?.locations.contains("OffNetworkPhone") ?? false self.statusText.stringValue = "New \(sms ? "SMS " : "")conversation..." self.statusButton.title = "Create" } else { self.statusText.stringValue = "Create..." self.statusButton.title = "Cancel" } } }
mpl-2.0
98788b8e16fbdf4a976a316aebd030d1
42.043228
186
0.624397
4.791787
false
false
false
false
Mioke/SwiftArchitectureWithPOP
SwiftyArchitecture/Base/Assistance/ConstValue&Function/Consts.swift
1
1794
// // Constants.swift // swiftArchitecture // // Created by jiangkelan on 28/06/2017. // Copyright © 2017 KleinMioke. All rights reserved. // import UIKit import SwiftUI public struct Consts { public static let defaultDomain = "com.mioke.swiftyarchitecture.default" public static let networkingDomain = "com.mioke.swiftyarchitecture.networking" } extension Consts { public static let kitName = "MIOSwiftyArchitecture" } internal func todo_error() -> NSError { return NSError(domain: "", code: 777, userInfo: nil) } public class KitErrors { public struct Info { let code: KitErrors.Codes let message: String? } static func error(domain: String, info: KitErrors.Info) -> NSError { return .init( domain: domain, code: info.code.rawValue, userInfo: [NSLocalizedDescriptionKey: info.message ?? ""] ) } } extension KitErrors { public enum Codes: Int { // general case noDelegate case unknown case todo = 777 // networking case responseError = 1000 case apiConstructionFailed // persistance // app docker // componentize case graphCycle = 4000 } } // Demo public extension KitErrors { static var todoInfo: Info { .init(code: .todo, message: "The author is too lazy to complete this.") } static let todo: NSError = error(domain: Consts.defaultDomain, info: KitErrors.todoInfo) static var unknownErrorInfo: Info { return .init(code: .unknown, message: "Unknown error") } static var unknown: NSError { return error(domain: Consts.networkingDomain, info: unknownErrorInfo) } }
mit
ae448c22c0d6655ed5344c6e8eb83603
21.696203
92
0.619074
4.373171
false
false
false
false
TotalDigital/People-iOS
People at Total/AppData.swift
1
22353
// // AppData // People at Total // // Created by Florian Letellier on 13/02/2017. // Copyright © 2017 Florian Letellier. All rights reserved. // import Foundation import SwiftyJSON class AppData { class var sharedInstance: AppData { struct Static { static let instance = AppData() } return Static.instance } var profiles: [Profile] = [] var projects: [Project] = [] var currentUser = Profile() { didSet { let userDefaults = UserDefaults.standard let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: currentUser) userDefaults.set(encodedData, forKey: "currentUser") userDefaults.synchronize() //print("saved object: \(userDefaults.object(forKey: "currentUser"))") if let data = userDefaults.object(forKey: "currentUser") { //let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) // print("myPeopleList: \(myPeopleList)") }else{ print("There is an issue") } //dump("currentUser : \(NSKeyedUnarchiver.unarchiveObject(with: encodedData))") } } var relation = Relation() { didSet { let userDefaults = UserDefaults.standard let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: relation) userDefaults.set(encodedData, forKey: "relation") userDefaults.synchronize() //print("saved object: \(userDefaults.object(forKey: "currentUser"))") if let data = userDefaults.object(forKey: "relation") { //let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) //print("myPeopleList: \(myPeopleList)") }else{ print("There is an issue") } //dump("currentUser : \(NSKeyedUnarchiver.unarchiveObject(with: encodedData))") } } var project = Project() { didSet { let userDefaults = UserDefaults.standard let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: project) userDefaults.set(encodedData, forKey: "project") userDefaults.synchronize() //print("saved object: \(userDefaults.object(forKey: "currentUser"))") if let data = userDefaults.object(forKey: "project") { //let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) //print("myPeopleList: \(myPeopleList)") }else{ print("There is an issue") } //dump("currentUser : \(NSKeyedUnarchiver.unarchiveObject(with: encodedData))") } } /*func getProjects() -> [Project] { let param: NSDictionary = [:] let url = "projects" APIUtility.sharedInstance.getAPICall(url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() if (error == nil) { let json = JSON(response) for i in 0..<json.count { var project = Project() project.id = json[i]["id"].intValue project.title = json[i]["name"].stringValue project.location = json[i]["project"].stringValue self.projects.append(project) } } } return self.projects } func getProfiles() -> [Profile]{ let param: NSDictionary = [:] let url = "users" APIUtility.sharedInstance.getAPICall(url: url, parameters: param) { (response, error) in //SVProgressHUD.dismiss() if (error == nil) { //let status : Int = response?.value(forKey: "status") as! Int let json = JSON(response) print(json) var users: [User] for i in 0..<json.count { //Do something you want var projects: [Project] = [] var jobs: [Job] = [] var user = User() if let first_name = json[i]["first_name"].stringValue as? String, let last_name = json[i]["last_name"].stringValue as? String { user.first_name = first_name user.last_name = last_name } if let job = json[i]["job_title"].stringValue as? String { user.job = "\(job)" } if let location = json[i]["office_address"].stringValue as? String { user.location = "\(location)" } if let image = json[i]["profile_picture_url"].stringValue as? String { user.image = image } if let entity = json[i]["entity"].stringValue as? String { user.entities = "\(entity)" } var skill = Skill() for j in 0..<json[i]["skills"].count { print("skill : \(json[i]["skills"][j]["name"].stringValue)") if let s = json[i]["skills"][j]["name"].stringValue as? String { skill.skills.append(s) print(s) } } var language = Language() for j in 0..<json[i]["languages"].count { if let l = json[i]["languages"][j].stringValue as? String { language.langues.append(json[i]["languages"][j].stringValue) } } var relations = Relation() for j in 0..<json[i]["relationships"].count { if let relation = (json[i]["relationships"][j].dictionaryValue) as? Dictionary{ let id = relation["id"]?.int switch ((relation["kind"]?.stringValue)!) { case "is_manager_of": print("kind : \((relation["kind"]?.stringValue)!)") relations.managers.append(Int(id!)) case "is_managed_by": relations.teamMember.append(id!) case "is_colleague_of": relations.colleagues.append(id!) case "is_assistant_of": relations.assistant.append(id!) default: break } } } for j in 0..<json[i]["project_participations"].count { var project = Project() if let proj = (json[i]["project_participations"][j].dictionaryValue) as? Dictionary { //project.title = proj["name"]?.stringValue //project.location = proj["location"]?.stringValue project.id = proj["id"]?.intValue project.start_date = proj["start_date"]?.stringValue project.end_date = proj["end_date"]?.stringValue project.description = proj["role_description"]?.stringValue projects.append(project) } } for j in 0..<json[i]["jobs"].count { var job = Job() if let j = (json[i]["job"][j].dictionaryValue) as? Dictionary { job.title = j["title"]?.stringValue job.location = j["location"]?.stringValue job.id = j["id"]?.intValue job.start_date = j["start_date"]?.stringValue jobs.append(job) } } var contact = Contact() if let email = json[i]["email"].stringValue as? String { contact.email = email } if let phone = json[i]["phone"].stringValue as? String { contact.phone_number = json[i]["phone"].stringValue } if let linkedin = json[i]["linkedin"].stringValue as? String { contact.linkedin_profile = linkedin } if let wat = json[i]["wat_link"].stringValue as? String { contact.wat_profile = wat } if let twitter = json[i]["twitter"].stringValue as? String { contact.twitter_profile = twitter } if let agil = json[i]["agil"].stringValue as? String { contact.agil_profile = agil } if let skype = json[i]["skype"].stringValue as? String { contact.skipe = skype } let profile = Profile() profile.user = user profile.jobs = jobs profile.contact = contact profile.projects = projects profile.langues = language profile.skills = skill profile.relations = relations if let id = json[i]["id"].intValue as? Int { profile.id = id } //dump(profile) self.profiles.append(profile) //defaults.set(self.profiles, forKey: "profiles") } } else { } } return self.profiles }*/ func generateRelations() -> [String:[Int]] { var relations = self.profiles[0].relations var relationsArray: [String: [Int]] = [:] if relations.managers.count > 0 { relationsArray["Managers"] = relations.managers } if relations.assistant.count > 0 { relationsArray["Assistant"] = relations.assistant } if relations.teamMember.count > 0 { relationsArray["Team Members"] = relations.teamMember } if relations.colleagues.count > 0 { relationsArray["Colleagues"] = relations.colleagues } return relationsArray } /* func generateProfiles () -> [Profile] { let user1 = User() let user2 = User() let user3 = User() let user4 = User() let user5 = User() user1.name = "Gregori Fabre" user1.job = "Digital Advisor" user1.location = "Coupole, 12E41" user1.image = "gregori" user1.entities = "EP/SCR/TF-DIGITAL" user2.name = "Virginie fromaget" user2.job = "Performance and Innovation Manager" user2.location = "Michelet 1735" user2.image = "virginie" user2.entities = "MS/RH/GC" user3.name = "Yves Le Stunff" user3.job = "Digital Officer Subsurface" user3.location = "Paris" user3.image = "yves" user3.entities = "EP/SCR/TF-DIGITAL" user4.name = "Gilles Cochevelou" user4.job = "CDO" user4.location = "Michelet A1215" user4.image = "gilles" user4.entities = "STI/CDO" user5.name = "Pierre de Milly" user5.job = "Schoolab consultant" user5.location = "Paris" user5.image = "pierre" user5.entities = "EP/SCR/TF-DIGITAL" var users = [user1, user2, user3, user4, user5] // Job greg var jobs: [Job] = [] let job1 = Job() job1.title = "Digital advisor E&P" job1.company = "Total" job1.date = "From May 2016" job1.description = "Advisor for digital initiatives in subsurface" job1.location = "Tour Coupole, Paris" // Job fromaget let job2 = Job() job2.title = "Exploration Geoscientist" job2.date = "September 2014 - May 2016" job2.description = "Deep & ultra deep offshore exploration Haute Mer geophysics MTPS geology & geophysics Nkossa geology & geophysics Publications : AAPG ICE 2013 speaker : A Lobe Story Through Spectral Decomposition AAPG ICE 2013 poster presenter : Illumination Using RTM and Kirchhoff Depth Processing to Enlighten the Geoscientists in Subsalt Domain" job2.location = "Tour Coupole, Paris" let job3 = Job() job3.title = "Performance and Innovation Manager" job3.date = "From September 2016" job3.description = "Innovation and Performance project manager for Career Managers Team in MS Branch" job3.location = "Michelet 1735" let job4 = Job() job4.title = "Gestionnaire de Carrières" job4.date = "From July 2012 to August 2016" job4.description = "En charge de la population OETAM de Michelet + stations d'aviation + dépôts pétroliers en France" let job5 = Job() job5.title = "Responsable du Service Clients GR" job5.date = "From October 2008 to June 2011" job5.location = "Spazio" job5.description = "Responsable du service clients GR + responsable Qualité + en charge du suivi des fraudes et pertes/profits" let job6 = Job() job6.title = "Chef de Secteur Cartes GR" job6.date = "From October 2005 to September 2008" job6.location = "Lyon" job6.description = "En charge du développement commercial des cartes GR sur le département du Rhône" // job yves let job7 = Job() job7.title = "Subsurface Digital Officer (EP/SCR)" job7.date = "From September 2015 (current)" job7.location = "Paris" job7.description = "Responsible of Digital Transformation of Subsurface domain(Geosciences + Drilling) Coordination of E&P Digital Transformation" let job8 = Job() job8.title = "Research and Development Strategy and Prospective Senior Manager (EP/SCR/RD)" job8.date = "From September 2012 to September 2015" job8.location = "Paris" job8.description = "In charge of defining E&P R&D strategy. Responsible of Prospective Labs (Nanotechnology, Robotics, Biotechnology, Numerical Methods, Image Processing)" let job9 = Job() job9.title = "Architect (APP)" job9.date = "From September 2009 to September 2012" job9.location = "Paris" job9.description = "In charge of development studies for APC area (Indonesia, Malysia, Vietnam,..)" // job gilles let job10 = Job() job10.title = "CDO" job10.date = "From September 2015" job10.location = "Paris (Michelet)" job10.description = "In charge of the Group digital transformation" let job11 = Job() job11.title = "VP Learning, Education, University" job11.date = "From January 2010 to September 2015" job11.location = "Paris" job11.description = "In charge of learning & development for the Group" let job12 = Job() job12.title = "VP R&D Gas & Power" job12.date = "From October 2007 to December 2009" job12.location = "Paris" job12.description = "In charge of R&D for solar energy, biotechnologies, energy storage, CO2 capture and transformation" let job13 = Job() job13.title = "VP Renewables" job13.date = "From September 2003 to September 2007" job13.location = "Paris" job13.description = "In charge of solar business and wind projects" // job pierre let job14 = Job() job14.title = "TOI Project Manager" job14.date = "From April 2016" job14.location = "21 rue de Clery, Paris" job14.description = "Leading the team working on the TOI aka JustOne project. We worked for 3 months inside the Schoolab incubator, designing and prototyping." var projects: [Project] = [] let project1 = Project() project1.title = "Just One Total" project1.date = "From May 2016" project1.location = "Paris, France" project1.description = "Sponsor for Just One Project" project1.members = [user2, user3] let project2 = Project() project2.title = "Benchmark visio conferencing tools" project2.date = "February 2015 - July 2015" project2.description = "In-house interpretation plateform" project2.location = "CSTJF, Pau" project2.members = [user1, user3] let project3 = Project() project3.title = "ATLAS" project3.date = "From March 2010 to June 2012" project3.location = "Spazio" project3.members = [user5, user4] let project4 = Project() project4.title = "People" project4.date = "From July 2016" project4.description = "Building the JustOne PLatform prototype" project4.members = [user1, user3, user4] let relations1: Relation = Relation() relations1.managers = [user3, user4] relations1.colleagues = [user2, user3] relations1.assistant = [user5, user2] relations1.teamMember = [user5, user4] let relations2: Relation = Relation() relations2.managers = [] relations2.colleagues = [user1] relations2.assistant = [user4] relations2.teamMember = [user5] let relations3: Relation = Relation() relations3.managers = [user4] relations3.colleagues = [] relations3.assistant = [] relations3.teamMember = [user1] let relations4: Relation = Relation() relations4.managers = [] relations4.colleagues = [] relations4.assistant = [user3] relations4.teamMember = [] let relations5: Relation = Relation() relations5.managers = [user1] relations5.colleagues = [] relations5.assistant = [] relations5.teamMember = [] var skill1: Skill = Skill() skill1.skills = ["digital", "structural", "geology", "geophysics", "innovation","braii"] var skill2: Skill = Skill() skill2.skills = ["digital", "marketing", "hr", "sales"] var skill3: Skill = Skill() skill3.skills = ["digital", "geophysics", "exploration", "geosciences", "seismic imaging", "r&d", "petroleum engineering"] var skill4: Skill = Skill() skill4.skills = ["digital", "innovation", "renewable energy", "solar energy", "wind energy", "power plant"] var skill5: Skill = Skill() skill5.skills = ["ruby on rails", "html", "css", "web development", "web design", "digital"] let langue1: Language = Language() langue1.langues = ["French", "English", "German"] let langue2: Language = Language() langue2.langues = ["French", "English"] let langue3: Language = Language() langue3.langues = ["French", "English", "Spanish"] let contact1: Contact = Contact() contact1.email = "[email protected]" contact1.phone_number = "+33 6 13 71 41 79" contact1.linkedin_profile = "https://fr.linkedin.com/in/fletelli" contact1.agil_profile = "agil/gregori" contact1.twitter_profile = "https://twitter.com/fletelli" contact1.wat_profile = "wat/gregori" contact1.skipe = "skype/gregori" let profile1 = Profile() profile1.user = user1 profile1.jobs = [job1, job2] profile1.projects = [project1, project2] profile1.relations = relations1 profile1.skills = skill1 profile1.langues = langue1 profile1.contact = contact1 let profile2 = Profile() profile2.user = user2 profile2.jobs = [job3, job4] profile2.projects = [project3] profile2.relations = relations2 profile2.skills = skill2 profile2.langues = langue2 profile2.contact = contact1 let profile3 = Profile() profile3.jobs = [job7, job8, job9] profile3.user = user3 profile3.projects = [project3, project4] profile3.relations = relations3 profile3.skills = skill3 profile3.langues = langue3 profile3.contact = contact1 let profile4 = Profile() profile4.jobs = [job10, job11, job12, job13] profile4.user = user4 profile4.projects = [project1, project2] profile4.relations = relations4 profile4.skills = skill4 profile4.langues = langue1 profile4.contact = contact1 let profile5 = Profile() profile5.user = user5 profile5.jobs = [job14] profile5.projects = [project4, project1] profile5.relations = relations5 profile5.skills = skill5 profile5.langues = langue2 profile5.contact = contact1 var profiles = [profile1, profile2, profile3, profile4, profile5] return profiles }*/ }
apache-2.0
9099a02c0f4c084e12ace6b73e2c33ed
39.699454
362
0.517544
4.65597
false
false
false
false
nguyenantinhbk77/practice-swift
Games/SwiftTetris/SwiftTetris/Shape.swift
3
5658
import SpriteKit /// Number of orientations let NumOrientations: UInt32 = 4 enum Orientation:Int, Printable{ case Zero = 0, Ninety, OneEighty, TwoSeventy /// Required fromt the printable interface var description: String { switch self { case .Zero: return "0" case .Ninety: return "90" case .OneEighty: return "180" case .TwoSeventy: return "270" } } /// Random orientation static func random() -> Orientation { return Orientation(rawValue:Int(arc4random_uniform(NumOrientations)))! } static func rotate(orientation:Orientation, clockwise: Bool) -> Orientation { var rotated = orientation.rawValue + (clockwise ? 1 : -1) if rotated > Orientation.TwoSeventy.rawValue { rotated = Orientation.Zero.rawValue } else if rotated < 0 { rotated = Orientation.TwoSeventy.rawValue } return Orientation(rawValue:rotated)! } } // The number of total shape varieties let NumShapeTypes: UInt32 = 7 // Shape indexes let FirstBlockIdx: Int = 0 let SecondBlockIdx: Int = 1 let ThirdBlockIdx: Int = 2 let FourthBlockIdx: Int = 3 class Shape:Hashable, Printable{ // The color of the shape let color:BlockColor // The blocks comprising the shape var blocks = Array<Block>() // The current orientation of the shape var orientation: Orientation // The column and row representing the shape's anchor point var column, row:Int // Required Overrides // Subclasses must override this property var blockRowColumnPositions: [Orientation: Array<(columnDiff: Int, rowDiff: Int)>] { return [:] } // Subclasses must override this property var bottomBlocksForOrientations: [Orientation: Array<Block>] { return [:] } var bottomBlocks:Array<Block> { if let bottomBlocks = bottomBlocksForOrientations[orientation] { return bottomBlocks } return [] } // Hashable var hashValue:Int { return reduce(blocks, 0) { $0.hashValue ^ $1.hashValue } } // Printable var description:String { return "\(color) block facing \(orientation): \(blocks[FirstBlockIdx]), \(blocks[SecondBlockIdx]), \(blocks[ThirdBlockIdx]), \(blocks[FourthBlockIdx])" } final func initializeBlocks() { if let blockRowColumnTranslations = blockRowColumnPositions[orientation] { for i in 0..<blockRowColumnTranslations.count { let blockRow = row + blockRowColumnTranslations[i].rowDiff let blockColumn = column + blockRowColumnTranslations[i].columnDiff let newBlock = Block(column: blockColumn, row: blockRow, color: color) blocks.append(newBlock) } } } init(column:Int, row:Int, color: BlockColor, orientation:Orientation) { self.color = color self.column = column self.row = row self.orientation = orientation initializeBlocks() } convenience init(column:Int, row:Int) { self.init(column:column, row:row, color:BlockColor.random(), orientation:Orientation.random()) } final func rotateBlocks(orientation: Orientation) { if let blockRowColumnTranslation:Array<(columnDiff: Int, rowDiff: Int)> = blockRowColumnPositions[orientation] { for (idx, (columnDiff:Int, rowDiff:Int)) in enumerate(blockRowColumnTranslation) { blocks[idx].column = column + columnDiff blocks[idx].row = row + rowDiff } } } final func lowerShapeByOneRow() { shiftBy(0, rows:1) } final func shiftBy(columns: Int, rows: Int) { self.column += columns self.row += rows for block in blocks { block.column += columns block.row += rows } } final func moveTo(column: Int, row:Int) { self.column = column self.row = row rotateBlocks(orientation) } final class func random(startingColumn:Int, startingRow:Int) -> Shape { switch Int(arc4random_uniform(NumShapeTypes)) { case 0: return SquareShape(column:startingColumn, row:startingRow) case 1: return LineShape(column:startingColumn, row:startingRow) case 2: return TShape(column:startingColumn, row:startingRow) case 3: return LShape(column:startingColumn, row:startingRow) case 4: return JShape(column:startingColumn, row:startingRow) case 5: return SShape(column:startingColumn, row:startingRow) default: return ZShape(column:startingColumn, row:startingRow) } } final func rotateClockwise() { let newOrientation = Orientation.rotate(orientation, clockwise: true) rotateBlocks(newOrientation) orientation = newOrientation } final func rotateCounterClockwise() { let newOrientation = Orientation.rotate(orientation, clockwise: false) rotateBlocks(newOrientation) orientation = newOrientation } final func raiseShapeByOneRow() { shiftBy(0, rows:-1) } final func shiftRightByOneColumn() { shiftBy(1, rows:0) } final func shiftLeftByOneColumn() { shiftBy(-1, rows:0) } } func ==(lhs: Shape, rhs: Shape) -> Bool { return lhs.row == rhs.row && lhs.column == rhs.column }
mit
e698c6cbccceaf2721f493b6f70b67e2
28.46875
159
0.611877
4.794915
false
false
false
false
hadashiA/RippleLayer
Sources/Ripple.swift
1
3607
import UIKit public final class Ripple { public enum Edge { case Top case Bottom } struct Spring { var height: CGFloat = 0 var velocity: CGFloat = 0 mutating func update(density: CGFloat, rippleSpeed: CGFloat) { // let k: CGFloat = 0.025 // let acceleration = -k * (targetHeight - self.height) // self.height += self.velocity // self.velocity += acceleration self.velocity += (-rippleSpeed * self.height - density * self.velocity) self.height += self.velocity } } public var size: CGSize public var density: CGFloat = 0.02 public var rippleSpeed: CGFloat = 0.1 public var numNeighbours = 8 public var animateEdge = Edge.Top var springs: [Spring] public init(size: CGSize, numSprings: Int = 340) { self.size = size self.springs = [Spring](count: numSprings, repeatedValue: Spring()) } public func rippleAt(i: Int, height: CGFloat) { if i < 0 || i > self.springs.count - 1 { return } self.springs[i].height = height } public func updateSprings(spread: CGFloat) { let count = self.springs.count for i in 0..<count { self.springs[i].update(self.density, rippleSpeed: self.rippleSpeed) // self.springs[i].update(self.size.height, rippleSpeed: self.rippleSpeed) } var leftDeltas = [CGFloat](count: self.springs.count, repeatedValue: 0) var rightDeltas = [CGFloat](count: self.springs.count, repeatedValue: 0) for t in 0..<self.numNeighbours { for i in 0..<count { if i > 0 { leftDeltas[i] = spread * (self.springs[i].height - self.springs[i - 1].height) self.springs[i - 1].velocity += leftDeltas[i] } if i < self.springs.count - 1 { rightDeltas[i] = spread * (self.springs[i].height - self.springs[i + 1].height) self.springs[i + 1].velocity += rightDeltas[i] } } for i in 0..<count { if i > 0 { self.springs[i - 1].height += leftDeltas[i] } if i < count - 1 { self.springs[i + 1].height += rightDeltas[i] } } } } public func createPath() -> CGPath { let path = UIBezierPath() switch self.animateEdge { case .Top: path.moveToPoint(CGPoint(x: 0, y: self.size.height)) for i in 0..<self.springs.count { let spring = self.springs[i] let x = CGFloat(i) * (self.size.width / CGFloat(self.springs.count)) let y = spring.height path.addLineToPoint(CGPoint(x: x, y: y)) } path.addLineToPoint(CGPoint(x: self.size.width, y: self.size.height)) case .Bottom: path.moveToPoint(CGPoint(x: 0, y: 0)) for i in 0..<self.springs.count { let spring = self.springs[i] let x = CGFloat(i) * (self.size.width / CGFloat(self.springs.count)) let y = self.size.height + spring.height path.addLineToPoint(CGPoint(x: x, y: y)) } path.addLineToPoint(CGPoint(x: self.size.width, y: 0)) } path.closePath() return path.CGPath } }
mit
6c94c653647544c2ac55d1b183bd5557
33.352381
99
0.509287
4.122286
false
false
false
false
vnu/YelpMe
YelpMe/BusinessTableViewCell.swift
1
1379
// // BusinessTableViewswift // YelpMe // // Created by Vinu Charanya on 2/10/16. // Copyright © 2016 Vnu. All rights reserved. // import UIKit class BusinessTableViewCell: UITableViewCell { @IBOutlet weak var businessImageView: UIImageView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! @IBOutlet weak var reviewCountLabel: UILabel! @IBOutlet weak var ratingsImageView: UIImageView! @IBOutlet weak var businessNameLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! var business: Business!{ didSet{ businessNameLabel.text = business.name! reviewCountLabel.text = "\(business.reviewCount!)" categoriesLabel.text = business.categories! addressLabel.text = business.location?.neighborhoods ratingsImageView.image = UIImage(named: "stars-\(business.rating!)") distanceLabel.text = business.distance! if let businessImage = business.imageUrl{ businessImageView.setImageWithURL(NSURL(string: businessImage)!) } } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
apache-2.0
2a136b0beb1ac1731b45acd11ab0a602
28.956522
80
0.646589
5.010909
false
false
false
false
ontouchstart/swift3-playground
Swift Standard Library.playground/Sources/RecipeApp.swift
1
5859
import UIKit public struct Ingredient: Equatable { public let name: String public let quantity: Int public let price: Int public let purchased: Bool public init(name: String, quantity: Int, price: Int, purchased: Bool) { self.name = name self.quantity = quantity self.price = price self.purchased = purchased } public var dictionaryRepresentation: [String: AnyObject] { get { return [ "name": name as NSString, "quantity": quantity as NSNumber, "price": price as NSNumber, "purchased": purchased as NSNumber ] } } } public func == (lhs: Ingredient, rhs: Ingredient) -> Bool { return lhs.name == rhs.name && lhs.price == rhs.price && lhs.purchased == rhs.purchased } public let sampleIngredients: [Ingredient] = [ Ingredient(name: "Tomato", quantity: 1, price: 2, purchased: false), Ingredient(name: "Saffron", quantity: 1, price: 6, purchased: false), Ingredient(name: "Chicken", quantity: 2, price: 3, purchased: true), Ingredient(name: "Rice", quantity: 1, price: 2, purchased: false), Ingredient(name: "Onion", quantity: 2, price: 1, purchased: true), Ingredient(name: "Garlic", quantity: 4, price: 1, purchased: false), Ingredient(name: "Pepper", quantity: 2, price: 3, purchased: false), Ingredient(name: "Salt", quantity: 1, price: 1, purchased: false) ] func needToBuy(_ ingredient: Ingredient) -> Bool { return !ingredient.purchased } public let shoppingList = sampleIngredients.filter(needToBuy) @available(iOS 9.0, *) class MapCell: UITableViewCell { let leftTextLabel = UILabel() let middleTextLabel = UILabel() let rightTextLabel = UILabel() let stack = UIStackView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) middleTextLabel.text = "→" middleTextLabel.textAlignment = .center middleTextLabel.font = UIFont.boldSystemFont(ofSize: 20) rightTextLabel.textAlignment = .right stack.distribution = UIStackViewDistribution.fillEqually stack.frame = self.contentView.bounds stack.addArrangedSubview(leftTextLabel) stack.addArrangedSubview(middleTextLabel) stack.addArrangedSubview(rightTextLabel) self.contentView.addSubview(stack) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() stack.frame = self.contentView.bounds } } private let IngredientCellIdentifier = "IngredientCellIdentifier" private class IngredientsListViewController: UITableViewController { var ingredients: [Ingredient] var filteredList: [Ingredient]? var transformed: [Int]? init(list: [Ingredient]) { ingredients = list super.init(style: .plain) self.view.frame = CGRect(x: 0, y: 0, width: 300, height: list.count * 44) self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: IngredientCellIdentifier) self.tableView.register(MapCell.self, forCellReuseIdentifier: "MapCell") self.tableView.separatorStyle = .singleLine self.tableView.separatorColor = .blue } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ingredients.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = transformed == nil ? IngredientCellIdentifier : "MapCell" let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) let ingredient = ingredients[indexPath.row] if let transforms = transformed { let mapCell = cell as! MapCell mapCell.leftTextLabel.text = "\(ingredient.quantity)x " + ingredient.name let transformedValue = transforms[indexPath.row] mapCell.rightTextLabel.text = "$\(transformedValue)" } else { cell.textLabel!.text = "\(ingredient.quantity)x " + ingredient.name cell.accessoryType = ingredient.purchased ? UITableViewCellAccessoryType.checkmark : UITableViewCellAccessoryType.none if filteredList != nil { cell.tintColor = UIColor.white } let keep = filteredList?.contains(ingredient) ?? true cell.textLabel!.textColor = keep ? UIColor.black : UIColor.white cell.backgroundColor = keep ? UIColor.white : UIColor(red: CGFloat(126/255.0), green: 72/255.0, blue: 229/255.0, alpha: 1.0) } return cell } } public func showIngredients(_ list: [Ingredient]) -> UIView { return IngredientsListViewController(list: list).view } public func visualize(_ list: [Ingredient], _ filteredList: [Ingredient]) -> UIView { let controller = IngredientsListViewController(list: list) controller.filteredList = filteredList return controller.view } public func visualize(_ list: [Ingredient], _ transformed: [Int]) -> UIView { let controller = IngredientsListViewController(list: list) controller.transformed = transformed return controller.view } public func visualize(_ list: [Ingredient], _ highlighted: Int?) -> UIView { if let highlighted = highlighted { let filteredList = list.prefix(upTo: highlighted) + list.suffix(from: highlighted + 1) return visualize(list, Array(filteredList)) } return showIngredients(list) }
mit
21c7e0aaecdbf0eefab63173bb62c2ef
36.787097
136
0.66365
4.674381
false
false
false
false
iSapozhnik/SILoadingControllerDemo
LoadingControllerDemo/LoadingControllerDemo/LoadingController/Views/LoadingViews/MulticolorLoadingView.swift
1
1372
// // MulticolorLoadingView.swift // LoadingControllerDemo // // Created by Sapozhnik Ivan on 28.06.16. // Copyright © 2016 Sapozhnik Ivan. All rights reserved. // import UIKit class MulticolorLoadingView: LoadingView, Animatable { var activity = MulticolorActivityView() override init(frame: CGRect) { super.init(frame: frame) defaultInitializer() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) defaultInitializer() } private func defaultInitializer() { let size = defaultActivitySize activity.frame = CGRectMake(0, 0, size.width, size.height) activity.colorArray = rainbowColors() addSubview(activity) } override func layoutSubviews() { super.layoutSubviews() activity.center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)) } func startAnimating() { let delay = 0.0 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { self.activity.startAnimating() }) } func stopAnimating() { activity.stopAnimating() } private func rainbowColors() -> [UIColor] { var colors = [UIColor]() let inc = 0.05 for var hue = 0.0; hue < 1.0; hue += inc { let color = UIColor(hue: CGFloat(hue), saturation: 1.0, brightness: 1.0, alpha: 1.0) colors.append(color) } return colors } }
mit
90c44c72a374cf384e7078ef59c0f9ed
20.761905
87
0.695842
3.376847
false
false
false
false
benlangmuir/swift
test/type/opaque_generic_superclass_constraint.swift
27
456
// RUN: %target-swift-frontend -disable-availability-checking -emit-ir -verify %s // rdar://problem/53318811 class Foo<T> { var x: T { fatalError() } } func foo<T>(_: T) -> some Foo<T> { let localProp: some Foo<T> = Foo() return localProp } class C<T> { func bar() -> some Foo<T> { return Foo() } var prop: some Foo<T> = Foo() } func bar() -> Int { var x = 0 x = foo(0).x x = C<Int>().bar().x x = C<Int>().prop.x return x }
apache-2.0
033f046077a18defcadfcdc0207298a6
15.285714
81
0.561404
2.635838
false
false
false
false
mshhmzh/firefox-ios
ClientTests/AuthenticatorTests.swift
6
7802
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import XCTest import Shared import Deferred @testable import Client @testable import Storage class MockFiles: FileAccessor { init() { let docPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] super.init(rootPath: (docPath as NSString).stringByAppendingPathComponent("testing")) } } class MockChallengeSender: NSObject, NSURLAuthenticationChallengeSender { func useCredential(credential: NSURLCredential, forAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {} func continueWithoutCredentialForAuthenticationChallenge(challenge: NSURLAuthenticationChallenge) {} func cancelAuthenticationChallenge(challenge: NSURLAuthenticationChallenge) {} } class MockMalformableLogin: LoginData { var guid: String var credentials: NSURLCredential var protectionSpace: NSURLProtectionSpace var hostname: String var username: String? var password: String var httpRealm: String? var formSubmitURL: String? var usernameField: String? var passwordField: String? var hasMalformedHostname = true var isValid = Maybe(success: ()) static func createWithHostname(hostname: String, username: String, password: String, formSubmitURL: String) -> MockMalformableLogin { return self.init(guid: Bytes.generateGUID(), hostname: hostname, username: username, password: password, formSubmitURL: formSubmitURL) } required init(guid: String, hostname: String, username: String, password: String, formSubmitURL: String) { self.guid = guid self.credentials = NSURLCredential(user: username, password: password, persistence: NSURLCredentialPersistence.None) self.hostname = hostname self.password = password self.username = username self.protectionSpace = NSURLProtectionSpace(host: hostname, port: 0, protocol: nil, realm: nil, authenticationMethod: nil) self.formSubmitURL = formSubmitURL } func toDict() -> [String: String] { // Not used for this mock return [String: String]() } func isSignificantlyDifferentFrom(login: LoginData) -> Bool { // Not used for this mock return true } } private let MainLoginColumns = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField" class AuthenticatorTests: XCTestCase { private var db: BrowserDB! private var logins: SQLiteLogins! private var mockVC = UIViewController() override func setUp() { super.setUp() self.db = BrowserDB(filename: "testsqlitelogins.db", files: MockFiles()) self.logins = SQLiteLogins(db: self.db) self.logins.removeAll().value } override func tearDown() { self.logins.removeAll().value } private func mockChallengeForURL(url: NSURL, username: String, password: String) -> NSURLAuthenticationChallenge { let scheme = url.scheme let host = url.host ?? "" let port = url.port?.integerValue ?? 80 let credential = NSURLCredential(user: username, password: password, persistence: .None) let protectionSpace = NSURLProtectionSpace(host: host, port: port, protocol: scheme, realm: "Secure Site", authenticationMethod: nil) return NSURLAuthenticationChallenge(protectionSpace: protectionSpace, proposedCredential: credential, previousFailureCount: 0, failureResponse: nil, error: nil, sender: MockChallengeSender()) } private func hostnameFactory(row: SDRow) -> String { return row["hostname"] as! String } private func rawQueryForAllLogins() -> Deferred<Maybe<Cursor<String>>> { let projection = MainLoginColumns let sql = "SELECT \(projection) FROM " + "\(TableLoginsLocal) WHERE is_deleted = 0 " + "UNION ALL " + "SELECT \(projection) FROM " + "\(TableLoginsMirror) WHERE is_overridden = 0 " + "ORDER BY hostname ASC" return db.runQuery(sql, args: nil, factory: hostnameFactory) } func testChallengeMatchesLoginEntry() { let login = Login.createWithHostname("https://securesite.com", username: "username", password: "password", formSubmitURL: "https://submit.me") logins.addLogin(login).value let challenge = mockChallengeForURL(NSURL(string: "https://securesite.com")!, username: "username", password: "password") let result = Authenticator.findMatchingCredentialsForChallenge(challenge, fromLoginsProvider: logins).value.successValue! XCTAssertNotNil(result) XCTAssertEqual(result?.user, "username") XCTAssertEqual(result?.password, "password") } func testChallengeMatchesSingleMalformedLoginEntry() { // Since Login has been updated to not store schemeless URL, write directly to simulate a malformed URL let malformedLogin = MockMalformableLogin.createWithHostname("malformed.com", username: "username", password: "password", formSubmitURL: "https://submit.me") logins.addLogin(malformedLogin).value // Pre-condition: Check that the hostname is malformed let oldHostname = rawQueryForAllLogins().value.successValue![0] XCTAssertEqual(oldHostname, "malformed.com") let challenge = mockChallengeForURL(NSURL(string: "https://malformed.com")!, username: "username", password: "password") let result = Authenticator.findMatchingCredentialsForChallenge(challenge, fromLoginsProvider: logins).value.successValue! XCTAssertNotNil(result) XCTAssertEqual(result?.user, "username") XCTAssertEqual(result?.password, "password") // Post-condition: Check that we updated the hostname to be not malformed let newHostname = rawQueryForAllLogins().value.successValue![0] XCTAssertEqual(newHostname, "https://malformed.com") } func testChallengeMatchesDuplicateLoginEntries() { // Since Login has been updated to not store schemeless URL, write directly to simulate a malformed URL let malformedLogin = MockMalformableLogin.createWithHostname("malformed.com", username: "malformed_username", password: "malformed_password", formSubmitURL: "https://submit.me") logins.addLogin(malformedLogin).value let login = Login.createWithHostname("https://malformed.com", username: "good_username", password: "good_password", formSubmitURL: "https://submit.me") logins.addLogin(login).value // Pre-condition: Verify that both logins were stored let hostnames = rawQueryForAllLogins().value.successValue! XCTAssertEqual(hostnames.count, 2) XCTAssertEqual(hostnames[0], "https://malformed.com") XCTAssertEqual(hostnames[1], "malformed.com") let challenge = mockChallengeForURL(NSURL(string: "https://malformed.com")!, username: "username", password: "password") let result = Authenticator.findMatchingCredentialsForChallenge(challenge, fromLoginsProvider: logins).value.successValue! XCTAssertNotNil(result) XCTAssertEqual(result?.user, "good_username") XCTAssertEqual(result?.password, "good_password") // Post-condition: Verify that malformed URL was removed let newHostnames = rawQueryForAllLogins().value.successValue! XCTAssertEqual(newHostnames.count, 1) XCTAssertEqual(newHostnames[0], "https://malformed.com") } }
mpl-2.0
f25a2ec30e5d5357219866e9ad6300a1
44.098266
185
0.702384
4.950508
false
true
false
false
bakarico/MyFirstiOSApp
MyFirstiOSApp/ViewController.swift
1
2732
// // ViewController.swift // MyFirstiOSApp // // Created by Rico on 15/2/21. // Copyright (c) 2015年 Rico. All rights reserved. // import Foundation import UIKit import Alamofire class ViewController: UIViewController { @IBOutlet weak var helloWorldLabel: UILabel! @IBOutlet weak var clickMeButton: UIButton! @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var copyrightLable: UILabel! var backgroundImageFlag = false override func viewDidLoad() { super.viewDidLoad() self.helloWorldLabel.text = "Are you hungry?" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func clickMeButtonTapped(sender: UIButton) { // Playground - noun: a place where people can play self.helloWorldLabel.text = "loading ..." // learn Alamofire Alamofire .request(.GET, "https://bakarico.github.io") .responseString { (request, response, data, error) in if error != nil { println(error) } else { let alert = UIAlertView() var error: NSError? let regex = NSRegularExpression(pattern: ".*<small>(.*?)</small>.*", options: .DotMatchesLineSeparators, error: &error) let response = NSString(string: data!) let range = NSRange(location: 0, length: response.length) let result = regex?.stringByReplacingMatchesInString(response, options: nil, range: range, withTemplate: "$1") if result != nil { alert.message = String(result!) } else { alert.message = "Failed to get moto" } alert.title = "HTML Response" alert.addButtonWithTitle("OK") alert.show() self.helloWorldLabel.text = String(result!) } } self.helloWorldLabel.backgroundColor = UIColor(white: 1, alpha: 0.8) self.copyrightLable.backgroundColor = UIColor(white: 1, alpha: 0.8) if !self.backgroundImageFlag { self.backgroundImageView.image = UIImage(named: "girl1") self.backgroundImageFlag = true } else { self.backgroundImageView.image = UIImage(named: "girl2") self.backgroundImageFlag = false } } }
mit
268f04094e33ea163d322b0cd888b461
31.891566
96
0.539194
5.290698
false
false
false
false
slavapestov/swift
stdlib/public/core/EmptyCollection.swift
2
2435
//===--- EmptyCollection.swift - A collection with no elements ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Sometimes an operation is best expressed in terms of some other, // larger operation where one of the parameters is an empty // collection. For example, we can erase elements from an Array by // replacing a subrange with the empty collection. // //===----------------------------------------------------------------------===// /// A generator that never produces an element. /// /// - SeeAlso: `EmptyCollection<Element>`. public struct EmptyGenerator<Element> : GeneratorType, SequenceType { @available(*, unavailable, renamed="Element") public typealias T = Element /// Construct an instance. public init() {} /// Return `nil`, indicating that there are no more elements. public mutating func next() -> Element? { return nil } } /// A collection whose element type is `Element` but that is always empty. public struct EmptyCollection<Element> : CollectionType { @available(*, unavailable, renamed="Element") public typealias T = Element /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = Int /// Construct an instance. public init() {} /// Always zero, just like `endIndex`. public var startIndex: Index { return 0 } /// Always zero, just like `startIndex`. public var endIndex: Index { return 0 } /// Returns an empty *generator*. /// /// - Complexity: O(1). public func generate() -> EmptyGenerator<Element> { return EmptyGenerator() } /// Access the element at `position`. /// /// Should never be called, since this collection is always empty. public subscript(position: Index) -> Element { _preconditionFailure("Index out of range") } /// Return the number of elements (always zero). public var count: Int { return 0 } }
apache-2.0
b21ba66b7123dd9984d8b855f1d1dc9f
29.822785
80
0.64271
4.691715
false
false
false
false
slavapestov/swift
stdlib/public/core/AssertCommon.swift
1
7604
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Implementation Note: this file intentionally uses very LOW-LEVEL // CONSTRUCTS, so that assert and fatal may be used liberally in // building library abstractions without fear of infinite recursion. // // FIXME: We could go farther with this simplification, e.g. avoiding // UnsafeMutablePointer @_transparent @warn_unused_result public // @testable func _isDebugAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 0 } @_transparent @warn_unused_result internal func _isReleaseAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 1 } @_transparent @warn_unused_result public // @testable func _isFastAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 2 } @_transparent @warn_unused_result public // @testable func _isStdlibInternalChecksEnabled() -> Bool { #if INTERNAL_CHECKS_ENABLED return true #else return false #endif } @_transparent @warn_unused_result internal func _fatalErrorFlags() -> UInt32 { // The current flags are: // (1 << 0): Report backtrace on fatal error #if os(iOS) || os(tvOS) || os(watchOS) return 0 #else return _isDebugAssertConfiguration() ? 1 : 0 #endif } @_silgen_name("_swift_stdlib_reportFatalErrorInFile") func _reportFatalErrorInFile( prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportFatalError") func _reportFatalError( prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportUnimplementedInitializerInFile") func _reportUnimplementedInitializerInFile( className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, _ column: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportUnimplementedInitializer") func _reportUnimplementedInitializer( className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, flags: UInt32) /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt, flags: UInt32 ) { prefix.withUTF8Buffer { (prefix) -> Void in message.withUTF8Buffer { (message) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), file.baseAddress, UInt(file.count), line, flags: flags) Builtin.int_trap() } } } Builtin.int_trap() } /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( prefix: StaticString, _ message: String, _ file: StaticString, _ line: UInt, flags: UInt32 ) { prefix.withUTF8Buffer { (prefix) -> Void in let messageUTF8 = message.nulTerminatedUTF8 messageUTF8.withUnsafeBufferPointer { (messageUTF8) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), messageUTF8.baseAddress, UInt(messageUTF8.count), file.baseAddress, UInt(file.count), line, flags: flags) } } } Builtin.int_trap() } /// This function should be used only in the implementation of stdlib /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") @_semantics("arc.programtermination_point") func _fatalErrorMessage( prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt, flags: UInt32 ) { #if INTERNAL_CHECKS_ENABLED prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in file.withUTF8Buffer { (file) in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), file.baseAddress, UInt(file.count), line, flags: flags) } } } #else prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in _reportFatalError( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), flags: flags) } } #endif Builtin.int_trap() } /// Prints a fatal error message when an unimplemented initializer gets /// called by the Objective-C runtime. @_transparent @noreturn public // COMPILER_INTRINSIC func _unimplemented_initializer(className: StaticString, initName: StaticString = #function, file: StaticString = #file, line: UInt = #line, column: UInt = #column) { // This function is marked @_transparent so that it is inlined into the caller // (the initializer stub), and, depending on the build configuration, // redundant parameter values (#file etc.) are eliminated, and don't leak // information about the user's source. if _isDebugAssertConfiguration() { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in file.withUTF8Buffer { (file) in _reportUnimplementedInitializerInFile( className.baseAddress, UInt(className.count), initName.baseAddress, UInt(initName.count), file.baseAddress, UInt(file.count), line, column, flags: 0) } } } } else { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in _reportUnimplementedInitializer( className.baseAddress, UInt(className.count), initName.baseAddress, UInt(initName.count), flags: 0) } } } Builtin.int_trap() } @noreturn public // COMPILER_INTRINSIC func _undefined<T>( @autoclosure message: () -> String = String(), file: StaticString = #file, line: UInt = #line ) -> T { _assertionFailed("fatal error", message(), file, line, flags: 0) }
apache-2.0
fb4ac4e555f5dce842848ce28898a74a
28.1341
80
0.657943
4.243304
false
false
false
false
maxsokolov/TableKit
Sources/TablePrototypeCellHeightCalculator.swift
3
3225
// // Copyright (c) 2015 Max Sokolov https://twitter.com/max_sokolov // // 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 open class TablePrototypeCellHeightCalculator: RowHeightCalculator { private(set) weak var tableView: UITableView? private var prototypes = [String: UITableViewCell]() private var cachedHeights = [Int: CGFloat]() private var separatorHeight = 1 / UIScreen.main.scale public init(tableView: UITableView?) { self.tableView = tableView } open func height(forRow row: Row, at indexPath: IndexPath) -> CGFloat { guard let tableView = tableView else { return 0 } let hash = row.hashValue ^ Int(tableView.bounds.size.width).hashValue if let height = cachedHeights[hash] { return height } var prototypeCell = prototypes[row.reuseIdentifier] if prototypeCell == nil { prototypeCell = tableView.dequeueReusableCell(withIdentifier: row.reuseIdentifier) prototypes[row.reuseIdentifier] = prototypeCell } guard let cell = prototypeCell else { return 0 } cell.prepareForReuse() row.configure(cell) cell.bounds = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: cell.bounds.height) cell.setNeedsLayout() cell.layoutIfNeeded() let height = cell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height + (tableView.separatorStyle != .none ? separatorHeight : 0) cachedHeights[hash] = height return height } open func estimatedHeight(forRow row: Row, at indexPath: IndexPath) -> CGFloat { guard let tableView = tableView else { return 0 } let hash = row.hashValue ^ Int(tableView.bounds.size.width).hashValue if let height = cachedHeights[hash] { return height } if let estimatedHeight = row.estimatedHeight , estimatedHeight > 0 { return estimatedHeight } return UITableView.automaticDimension } open func invalidate() { cachedHeights.removeAll() } }
mit
041637266b7742728a619532f3c9af61
36.068966
164
0.682481
4.901216
false
false
false
false
mozilla/swift-json
json/main.swift
1
3921
// // main.swift // json // // Created by Dan Kogai on 7/15/14. // Copyright (c) 2014 Dan Kogai. All rights reserved. // import Foundation //for convenience infix operator => { associativity left precedence 95 } func => <A,R> (lhs:A, rhs:A->R)->R { return rhs(lhs) } //let the show begin! let obj:[String:AnyObject] = [ "array": [JSON.null, false, 0, "", [], [:]], "object":[ "null": JSON.null, "bool": true, "int": 42, "int64": NSNumber(longLong: 2305843009213693951), // for 32-bit environment "double": 3.141592653589793, "string": "a α\t弾\nð", "array": [], "object": [:] ], "url":"http://blog.livedoor.com/dankogai/" ] // let json = JSON(obj) let jstr = json.toString() jstr => println JSON(string:jstr).toString() == JSON.parse(jstr).toString() => println json.toString(pretty: true) => println json["object"] => println json["object"]["array"] => println json["object"]["array"][0] => println json["object"]["object"][""] => println json["array"] => println let object = json["object"] object["null"].isNull => println object["null"].asNull => println object["bool"].isBool => println object["bool"].asBool => println object["int"].isInt => println object["int"].asInt => println object["int"].asInt32 => println object["int64"].isInt => println object["int64"].asInt => println // clashes in 32-bit environment //object["int64"].asInt32 => println // clashes object["int64"].asInt64 => println object["double"].isDouble => println object["double"].asDouble => println object["double"].asFloat => println object["string"].asString => println json["array"].isArray => println json["array"].asArray => println json["array"].length => println json["object"].isDictionary => println json["object"].asDictionary => println json["object"].length => println for (k, v) in json["array"] { "[\"array\"][\(k)] =>\t\(v)" => println } for (k, v) in json["object"] { "[\"object\"][\"\(k)\"] =>\t\(v)" => println } for (k, v) in json["url"] { "!!!! not supposed to see this!" => println } json["wrong_key"][Int.max]["wrong_name"] => println /// error handling if let b = json["noexistent"][1234567890]["entry"].asBool { println(b); } else { let e = json["noexistent"][1234567890]["entry"].asError println(e) } //// schema by subclassing class MyJSON : JSON { override init(_ obj:AnyObject){ super.init(obj) } override init(_ json:JSON) { super.init(json) } var null :NSNull? { return self["null"].asNull } var bool :Bool? { return self["bool"].asBool } var int :Int? { return self["int"].asInt } var double:Double? { return self["double"].asDouble } var string:String? { return self["string"].asString } var url: String? { return self["url"].asString } var array :MyJSON { return MyJSON(self["array"]) } var object:MyJSON { return MyJSON(self["object"]) } } let myjson = MyJSON(obj) myjson.toString() == jstr => println myjson.object => println myjson.object.array => println myjson.array => println myjson.object.null => println myjson.object.bool => println myjson.object.int => println myjson.object.double => println myjson.object.string => println myjson.url => println //// var url = "http://api.dan.co.jp/asin/4534045220.json" JSON(url:url).toString(pretty:true) => println url = "http://api.dan.co.jp/nonexistent" JSON(url:url).toString(pretty:true) => println /// https://github.com/dankogai/swift-json/issues/18 let jinj = JSON(JSON(["json in JSON", JSON(["json in JSON":JSON(true)])])) jinj.toString() => println
mit
a27df40aa0a5ead3823e9af6fe421938
34.288288
84
0.584376
3.472518
false
false
false
false
seanwoodward/IBAnimatable
IBAnimatable/SystemCubeAnimator.swift
1
2201
// // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit /** System Cube Animator - To support 3D animation (Four rotation directions supported: left, right, top, bottom) */ public class SystemCubeAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private private var fromDirection: TransitionDirection public init(fromDirection: TransitionDirection, transitionDuration: Duration) { self.fromDirection = fromDirection self.transitionDuration = transitionDuration switch fromDirection { case .Right: self.transitionAnimationType = .SystemCube(fromDirection: .Right) self.reverseAnimationType = .SystemCube(fromDirection: .Left) self.interactiveGestureType = .Pan(fromDirection: .Left) case .Top: self.transitionAnimationType = .SystemCube(fromDirection: .Top) self.reverseAnimationType = .SystemCube(fromDirection: .Bottom) self.interactiveGestureType = .Pan(fromDirection: .Bottom) case .Bottom: self.transitionAnimationType = .SystemCube(fromDirection: .Bottom) self.reverseAnimationType = .SystemCube(fromDirection: .Top) self.interactiveGestureType = .Pan(fromDirection: .Top) default: self.transitionAnimationType = .SystemCube(fromDirection: .Left) self.reverseAnimationType = .SystemCube(fromDirection: .Right) self.interactiveGestureType = .Pan(fromDirection: .Right) } super.init() } } extension SystemCubeAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return retrieveTransitionDuration(transitionContext) } public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { animateWithCATransition(transitionContext, type: SystemTransitionType.Cube, subtype: fromDirection.CATransitionSubtype) } }
mit
34c6069859175dcd3a50b1ce1d7b059b
39
123
0.770455
5.104408
false
false
false
false
kaizeiyimi/XLYAnimatedImage
XLYAnimatedImage/codes/XLYAnimatedImage.swift
1
7669
// // XLYAnimatedImage.swift // XLYAnimatedImage // // Created by kaizei on 16/1/12. // Copyright © 2016年 kaizei. All rights reserved. // import UIKit import ImageIO import MobileCoreServices private let kMinDurationPerFrame: TimeInterval = 0.01, kDefaultDurationPerFrame: TimeInterval = 0.1 // MARK: - image public protocol AnimatedImage: class { var scale: CGFloat { get } var frameCount: Int { get } var totalTime: TimeInterval { get } var durations: [TimeInterval] { get } var firtImage: UIImage { get } func image(at index: Int) -> UIImage? } extension AnimatedImage { public var frameCount: Int { return durations.count } } // MARK: - mainly for GIF. /** ios device bug, count for apng will always be 1 bug simulator is ok. Now only support GIF, other will has only the first frame. (will try other way to decode apng) */ open class AnimatedDataImage: AnimatedImage { public let scale: CGFloat public let totalTime: TimeInterval public let durations: [TimeInterval] public let firtImage: UIImage private let source: CGImageSource? public init?(data:Data, scale: CGFloat = UIScreen.main.scale) { self.scale = scale source = CGImageSourceCreateWithData(data as CFData, nil) if let source = source, let gifDurations = try? getSourceDurations(source) { totalTime = gifDurations.reduce(0){ $0 + $1 } durations = gifDurations.map{ $0 } if let image = decodeCGImage(CGImageSourceCreateImageAtIndex(source, 0, nil)) { firtImage = UIImage(cgImage: image, scale: scale, orientation: .up) } else { firtImage = UIImage() } } else { totalTime = 0 durations = [0] if let image = UIImage(data: data, scale: scale) { firtImage = image } else { firtImage = UIImage() return nil } } } open func image(at index: Int) -> UIImage? { if let source = source, let image = decodeCGImage(CGImageSourceCreateImageAtIndex(source, index % frameCount, nil)) { return UIImage(cgImage: image, scale: scale, orientation: .up) } return nil } } // MARK: - imageArray open class AnimatedFrameImage: AnimatedImage { public let scale: CGFloat public let totalTime: TimeInterval public let durations: [TimeInterval] public var firtImage: UIImage { return images[0] } private var images: [UIImage] public convenience init?(animatedUIImage image: UIImage) { if let images = image.images , images.count > 0 { self.init(images: images, durations: [TimeInterval](repeating: image.duration, count: images.count)) } else { self.init(images: [image], durations: [image.duration]) } } public init?(images: [UIImage], durations: [TimeInterval]) { var durations = durations if images.count == 0 && durations.count == 0 { (self.scale, self.totalTime, self.durations, self.images) = (0, 0, [], []) return nil } else { if durations.count < images.count { durations.append(contentsOf: Array<TimeInterval>(repeating: kDefaultDurationPerFrame, count: images.count - durations.count)) } let validImages = zip(images, durations).map { (image: $0, duration: $1 < kMinDurationPerFrame ? kDefaultDurationPerFrame : $1) } self.images = validImages.map { $0.image } if validImages.count >= 2 { self.durations = validImages.map { $0.duration } self.totalTime = self.durations.reduce(0){ $0 + $1 } } else { self.durations = [0] self.totalTime = 0 } self.scale = self.images[0].scale } } open func image(at index: Int) -> UIImage? { let origin = images[index % frameCount] if let decoded = decodeCGImage(origin.cgImage) { return UIImage(cgImage: decoded, scale: scale, orientation: .up) } else { return origin } } } // MARK: - helper methods private struct InvalidAnimateDataError: Error { let description = "Data is not a valid animated image data or frame count not > 2." } /// stolen from SDWebImage's decoder. just change OC to swift. private func decodeCGImage(_ image: CGImage?) -> CGImage? { guard let image = image else { return nil } var result: CGImage? autoreleasepool { let width = image.width, height = image.height let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo = image.bitmapInfo.rawValue let infoMask = bitmapInfo & CGBitmapInfo.alphaInfoMask.rawValue let anyNonAlpha = (infoMask == CGImageAlphaInfo.none.rawValue || infoMask == CGImageAlphaInfo.noneSkipFirst.rawValue || infoMask == CGImageAlphaInfo.noneSkipLast.rawValue) if infoMask == CGImageAlphaInfo.none.rawValue && colorSpace.numberOfComponents > 1 { bitmapInfo &= ~CGBitmapInfo.alphaInfoMask.rawValue bitmapInfo |= CGImageAlphaInfo.noneSkipFirst.rawValue } else if !anyNonAlpha && colorSpace.numberOfComponents == 3 { bitmapInfo &= ~CGBitmapInfo.alphaInfoMask.rawValue bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue } let context = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: image.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo) context!.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) result = context!.makeImage() } return result } private func getSourceDurations(_ source: CGImageSource) throws -> [TimeInterval] { let count = CGImageSourceGetCount(source) guard let type = CGImageSourceGetType(source) , type == kUTTypeGIF && count > 1 else { throw InvalidAnimateDataError() } return (0..<count).map{ getGIFDelay(source: source, index: $0) } } private func getGIFDelay(source: CGImageSource, index: Int) -> TimeInterval { var delay: TimeInterval = kDefaultDurationPerFrame let propertiesDict = CGImageSourceCopyPropertiesAtIndex(source, index, nil) if (propertiesDict != nil) { let dictionaryPropertyKey = unsafeBitCast(kCGImagePropertyGIFDictionary, to: UnsafeRawPointer.self) let properties = CFDictionaryGetValue(propertiesDict, dictionaryPropertyKey) if (properties != nil) { let propertiesDict = unsafeBitCast(properties, to: CFDictionary.self) let unclampedDelayTimePropertyKey = unsafeBitCast(kCGImagePropertyGIFUnclampedDelayTime, to: UnsafeRawPointer.self) var number = CFDictionaryGetValue(propertiesDict, unclampedDelayTimePropertyKey) if number != nil && unsafeBitCast(number, to: NSNumber.self).doubleValue >= kMinDurationPerFrame { delay = unsafeBitCast(number, to: NSNumber.self).doubleValue } else if number == nil { let delayTimePropertyKey = unsafeBitCast(kCGImagePropertyGIFDelayTime, to: UnsafeRawPointer.self) number = CFDictionaryGetValue(propertiesDict, delayTimePropertyKey) if number != nil && unsafeBitCast(number, to: NSNumber.self).doubleValue >= kMinDurationPerFrame { delay = unsafeBitCast(number, to: NSNumber.self).doubleValue } } } } return delay }
mit
004646e677f3bcb8df33908bdd5c0d48
38.927083
185
0.639186
4.767413
false
false
false
false
Deliany/yaroslav_skorokhid_SimplePins
yaroslav_skorokhid_SimplePins/MoreViewController.swift
1
1799
// // MoreViewController.swift // yaroslav_skorokhid_SimplePins // // Created by Yaroslav Skorokhid on 10/15/16. // Copyright © 2016 CollateralBeauty. All rights reserved. // import UIKit class MoreViewController: UIViewController { @IBOutlet private weak var avatarImageView: UIImageView! @IBOutlet private weak var nameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.avatarImageView.image = nil self.nameLabel.text = nil self.updateUserDetailsUI() FacebookGraphAPI.getProfileDetails { (user, errorString) in if let user = user { SettingsService.currentUser = user self.updateUserDetailsUI() } } } func updateUserDetailsUI() { if let user = SettingsService.currentUser { self.nameLabel.text = user.name // load image in old-ish way without caching // just to not include SDWebImage if let avatarURL = user.avatarURL { NSURLSession.sharedSession().dataTaskWithURL(avatarURL, completionHandler: { (data, response, error) in if let data = data { let image = UIImage(data: data) dispatch_async(dispatch_get_main_queue(), { self.avatarImageView.image = image }) } }).resume() } } } @IBAction func logoutButtonPressed(sender: AnyObject) { SettingsService.removeSessionData() self.tabBarController?.dismissViewControllerAnimated(true, completion: nil) } }
mit
4ca0b88ac84a6d98d4f827ef4a26b853
30.54386
119
0.583982
5.272727
false
false
false
false
doronkatz/firefox-ios
SharedTests/UtilsTests.swift
2
3265
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCTest /** * Test for our own utils. */ class UtilsTests: XCTestCase { func testMapUtils() { let m: [String: Int] = ["foo": 123, "bar": 456] let f: (Int) -> Int? = { v in return (v > 200) ? 999 : nil } let o = mapValues(m, f: f) XCTAssertEqual(2, o.count) XCTAssertTrue(o["foo"]! == nil) XCTAssertTrue(o["bar"]! == 999) let filtered = optFilter(o) XCTAssertEqual(1, filtered.count) XCTAssertTrue(filtered["bar"] == 999) } func testOptFilter() { let a: [Int?] = [nil, 1, nil, 2, 3, 4] let b = optFilter(a) XCTAssertEqual(4, b.count) XCTAssertEqual([1, 2, 3, 4], b) } func testOptArrayEqual() { let x: [String] = ["a", "b", "c"] let y: [String]? = ["a", "b", "c"] let z: [String]? = nil XCTAssertTrue(optArrayEqual(x, rhs: y)) XCTAssertTrue(optArrayEqual(x, rhs: x)) XCTAssertTrue(optArrayEqual(y, rhs: y)) XCTAssertTrue(optArrayEqual(z, rhs: z)) XCTAssertFalse(optArrayEqual(x, rhs: z)) XCTAssertFalse(optArrayEqual(z, rhs: y)) } func testChunk() { let examples: [([Int], Int, [[Int]])] = [ ([], 2, []), ([1, 2], 0, [[1], [2]]), ([1, 2], 1, [[1], [2]]), ([1, 2, 3], 2, [[1, 2], [3]]), ([1, 2], 3, [[1, 2]]), ([1, 2, 3], 1, [[1], [2], [3]]), ] for (arr, by, expected) in examples { // Turn the ArraySlices back into Arrays for comparison. let actual = chunk(arr as [Int], by: by).map { Array($0) } XCTAssertEqual(expected as NSArray, actual as NSArray) //wtf. why is XCTAssert being so weeird } } func testParseTimestamps() { let millis = "1492316843992" // Firefox for iOS produced millisecond timestamps. Oops. let decimal = "1492316843.99" let truncated = "1492316843" let huge = "1844674407370955161512" XCTAssertNil(decimalSecondsStringToTimestamp("")) XCTAssertNil(decimalSecondsStringToTimestamp(huge)) XCTAssertNil(decimalSecondsStringToTimestamp("foo")) XCTAssertNil(someKindOfTimestampStringToTimestamp("")) XCTAssertNil(someKindOfTimestampStringToTimestamp(huge)) XCTAssertNil(someKindOfTimestampStringToTimestamp("foo")) XCTAssertEqual(decimalSecondsStringToTimestamp(decimal) ?? 0, Timestamp(1492316843990)) XCTAssertEqual(someKindOfTimestampStringToTimestamp(decimal) ?? 0, Timestamp(1492316843990)) XCTAssertEqual(decimalSecondsStringToTimestamp(truncated) ?? 0, Timestamp(1492316843000)) XCTAssertEqual(someKindOfTimestampStringToTimestamp(truncated) ?? 0, Timestamp(1492316843000)) XCTAssertEqual(decimalSecondsStringToTimestamp(millis) ?? 0, Timestamp(1492316843992000)) // Oops. XCTAssertEqual(someKindOfTimestampStringToTimestamp(millis) ?? 0, Timestamp(1492316843992)) } }
mpl-2.0
acd67e86b68d58ed0c6f615d3b8196ce
35.685393
107
0.599387
3.952785
false
true
false
false
JackLian/ReactiveCocoa
ReactiveCocoaTests/Swift/ActionSpec.swift
134
5295
// // ActionSpec.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-12-11. // Copyright (c) 2014 GitHub. All rights reserved. // import Result import Nimble import Quick import ReactiveCocoa class ActionSpec: QuickSpec { override func spec() { describe("Action") { var action: Action<Int, String, NSError>! var enabled: MutableProperty<Bool>! var executionCount = 0 var values: [String] = [] var errors: [NSError] = [] var scheduler: TestScheduler! let testError = NSError(domain: "ActionSpec", code: 1, userInfo: nil) beforeEach { executionCount = 0 values = [] errors = [] enabled = MutableProperty(false) scheduler = TestScheduler() action = Action(enabledIf: enabled) { number in return SignalProducer { observer, disposable in executionCount++ if number % 2 == 0 { sendNext(observer, "\(number)") sendNext(observer, "\(number)\(number)") scheduler.schedule { sendCompleted(observer) } } else { scheduler.schedule { sendError(observer, testError) } } } } action.values.observe(next: { values.append($0) }) action.errors.observe(next: { errors.append($0) }) } it("should be disabled and not executing after initialization") { expect(action.enabled.value).to(beFalsy()) expect(action.executing.value).to(beFalsy()) } it("should error if executed while disabled") { var receivedError: ActionError<NSError>? action.apply(0).start(error: { receivedError = $0 }) expect(receivedError).notTo(beNil()) if let error = receivedError { let expectedError = ActionError<NSError>.NotEnabled expect(error == expectedError).to(beTruthy()) } } it("should enable and disable based on the given property") { enabled.value = true expect(action.enabled.value).to(beTruthy()) expect(action.executing.value).to(beFalsy()) enabled.value = false expect(action.enabled.value).to(beFalsy()) expect(action.executing.value).to(beFalsy()) } describe("execution") { beforeEach { enabled.value = true } it("should execute successfully") { var receivedValue: String? action.apply(0).start(next: { receivedValue = $0 }) expect(executionCount).to(equal(1)) expect(action.executing.value).to(beTruthy()) expect(action.enabled.value).to(beFalsy()) expect(receivedValue).to(equal("00")) expect(values).to(equal([ "0", "00" ])) expect(errors).to(equal([])) scheduler.run() expect(action.executing.value).to(beFalsy()) expect(action.enabled.value).to(beTruthy()) expect(values).to(equal([ "0", "00" ])) expect(errors).to(equal([])) } it("should execute with an error") { var receivedError: ActionError<NSError>? action.apply(1).start(error: { receivedError = $0 }) expect(executionCount).to(equal(1)) expect(action.executing.value).to(beTruthy()) expect(action.enabled.value).to(beFalsy()) scheduler.run() expect(action.executing.value).to(beFalsy()) expect(action.enabled.value).to(beTruthy()) expect(receivedError).notTo(beNil()) if let error = receivedError { let expectedError = ActionError<NSError>.ProducerError(testError) expect(error == expectedError).to(beTruthy()) } expect(values).to(equal([])) expect(errors).to(equal([ testError ])) } } } describe("CocoaAction") { var action: Action<Int, Int, NoError>! beforeEach { action = Action { value in SignalProducer(value: value + 1) } expect(action.enabled.value).to(beTruthy()) expect(action.unsafeCocoaAction.enabled).toEventually(beTruthy()) } #if os(OSX) it("should be compatible with AppKit") { let control = NSControl(frame: NSZeroRect) control.target = action.unsafeCocoaAction control.action = CocoaAction.selector control.performClick(nil) } #elseif os(iOS) it("should be compatible with UIKit") { let control = UIControl(frame: CGRectZero) control.addTarget(action.unsafeCocoaAction, action: CocoaAction.selector, forControlEvents: UIControlEvents.TouchDown) control.sendActionsForControlEvents(UIControlEvents.TouchDown) } #endif it("should generate KVO notifications for enabled") { var values: [Bool] = [] action.unsafeCocoaAction .rac_valuesForKeyPath("enabled", observer: nil) .toSignalProducer() |> map { $0! as! Bool } |> start(Event.sink(next: { values.append($0) })) expect(values).to(equal([ true ])) let result = action.apply(0) |> first expect(result?.value).to(equal(1)) expect(values).toEventually(equal([ true, false, true ])) } it("should generate KVO notifications for executing") { var values: [Bool] = [] action.unsafeCocoaAction .rac_valuesForKeyPath("executing", observer: nil) .toSignalProducer() |> map { $0! as! Bool } |> start(Event.sink(next: { values.append($0) })) expect(values).to(equal([ false ])) let result = action.apply(0) |> first expect(result?.value).to(equal(1)) expect(values).toEventually(equal([ false, true, false ])) } } } }
mit
50deb42886c22201ef2d68125eae7560
25.742424
123
0.644759
3.689895
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/CoreText/ZSDisplayView.swift
1
20702
// // ZSDisplayView.swift // CoreTextDemo // // Created by caony on 2019/7/12. // Copyright © 2019 cj. All rights reserved. // import UIKit import Kingfisher class ZSDisplayView: UIView { // MARK: - Properties var ctFrame: CTFrame? var images: [(image: UIImage, frame: CGRect)] = [] var imageModels:[ZSImageData] = [] // MARK: - Properties var imageIndex: Int! var longPress:UILongPressGestureRecognizer! var originRange = NSRange(location: 0, length: 0) var selectedRange = NSRange(location: 0, length: 0) var attributeString:NSMutableAttributedString = NSMutableAttributedString(string: "") var rects:[CGRect] = [] var leftCursor:ZSTouchAnchorView! var rightCursor:ZSTouchAnchorView! // 移动光标 private var isTouchCursor = false private var touchRightCursor = false private var touchOriginRange = NSRange(location: 0, length: 0) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear isUserInteractionEnabled = true if longPress == nil { longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gesture:))) addGestureRecognizer(longPress) } let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(tap:))) addGestureRecognizer(tap) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func tapAction(tap:UITapGestureRecognizer) { originRange = NSRange(location: 0, length: 0) selectedRange = NSRange(location: 0, length: 0) rects.removeAll() hideCursor() setNeedsDisplay() } @objc private func longPressAction(gesture:UILongPressGestureRecognizer) { var originPoint = CGPoint.zero switch gesture.state { case .began: originPoint = gesture.location(in: self) originRange = touchLocation(point: originPoint, str: self.attributeString.string) selectedRange = originRange rects = rangeRects(range: selectedRange, ctframe: ctFrame) showCursor() setNeedsDisplay() break case .changed: let finalRange = touchLocation(point: gesture.location(in: self), str: attributeString.string) if finalRange.location == 0 || finalRange.location == NSNotFound { return } var range = NSRange(location: 0, length: 0) range.location = min(finalRange.location, originRange.location) if finalRange.location > originRange.location { range.length = finalRange.location - originRange.location + finalRange.length } else { range.length = originRange.location - finalRange.location + originRange.length } selectedRange = range rects = rangeRects(range: selectedRange, ctframe: ctFrame) showCursor() setNeedsDisplay() break case .ended: break case .cancelled: break default: break } } func showCursor() { guard rects.count > 0 else { return } let leftRect = rects.first! let rightRect = rects.last! if leftCursor == nil { let rect = CGRect(x: leftRect.minX - 2, y: bounds.height - leftRect.origin.y - rightRect.height - 6, width: 10, height: leftRect.height + 6) leftCursor = ZSTouchAnchorView(frame: rect) addSubview(leftCursor) } else { let rect = CGRect(x: leftRect.minX - 2, y: bounds.height - leftRect.origin.y - rightRect.height - 6, width: 10, height: leftRect.height + 6) leftCursor.frame = rect } if rightCursor == nil { let rect = CGRect(x: rightRect.maxX - 2, y: bounds.height - rightRect.origin.y - rightRect.height - 6, width: 10, height: rightRect.height + 6) rightCursor = ZSTouchAnchorView(frame: rect) addSubview(rightCursor) } else { rightCursor.frame = CGRect(x: rightRect.maxX - 4, y: bounds.height - rightRect.origin.y - rightRect.height - 6, width: 10, height: rightRect.height + 6) } } func hideCursor() { if leftCursor != nil { leftCursor.removeFromSuperview() leftCursor = nil } if rightCursor != nil { rightCursor.removeFromSuperview() rightCursor = nil } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let point = touches.first?.location(in: self) else { return } guard leftCursor != nil && rightCursor != nil else { return } if rightCursor.frame.insetBy(dx: -30, dy: -30).contains(point) { touchRightCursor = true isTouchCursor = true } else if leftCursor.frame.insetBy(dx: -30, dy: -30).contains(point) { touchRightCursor = false isTouchCursor = true } touchOriginRange = selectedRange } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let point = touches.first?.location(in: self) else { return } guard leftCursor != nil && rightCursor != nil else { return } if isTouchCursor { let finalRange = touchLocation(point: point, str: attributeString.string) if (finalRange.location == 0 && finalRange.length == 0) || finalRange.location == NSNotFound { return } var range = NSRange(location: 0, length: 0) if touchRightCursor { // 移动右边光标 if finalRange.location >= touchOriginRange.location { range.location = touchOriginRange.location range.length = finalRange.location - touchOriginRange.location + 1 } else { range.location = finalRange.location range.length = touchOriginRange.location - range.location } } else { // 移动左边光标 if finalRange.location <= touchOriginRange.location { range.location = finalRange.location range.length = touchOriginRange.location - finalRange.location + touchOriginRange.length } else if finalRange.location > touchOriginRange.location { if finalRange.location <= touchOriginRange.location + touchOriginRange.length - 1 { range.location = finalRange.location range.length = touchOriginRange.location + touchOriginRange.length - finalRange.location } else { range.location = touchOriginRange.location + touchOriginRange.length range.length = finalRange.location - range.location } } } selectedRange = range rects = rangeRects(range: selectedRange, ctframe: ctFrame) // 显示光标 showCursor() setNeedsDisplay() } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { isTouchCursor = false touchOriginRange = selectedRange } func rangeRects(range:NSRange, ctframe:CTFrame?) ->[CGRect] { var rects:[CGRect] = [] guard let ctframe = ctframe else { return rects } guard range.location != NSNotFound else { return rects } var lines = CTFrameGetLines(ctframe) as Array var origins = [CGPoint](repeating: CGPoint.zero, count: lines.count) CTFrameGetLineOrigins(ctframe, CFRange(location: 0, length: 0), &origins) for index in 0..<lines.count { let line = lines[index] as! CTLine let origin = origins[index] let lineCFRange = CTLineGetStringRange(line) if lineCFRange.location != NSNotFound { let lineRange = NSRange(location: lineCFRange.location, length: lineCFRange.length) if lineRange.location + lineRange.length > range.location && lineRange.location < (range.location + range.length) { var ascent: CGFloat = 0 var descent: CGFloat = 0 var startX: CGFloat = 0 var contentRange = NSRange(location: range.location, length: 0) let end = min(lineRange.location + lineRange.length, range.location + range.length) contentRange.length = end - contentRange.location CTLineGetTypographicBounds(line, &ascent, &descent, nil) let y = origin.y - descent startX = CTLineGetOffsetForStringIndex(line, contentRange.location, nil) let endX = CTLineGetOffsetForStringIndex(line, contentRange.location + contentRange.length, nil) let rect = CGRect(x: origin.x + startX, y: y, width: endX - startX, height: ascent + descent) rects.append(rect) } } } return rects } func touchLocation(point:CGPoint, str:String = "") ->NSRange { var touchRange = NSMakeRange(0, 0) guard let ctFrame = self.ctFrame else { return touchRange } var lines = CTFrameGetLines(ctFrame) as Array var origins = [CGPoint](repeating: CGPoint.zero, count: lines.count) CTFrameGetLineOrigins(ctFrame, CFRange(location: 0, length: 0), &origins) for index in 0..<lines.count { let line = lines[index] as! CTLine let origin = origins[index] var ascent: CGFloat = 0 var descent: CGFloat = 0 CTLineGetTypographicBounds(line, &ascent, &descent, nil) let lineRect = CGRect(x: origin.x, y: bounds.height - origin.y - (ascent + descent), width: CTLineGetOffsetForStringIndex(line, 100000, nil), height: ascent + descent) if lineRect.contains(point) { let lineRange = CTLineGetStringRange(line) for rangeIndex in 0..<lineRange.length { let location = lineRange.location + rangeIndex var offsetX = CTLineGetOffsetForStringIndex(line, location, nil) var offsetX2 = CTLineGetOffsetForStringIndex(line, location + 1, nil) offsetX += origin.x offsetX2 += origin.x let runs = CTLineGetGlyphRuns(line) as Array for runIndex in 0..<runs.count { let run = runs[runIndex] as! CTRun let runRange = CTRunGetStringRange(run) if runRange.location <= location && location <= (runRange.location + runRange.length - 1) { // 说明在当前的run中 var ascent: CGFloat = 0 var descent: CGFloat = 0 CTRunGetTypographicBounds(run, CFRange(location: 0, length: 0), &ascent, &descent, nil) let frame = CGRect(x: offsetX, y: bounds.height - origin.y - (ascent + descent), width: (offsetX2 - offsetX)*2, height: ascent + descent) if frame.contains(point) { touchRange = NSRange(location: location, length: min(2, lineRange.length + lineRange.location - location)) } } } } } } return touchRange } func buildContent(attr:NSAttributedString, andImages:[ZSImageData] , settings:CTSettings) { attributeString = NSMutableAttributedString(attributedString: attr) imageIndex = 0 let framesetter = CTFramesetterCreateWithAttributedString(attr as CFAttributedString) let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), nil, CGSize(width: settings.pageRect.size.width, height: CGFloat.greatestFiniteMagnitude), nil) let path = CGMutablePath() path.addRect(CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: settings.pageRect.width, height: textSize.height))) let ctframe = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) self.ctFrame = ctframe self.imageModels = andImages attachImages(andImages, ctframe: ctframe, margin: settings.margin) setNeedsDisplay() } func build(withAttrString attrString: NSAttributedString, andImages images: [[String: Any]]) { imageIndex = 0 //4 let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString) let settings = CTSettings.shared let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), nil, CGSize(width: settings.pageRect.size.width, height: CGFloat.greatestFiniteMagnitude), nil) self.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: textSize.height) if let parentView = self.superview as? UIScrollView { parentView.contentSize = CGSize(width: self.bounds.width, height: textSize.height) } let path = CGMutablePath() path.addRect(CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: settings.pageRect.width, height: textSize.height))) let ctframe = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) self.ctFrame = ctframe attachImagesWithFrame(images, ctframe: ctframe, margin: settings.margin) } func attachImages(_ images: [ZSImageData],ctframe: CTFrame,margin: CGFloat) { if images.count == 0 { return } let lines = CTFrameGetLines(ctframe) as NSArray var origins = [CGPoint](repeating: .zero, count: lines.count) CTFrameGetLineOrigins(ctframe, CFRangeMake(0, 0), &origins) var nextImage:ZSImageData? = imageModels[imageIndex] for lineIndex in 0..<lines.count { if nextImage == nil { break } let line = lines[lineIndex] as! CTLine if let glyphRuns = CTLineGetGlyphRuns(line) as? [CTRun] { for run in glyphRuns { let runAttr = CTRunGetAttributes(run) as? [NSAttributedString.Key:Any] let delegate = runAttr?[(kCTRunDelegateAttributeName as NSAttributedString.Key)] if delegate == nil { continue } var imgBounds: CGRect = .zero var ascent: CGFloat = 0 var descent: CGFloat = 0 imgBounds.size.width = CGFloat(CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, nil)) imgBounds.size.height = ascent + descent let xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil) imgBounds.origin.x = origins[lineIndex].x + xOffset imgBounds.origin.y = origins[lineIndex].y imgBounds.origin.y -= descent; let pathRef = CTFrameGetPath(ctframe) let colRect = pathRef.boundingBox let delegateBounds = imgBounds.offsetBy(dx: colRect.origin.x, dy: colRect.origin.y) nextImage!.imagePosition = delegateBounds imageModels[imageIndex].imagePosition = imgBounds imageIndex! += 1 if imageIndex < images.count { nextImage = images[imageIndex] } else { nextImage = nil } } } } } func attachImagesWithFrame(_ images: [[String: Any]], ctframe: CTFrame, margin: CGFloat) { //1 let lines = CTFrameGetLines(ctframe) as NSArray //2 var origins = [CGPoint](repeating: .zero, count: lines.count) CTFrameGetLineOrigins(ctframe, CFRangeMake(0, 0), &origins) //3 var nextImage = images[imageIndex] guard var imgLocation = nextImage["location"] as? Int else { return } //4 for lineIndex in 0..<lines.count { let line = lines[lineIndex] as! CTLine //5 if let glyphRuns = CTLineGetGlyphRuns(line) as? [CTRun], let imageFilename = nextImage["filename"] as? String, let img = UIImage(named: imageFilename) { for run in glyphRuns { // 1 let runRange = CTRunGetStringRange(run) if runRange.location > imgLocation || runRange.location + runRange.length <= imgLocation { continue } //2 var imgBounds: CGRect = .zero var ascent: CGFloat = 0 imgBounds.size.width = CGFloat(CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, nil, nil)) imgBounds.size.height = ascent //3 let xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil) imgBounds.origin.x = origins[lineIndex].x + xOffset imgBounds.origin.y = origins[lineIndex].y //4 self.images += [(image: img, frame: imgBounds)] //5 imageIndex! += 1 if imageIndex < images.count { nextImage = images[imageIndex] imgLocation = (nextImage["location"] as AnyObject).intValue } } } } } // MARK: - Life Cycle override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } context.textMatrix = .identity context.translateBy(x: 0, y: bounds.size.height) context.scaleBy(x: 1.0, y: -1.0) if rects.count > 0 { let lineRects = rects.map { rect -> CGRect in return CGRect(x: rect.origin.x + 2, y: rect.origin.y, width: rect.width, height: rect.height) } let fillPath = CGMutablePath() UIColor(red:0.92, green:0.5, blue:0.5, alpha:1.00).withAlphaComponent(0.5).setFill() fillPath.addRects(lineRects) context.addPath(fillPath) context.fillPath() } CTFrameDraw(ctFrame!, context) for imageData in images { if let image = imageData.image.cgImage { let imgBounds = imageData.frame context.draw(image, in: imgBounds) } } for imageModel in imageModels { if let image = imageModel.image { context.draw(image.cgImage!, in: imageModel.imagePosition) continue } if let url = URL(string: imageModel.parse?.url ?? "" ) { ImageDownloader.default.downloadImage(with: url, options: nil, progressBlock: nil) { [weak self] (result) in switch result { case .success(let value): print(value.image) self!.imageModels[self?.indexOfModel(model: imageModel, models: self!.imageModels) ?? 0].image = value.image self?.setNeedsDisplay() case .failure(let error): print(error) } } } } } func indexOfModel(model:ZSImageData, models:[ZSImageData]) ->Int { var index = 0 for data in models { if data.parse?.url == model.parse?.url { break } index += 1 } return index } }
mit
fc39ab6e04414dade81b1faa6dc97b61
42.285115
195
0.558047
4.944205
false
false
false
false
easyui/Alamofire
Example/Source/AppDelegate.swift
4
2592
// // AppDelegate.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { // MARK: - Properties var window: UIWindow? // MARK: - UIApplicationDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { let splitViewController = window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers.last as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self return true } // MARK: - UISplitViewControllerDelegate func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController, let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { return topAsDetailController.request == nil } return false } }
mit
b1fc43bf6801083840d4a01e180f1c23
42.932203
124
0.731096
5.76
false
false
false
false
wangchong321/tucao
WCWeiBo/WCWeiBo/Classes/Model/Home/ComposeViewController.swift
1
6360
// // ComposeViewController.swift // WCWeiBo // // Created by 王充 on 15/5/22. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class ComposeViewController: UIViewController ,UITextViewDelegate { // lazy var keyboadVC: EmoticonKeyboardViewController = { // // 闭包中会对 self 强引用 // weak var weakSelf = self // return EmoticonKeyboardViewController(selectedEmoticon: { (emoticon) -> () in // // 调用方法,同样会产生强引用,在 OC 中同样需要注意 // weakSelf?.textView.insertEmoticon(emoticon) // }) // }() /// 输入的textView文本框 private let maxTextViewLength = 10 @IBOutlet weak var textView: EmoticonsTextView! /// 模仿Placeholder 的labe @IBOutlet weak var textLabel: UILabel! /// 姓名 @IBOutlet weak var nameLabel: UILabel! /// 发送按钮 @IBOutlet weak var sendBtn: UIBarButtonItem! /// 返回按钮 @IBAction func dismsClick(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBOutlet weak var pictureCollectionViewHeight: NSLayoutConstraint! @IBOutlet weak var toolBarHeightConstrain: NSLayoutConstraint! /// 发送微博 @IBAction func sendClick(sender: AnyObject) { sendStatus() } /// 点击头像按钮 lazy var keyboadVC: EmoticonKeyboardViewController = { // 闭包中会对 self 强引用 weak var weakSelf = self //var vc = EmoticonKeyboardViewController() var vc = EmoticonKeyboardViewController(selectedEmoticon: { (emoticon) -> () in weakSelf?.textView.insertEmoticon(emoticon) }) return vc }() @IBAction func headImgClick() { println("点击了头像") // 查看之前的键盘,如果是 nil,表示当前键盘是系统键盘 println(textView.inputView) // 目前 textView 有键盘,首先先关闭键盘 textView.resignFirstResponder() // 设置输入视图键盘 textView.inputView = (textView.inputView == nil) ? keyboadVC.view : nil // 重新激活键盘 textView.becomeFirstResponder() } override func viewDidLoad() { super.viewDidLoad() pictureCollectionViewHeight.constant = 0 nameLabel.text = sharedUserAccount?.name setuoUI() registerNotification() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // 开始键盘 textView.becomeFirstResponder() } private func setuoUI(){ addChildViewController(keyboadVC) // 添加自控制器 // for vc in childViewControllers { // if vc is PictureSelectCollectionViewController { // self.addChildViewController(PictureSelectCollectionViewController()) // } // } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // 结束键盘 textView.resignFirstResponder() } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } // 注册通知 private func registerNotification(){ NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillHideNotification, object: nil) } func keyboardChanged(notification : NSNotification) { // 从 userInfo 字典中,取出键盘高度 // 字典中如果保存的是结构体,通常是以 NSValue 的形式保存的 var duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval // 如果监听的是键盘的frame改变事件,如果是则弹起键盘, 如果不是则放下键盘 var height : CGFloat = 0 if notification.name == UIKeyboardWillChangeFrameNotification { var rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() height = rect.height UIView.animateWithDuration(duration, animations: { () -> Void in self.toolBarHeightConstrain.constant = height self.view.layoutIfNeeded() }) }else { self.toolBarHeightConstrain.constant = height } } // 选中了图片按钮 @IBAction func seletcPicture() { // 点击图片按钮的时候键盘弹下, 图片控制器显示 pictureCollectionViewHeight.constant = UIScreen.mainScreen().bounds.height / 3 textView.resignFirstResponder() } // Mark - UIScrollView的代理方法 func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { textView.resignFirstResponder() } // 发送文字微博 private func sendStatus(){ var status = textView.text let urlString = "https://api.weibo.com/2/statuses/update.json" let parame = ["access_token" : sharedUserAccount?.access_token , "status" : status] NetWorkingTools.requestJSON(.POST, urlString, parame) { (JSON) -> () in self.dismissViewControllerAnimated(true, completion: nil) } } } extension ComposeViewController : UITextViewDelegate { func textViewDidChange(textView: UITextView) { // println("\(textView.text)") // textView.text如果是空的就不隐藏.否则隐藏 textLabel.hidden = self.textView.hasText() sendBtn.enabled = textView.hasText() var text = textView.text as NSString if text.length > maxTextViewLength{ textView.text = text.substringToIndex(maxTextViewLength) } } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{ println(text) // 调整最大的传送字节上限 if ((textView.text as NSString).length + (text as NSString).length) > 10 { return false } return true } }
mit
388d1c9094c8f8809c5efa06aa834e94
32.274286
150
0.630539
4.933898
false
false
false
false
josherick/DailySpend
DailySpend/ExpenseViewController.swift
1
2027
// // ExpenseViewController.swift // DailySpend // // Created by Josh Sherick on 7/22/17. // Copyright © 2017 Josh Sherick. All rights reserved. // import UIKit class ExpenseViewController: UIViewController, ExpenseViewDelegate { var expenseView: ExpenseView! var expense: Expense? var rightBBIStack = [UIBarButtonItem]() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.navigationItem.title = "Expense" expenseView = ExpenseView(frame: view.bounds) expenseView.delegate = self expenseView.dataSource = ExpenseProvider(expense: expense) expenseView.updateFieldValues() expenseView.updateSubviewFrames() view.addSubview(expenseView) } func didBeginEditing(sender: ExpenseView) { } func didEndEditing(sender: ExpenseView, expense: Expense?) { navigationController?.popViewController(animated: true) } func present(_ vc: UIViewController, animated: Bool, completion: (() -> Void)?, sender: Any?) { self.present(vc, animated: animated, completion: completion) } func pushRightBBI(_ bbi: UIBarButtonItem, sender: Any?) { rightBBIStack.append(bbi) self.navigationItem.rightBarButtonItem = rightBBIStack.last! } func popRightBBI(sender: Any?) { _ = rightBBIStack.popLast() if let bbi = rightBBIStack.last { self.navigationItem.rightBarButtonItem = bbi } } func pushLeftBBI(_ bbi: UIBarButtonItem, sender: Any?) { } func popLeftBBI(sender: Any?) { } func disableRightBBI(sender: Any?) { self.navigationItem.rightBarButtonItem?.isEnabled = false } func enableRightBBI(sender: Any?) { self.navigationItem.rightBarButtonItem?.isEnabled = true } func disableLeftBBI(sender: Any?) { } func enableLeftBBI(sender: Any?) { } }
mit
f7457d7dcd1d39c37538a5693102d131
26.013333
68
0.636723
4.625571
false
false
false
false
WestlakeAPC/game-off-2016
external/Fiber2D/Fiber2D/ActionRepeat.swift
1
4948
// // ActionRepeat.swift // Fiber2D // // Created by Andrey Volodin on 04.09.16. // Copyright © 2016 s1ddok. All rights reserved. // import SwiftMath /** * Repeats an action indefinitely (until stopped). * To repeat the action for a limited number of times use the ActionRepeat action. * * @note This action can not be used within a ActionSequence because it is not an FiniteTime action. * However you can use ActionRepeatForever to repeat a ActionSequence. */ public struct ActionRepeatForeverContainer: ActionContainer { public mutating func update(state: Float) { } public mutating func start(with target: AnyObject?) { self.target = target innerContainer.start(with: target) } mutating public func step(dt: Time) { innerContainer.step(dt: dt) if innerContainer.isDone { if let c = innerContainer as? Continous { let diff = c.elapsed - c.duration defer { // to prevent jerk. issue #390, 1247 innerContainer.step(dt: 0.0) innerContainer.step(dt: diff) } } innerContainer.start(with: target) } } public var tag: Int = 0 weak var target: AnyObject? = nil public var isDone: Bool { return false } private(set) var innerContainer: ActionContainer init(action: ActionContainer) { self.innerContainer = action if !(action is FiniteTime) { assertionFailure("ERROR: You can't repeat infinite action") } } } public struct ActionRepeatContainer: ActionContainer, FiniteTime { public mutating func update(state: Float) { // issue #80. Instead of hooking step:, hook update: since it can be called by any // container action like Repeat, Sequence, Ease, etc.. let dt = state if dt >= nextDt { while dt >= nextDt && remainingRepeats > 0 { innerContainer.update(state: 1.0) remainingRepeats -= 1 innerContainer.stop() innerContainer.start(with: target) self.nextDt = Float(Int(repeatCount - remainingRepeats) + 1) / Float(repeatCount) } // fix for issue #1288, incorrect end value of repeat if dt ~= 1.0 && remainingRepeats > 0 { innerContainer.update(state: 1.0) remainingRepeats -= 1 } guard icDuration > 0 else { return } if remainingRepeats == 0 { innerContainer.stop() } else { // issue #390 prevent jerk, use right update innerContainer.update(state: dt - (nextDt - 1.0 / Float(repeatCount))) } } else { guard icDuration > 0 else { return } let clampedState = (dt * Float(repeatCount)).truncatingRemainder(dividingBy: 1.0) innerContainer.update(state: clampedState) } } public mutating func start(with target: AnyObject?) { self.elapsed = 0 self.target = target self.remainingRepeats = repeatCount self.nextDt = 1.0 / Float(repeatCount) innerContainer.start(with: target) } mutating public func step(dt: Time) { guard icDuration > 0 else { innerContainer.start(with: target) innerContainer.update(state: 1.0) innerContainer.stop() remainingRepeats -= 1 return } elapsed += dt self.update(state: max(0, // needed for rewind. elapsed could be negative min(1, elapsed / max(duration, Float.ulpOfOne)) // division by 0 ) ) } public var tag: Int = 0 weak var target: AnyObject? = nil public var isDone: Bool { return remainingRepeats == 0 } public let repeatCount: UInt private var remainingRepeats: UInt = 0 private var nextDt: Float = 0.0 private let icDuration: Time public let duration: Time private var elapsed: Time = 0.0 private(set) var innerContainer: ActionContainerFiniteTime init(action: ActionContainerFiniteTime, repeatCount: UInt) { self.innerContainer = action self.repeatCount = repeatCount self.icDuration = action.duration self.duration = Float(repeatCount) * icDuration } } public extension ActionContainer where Self: FiniteTime { public func `repeat`(times: UInt) -> ActionRepeatContainer { return ActionRepeatContainer(action: self, repeatCount: times) } public var repeatForever: ActionRepeatForeverContainer { return ActionRepeatForeverContainer(action: self) } }
apache-2.0
d8f6f10e312a96e79c40a58432fd1bc6
30.916129
101
0.580352
4.619048
false
false
false
false
RomainBoulay/SectionSpacingFlowLayout
CollectionViewCompactLayout/ViewController.swift
1
7213
import UIKit class ViewController: UIViewController, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! let data = [["1.1", "1.2", "1.3"], ["2.1","2.2", "2.3", "2.4"], [], ["3.1","3.2"], ["4.1"]] // let data = [["1.1", "1.2", "1.3"], ["2.1","2.2", "2.3", "2.4"], ["3.1","3.2"], ["4.1"]] override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self spacingFlowLayout.decorationViewKind = "Spacing" let cellNib = UINib(nibName: "Cell", bundle: nil) let headerNib = UINib(nibName: "Header", bundle: nil) let footerNib = UINib(nibName: "Footer", bundle: nil) let decorationNib = UINib(nibName: "Spacing", bundle: nil) collectionView.register(cellNib, forCellWithReuseIdentifier: "Cell") collectionView.register(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header") collectionView.register(footerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer") collectionView.collectionViewLayout.register(decorationNib, forDecorationViewOfKind: "Spacing") } var spacingFlowLayout: SectionSpacingFlowLayout { return collectionView.collectionViewLayout as! SectionSpacingFlowLayout } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (_) in self.collectionView.collectionViewLayout.invalidateLayout() }) { (_) in } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() setupDefaults(collectionView.collectionViewLayout as! UICollectionViewFlowLayout) collectionView.reloadData() } func setupDefaults(_ collectionViewLayout: UICollectionViewFlowLayout) { collectionViewLayout.minimumLineSpacing = 1.0 / UIScreen.main.scale collectionViewLayout.sectionInset.top = 1.0 / UIScreen.main.scale collectionViewLayout.sectionInset.bottom = 1.0 / UIScreen.main.scale let width = itemWidth(collectionViewLayout) collectionViewLayout.headerReferenceSize = .init(width: width, height: 50) collectionViewLayout.footerReferenceSize = .init(width: width, height: 50) collectionViewLayout.itemSize = CGSize(width: width, height: 30) } func itemWidth(_ collectionViewLayout: UICollectionViewFlowLayout) -> CGFloat { guard let collectionView = collectionView else { return 0 } return collectionView.frame.width - collectionViewLayout.sectionInset.left - collectionViewLayout.sectionInset.right - collectionView.contentInset.left - collectionView.contentInset.right } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) collectionView.reloadData() } @IBAction func didTap(_ sender: Any) { spacingFlowLayout.spacingHeight = spacingFlowLayout.spacingHeight == 20 ? 100 : 20 } // MARK: - DataSource public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data[section].count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell cell.label.text = data[indexPath.section][indexPath.row] return cell } public func numberOfSections(in collectionView: UICollectionView) -> Int { return data.count } public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader: let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! Header return headerView case UICollectionElementKindSectionFooter: let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath) as! Footer return footerView default: assert(false, "Unexpected element kind") } } } extension ViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.width/2.0 - 5, height: 50) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { switch section { case 0: return .zero case 1: return UIEdgeInsets(top: 25, left: 5, bottom: 25, right: 5) case 2: return UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5) default: return .zero } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1.0 / UIScreen.main.scale } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 20 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { switch section { case 0: return CGSize(width: collectionView.frame.width, height: 10) case 1: return CGSize(width: collectionView.frame.width, height: 20) case 2: return CGSize(width: collectionView.frame.width, height: 30) case 3: return CGSize(width: collectionView.frame.width, height: 40) default: return CGSize(width: collectionView.frame.width, height: 10) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { switch section { case 0: return CGSize(width: collectionView.frame.width, height: 10) case 1: return CGSize(width: collectionView.frame.width, height: 20) case 2: return CGSize(width: collectionView.frame.width, height: 30) case 3: return CGSize(width: collectionView.frame.width, height: 40) default: return CGSize(width: collectionView.frame.width, height: 10) } } }
mit
d20bd34a49d67dec39ac7aaea3f278ef
47.409396
195
0.68127
5.595811
false
false
false
false
tardieu/swift
test/Constraints/closures.swift
1
18282
// RUN: %target-typecheck-verify-swift func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {} var intArray : [Int] _ = myMap(intArray, { String($0) }) _ = myMap(intArray, { x -> String in String(x) } ) // Closures with too few parameters. func foo(_ x: (Int, Int) -> Int) {} foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} struct X {} func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {} func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {} var strings : [String] _ = mySort(strings, { x, y in x < y }) // Closures with inout arguments. func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U { var t2 = t return f(&t2) } struct X2 { func g() -> Float { return 0 } } _ = f0(X2(), {$0.g()}) // Autoclosure func f1(f: @autoclosure () -> Int) { } func f2() -> Int { } f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}} f1(f: 5) // Ternary in closure var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"} // <rdar://problem/15367882> func foo() { not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}} } // <rdar://problem/15536725> struct X3<T> { init(_: (T) -> ()) {} } func testX3(_ x: Int) { var x = x _ = X3({ x = $0 }) _ = x } // <rdar://problem/13811882> func test13811882() { var _ : (Int) -> (Int, Int) = {($0, $0)} var x = 1 var _ : (Int) -> (Int, Int) = {($0, x)} x = 2 } // <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement // <https://bugs.swift.org/browse/SR-3671> func r21544303() { var inSubcall = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false // This is a problem, but isn't clear what was intended. var somethingElse = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false var v2 : Bool = false v2 = inSubcall { // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } } // <https://bugs.swift.org/browse/SR-3671> func SR3671() { let n = 42 func consume(_ x: Int) {} { consume($0) }(42) ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; // This is technically a valid call, so nothing goes wrong until (42) { $0(3) } { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; { $0(3) } { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; // Equivalent but more obviously unintended. { $0(3) } // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ({ $0(3) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ; // Also a valid call (!!) { $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}} consume(111) } // <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure func r22162441(_ lines: [String]) { _ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} _ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} } func testMap() { let a = 42 [1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier [].reduce { $0 + $1 } // expected-error {{missing argument for parameter #1 in call}} // <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments var _: () -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }} var _: (Int) -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}} var _: (Int) -> Int = { 0 } // expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }} var _: (Int, Int) -> Int = {0} // expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {$0+$1} var _: () -> Int = {a in 0} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}} var _: (Int) -> Int = {a,b in 0} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}} var _: (Int) -> Int = {a,b,c in 0} var _: (Int, Int) -> Int = {a in 0} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {a, b in a+b} // <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument func r15998821() { func take_closure(_ x : (inout Int) -> ()) { } func test1() { take_closure { (a : inout Int) in a = 42 } } func test2() { take_closure { a in a = 42 } } func withPtr(_ body: (inout Int) -> Int) {} func f() { withPtr { p in return p } } let g = { x in x = 3 } take_closure(g) } // <rdar://problem/22602657> better diagnostics for closures w/o "in" clause var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} // Crash when re-typechecking bodies of non-single expression closures struct CC {} func callCC<U>(_ f: (CC) -> U) -> () {} func typeCheckMultiStmtClosureCrash() { callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }} _ = $0 return 1 } } // SR-832 - both these should be ok func someFunc(_ foo: ((String) -> String)?, bar: @escaping (String) -> String) { let _: (String) -> String = foo != nil ? foo! : bar let _: (String) -> String = foo ?? bar } // SR-1069 - Error diagnostic refers to wrong argument class SR1069_W<T> { func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {} } class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() } struct S<T> { let cs: [SR1069_C<T>] = [] func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable { let wrappedMethod = { (object: AnyObject, value: T) in } // expected-error @+1 {{value of optional type 'Object?' not unwrapped; did you mean to use '!' or '?'?}} cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) } } } // Make sure we cannot infer an () argument from an empty parameter list. func acceptNothingToInt (_: () -> Int) {} func testAcceptNothingToInt(ac1: @autoclosure () -> Int) { // expected-note@-1{{parameter 'ac1' is implicitly non-escaping because it was declared @autoclosure}} acceptNothingToInt({ac1($0)}) // expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}} // FIXME: expected-error@-2{{closure use of non-escaping parameter 'ac1' may allow it to escape}} } // <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference) struct Thing { init?() {} } // This throws a compiler error let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> (Thing) }} // Commenting out this makes it compile _ = thing return thing } // <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches func r21675896(file : String) { let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }} if true { return "foo" } else { return file } }().pathExtension } // <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _") func ident<T>(_ t: T) -> T {} var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}} // <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block var afterMessageCount : Int? func uintFunc() -> UInt {} func takeVoidVoidFn(_ a : () -> ()) {} takeVoidVoidFn { () -> Void in afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}} } // <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure func f19997471(_ x: String) {} func f19997471(_ x: Int) {} func someGeneric19997471<T>(_ x: T) { takeVoidVoidFn { f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}} // expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}} } } // <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information func f20371273() { let x: [Int] = [1, 2, 3, 4] let y: UInt = 4 x.filter { $0 == y } // expected-error {{binary operator '==' cannot be applied to operands of type 'Int' and 'UInt'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: (UInt, UInt), (Int, Int)}} } // <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } [0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }} _ in let r = (1,2).0 return r } // <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type func rdar21078316() { var foo : [String : String]? var bar : [(String, String)]? bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}} } // <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure var numbers = [1, 2, 3] zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}} // <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type' func foo20868864(_ callback: ([String]) -> ()) { } func rdar20868864(_ s: String) { var s = s foo20868864 { (strings: [String]) in s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}} } } // <rdar://problem/22058555> crash in cs diags in withCString func r22058555() { var firstChar: UInt8 = 0 "abc".withCString { chars in firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} } } // <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type func r20789423() { class C { func f(_ value: Int) { } } let p: C print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}} let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }} print("a") return "hi" } } // Make sure that behavior related to allowing trailing closures to match functions // with Any as a final parameter is the same after the changes made by SR-2505, namely: // that we continue to select function that does _not_ have Any as a final parameter in // presence of other possibilities. protocol SR_2505_Initable { init() } struct SR_2505_II : SR_2505_Initable {} protocol P_SR_2505 { associatedtype T: SR_2505_Initable } extension P_SR_2505 { func test(it o: (T) -> Bool) -> Bool { return o(T.self()) } } class C_SR_2505 : P_SR_2505 { typealias T = SR_2505_II func test(_ o: Any) -> Bool { return false } func call(_ c: C_SR_2505) -> Bool { // Note: no diagnostic about capturing 'self', because this is a // non-escaping closure -- that's how we know we have selected // test(it:) and not test(_) return c.test { o in test(o) } } } let _ = C_SR_2505().call(C_SR_2505()) // <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic extension Collection { func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index { return startIndex } } func fn_r28909024(n: Int) { return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}} _ in true } } // SR-2994: Unexpected ambiguous expression in closure with generics struct S_2994 { var dataOffset: Int } class C_2994<R> { init(arg: (R) -> Void) {} } func f_2994(arg: String) {} func g_2994(arg: Int) -> Double { return 2 } C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}} let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}} let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}} let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}} // https://bugs.swift.org/browse/SR-403 // The () -> T => () -> () implicit conversion was kicking in anywhere // inside a closure result, not just at the top-level. let mismatchInClosureResultType : (String) -> ((Int) -> Void) = { (String) -> ((Int) -> Void) in return { } // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} } // SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS func sr3520_1<T>(_ g: (inout T) -> Int) {} sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}} func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) { var x = item update(&x) } var sr3250_arg = 42 sr3520_2(sr3250_arg) { $0 += 3 } // ok // This test makes sure that having closure with inout argument doesn't crash with member lookup struct S_3520 { var number1: Int } func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{type of expression is ambiguous without more context}} // SR-1976/SR-3073: Inference of inout func sr1976<T>(_ closure: (inout T) -> Void) {} sr1976({ $0 += 2 }) // ok // SR-3073: UnresolvedDotExpr in single expression closure struct SR3073Lense<Whole, Part> { let set: (inout Whole, Part) -> () } struct SR3073 { var number1: Int func lenses() { let _: SR3073Lense<SR3073, Int> = SR3073Lense( set: { $0.number1 = $1 } // ok ) } } // SR-3479: Segmentation fault and other error for closure with inout parameter func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {} func sr3497() { let _ = sr3497_unfold((0, 0)) { s in 0 } // ok } // SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs let _: ((Any?) -> Void) = { (arg: Any!) in } // This example was rejected in 3.0 as well, but accepting it is correct. let _: ((Int?) -> Void) = { (arg: Int!) in } // rdar://30429709 - We should not attempt an implicit conversion from // () -> T to () -> Optional<()>. func returnsArray() -> [Int] { return [] } returnsArray().flatMap { $0 }.flatMap { } // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}}
apache-2.0
4af892238ff33235072c4100be22ad41
34.361702
254
0.640466
3.387437
false
false
false
false
domenicosolazzo/practice-swift
playgrounds/Array.playground/section-1.swift
1
1247
// Array: An array stores multiple values of the same type import Cocoa /* ====== Array literal ====== */ var arr: [String] = ["Domenico", "Italian"] /* ====== Counting ====== */ var count = arr.count /* ====== Checking if an array is empty ====== */ var isEmpty = arr.isEmpty /* ====== Append an item at the end ====== */ arr.append("last") // ...Or use the addition assignment operator arr.push("next") arr += ["next2", "abc"] /* ====== Retrieve a value ====== */ var firstValue = arr[0] /* ====== Override a value ====== */ arr[0] = "Updated" /* ====== Insert a value at a specific index ====== */ arr.insert("new-element", atIndex: 0) /* ====== Remove an item at a certain index ====== */ arr.removeAtIndex(0) /* ====== Remove the last element of the array ====== */ arr.removeLast() /* ====== Remove all the elements ====== */ arr.removeAll(keepCapacity: false) /* ====== Iterate over an array ====== */ for val in arr{ var temp = val } for (index, val) in enumerate(arr){ var i = index var temp = val } /* ====== Initializing an array ====== */ var someInts = Int()[] // ..Or someInts = [] /* ====== Reverse an array ====== */ var ordered = [1,2,3,4,5] var reversed = ordered.reverse() print(reversed)
mit
1093ca783e01c43b83f7a400c34c6ccb
12.265957
58
0.554932
3.352151
false
false
false
false
codefellows/sea-b23-iOS
TwitterClone/HomeTimeLineViewController.swift
1
2741
// // HomeTimeLineViewController.swift // TwitterClone // // Created by Bradley Johnson on 10/6/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import UIKit import Accounts import Social class HomeTimeLineViewController: UIViewController, UITableViewDataSource, UIApplicationDelegate { @IBOutlet weak var tableView: UITableView! var tweets : [Tweet]? var twitterAccount : ACAccount? var networkController : NetworkController! override func viewDidLoad() { super.viewDidLoad() self.tableView.registerNib(UINib(nibName: "TweetCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "TWEET_CELL") let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate self.networkController = appDelegate.networkController self.networkController.fetchHomeTimeLine { (errorDescription : String?, tweets : [Tweet]?) -> (Void) in if errorDescription != nil { //alert the user that something went wrong } else { self.tweets = tweets self.tableView.reloadData() } } println("Hello") if let path = NSBundle.mainBundle().pathForResource("tweet", ofType: "json") { var error : NSError? let jsonData = NSData(contentsOfFile: path) self.tweets = Tweet.parseJSONDataIntoTweets(jsonData) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.tweets != nil { return self.tweets!.count } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //step 1 dequeue the cell let cell = tableView.dequeueReusableCellWithIdentifier("TWEET_CELL", forIndexPath: indexPath) as TweetCell //step 2 figure out which model object youre going to use to configure the cell //this is where we would grab a reference to the correct tweet and use it to configure the cell let tweet = self.tweets?[indexPath.row] cell.tweetLabel.text = tweet?.text if tweet?.avatarImage != nil { cell.avatarImageView.image = tweet?.avatarImage } else { self.networkController.downloadUserImageForTweet(tweet!, completionHandler: { (image) -> (Void) in let cellForImage = self.tableView.cellForRowAtIndexPath(indexPath) as TweetCell? cellForImage?.avatarImageView.image = image }) } //step 3 return the cell return cell } }
mit
33e36f61af703c7b38db1549cfe3e21e
36.040541
132
0.631521
5.312016
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureWalletConnect/Sources/FeatureWalletConnectData/Session/Repository/SessionRepositoryMetadata.swift
1
4130
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import FeatureWalletConnectDomain import Foundation import MetadataKit import WalletPayloadKit final class SessionRepositoryMetadata: SessionRepositoryAPI { private let walletConnectMetadata: WalletConnectMetadataAPI private let walletConnectFetcher: WalletConnectFetcherAPI private let nativeWalletFlag: () -> AnyPublisher<Bool, Never> init( walletConnectMetadata: WalletConnectMetadataAPI = resolve(), walletConnectFetcher: WalletConnectFetcherAPI = resolve(), nativeWalletFlag: @escaping () -> AnyPublisher<Bool, Never> ) { self.walletConnectMetadata = walletConnectMetadata self.walletConnectFetcher = walletConnectFetcher self.nativeWalletFlag = nativeWalletFlag } func contains(session: WalletConnectSession) -> AnyPublisher<Bool, Never> { loadSessions() .map { sessions in sessions .contains(where: { $0.isEqual(session) }) } // in some cases WC tries to reconnect when Metadata is not yet available // in this case we don't want to display a first connection popup // the session is an existing one as it's a reconnect event .replaceError(with: true) .eraseToAnyPublisher() } func store(session: WalletConnectSession) -> AnyPublisher<Void, Never> { retrieve() .map { sessions -> [WalletConnectSession] in var sessions = sessions .filter { item in !item.isEqual(session) } sessions.append(session) return sessions } .flatMap { [store] sessions -> AnyPublisher<Void, Never> in store(sessions) } .eraseToAnyPublisher() } func remove(session: WalletConnectSession) -> AnyPublisher<Void, Never> { retrieve() .map { sessions in sessions.filter { item in !item.isEqual(session) } } .flatMap { [store] sessions -> AnyPublisher<Void, Never> in store(sessions) } .eraseToAnyPublisher() } func removeAll() -> AnyPublisher<Void, Never> { store(sessions: []) } func retrieve() -> AnyPublisher<[WalletConnectSession], Never> { loadSessions() .replaceError(with: []) .eraseToAnyPublisher() } private func loadSessions() -> AnyPublisher<[WalletConnectSession], WalletConnectMetadataError> { nativeWalletFlag() .flatMap { [walletConnectMetadata, walletConnectFetcher] isEnabled -> AnyPublisher<[WalletConnectSession], WalletConnectMetadataError> in guard isEnabled else { return walletConnectMetadata.v1Sessions } return walletConnectFetcher.fetchSessions() .mapError { _ in WalletConnectMetadataError.unavailable } .compactMap { wrapper in wrapper.retrieveSessions(version: .v1) } .eraseToAnyPublisher() } .eraseToAnyPublisher() } private func store(sessions: [WalletConnectSession]) -> AnyPublisher<Void, Never> { nativeWalletFlag() .flatMap { [walletConnectMetadata, walletConnectFetcher] isEnabled -> AnyPublisher<Void, Never> in guard isEnabled else { return walletConnectMetadata .update(v1Sessions: sessions) .replaceError(with: ()) .eraseToAnyPublisher() } return walletConnectFetcher .update(v1Sessions: sessions) .replaceError(with: ()) .mapToVoid() .eraseToAnyPublisher() } .eraseToAnyPublisher() } }
lgpl-3.0
5bb967dfd56b78388f80ab8c93421482
35.866071
110
0.574715
5.695172
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/DetailScreen/DetailCellViewModel.swift
1
534
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxDataSources public struct DetailCellViewModel { public let presenter: DetailCellPresenter public init(presenter: DetailCellPresenter) { self.presenter = presenter } } extension DetailCellViewModel: IdentifiableType, Equatable { public var identity: AnyHashable { presenter.identity } public static func == (lhs: DetailCellViewModel, rhs: DetailCellViewModel) -> Bool { lhs.presenter == rhs.presenter } }
lgpl-3.0
7aa009a893812380f24bfaa81172c36f
24.380952
88
0.714822
5.028302
false
false
false
false
kstaring/swift
stdlib/public/core/ObjCMirrors.swift
4
2537
//===--- ObjCMirrors.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) @_silgen_name("swift_ObjCMirror_count") func _getObjCCount(_: _MagicMirrorData) -> Int @_silgen_name("swift_ObjCMirror_subscript") func _getObjCChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror) func _getObjCSummary(_ data: _MagicMirrorData) -> String { let theDescription = _swift_stdlib_objcDebugDescription(data._loadValue(ofType: AnyObject.self)) as AnyObject return _cocoaStringToSwiftString_NonASCII(theDescription) } public // SPI(runtime) struct _ObjCMirror : _Mirror { let data: _MagicMirrorData public var value: Any { return data.objcValue } public var valueType: Any.Type { return data.objcValueType } public var objectIdentifier: ObjectIdentifier? { return data._loadValue(ofType: ObjectIdentifier.self) } public var count: Int { return _getObjCCount(data) } public subscript(i: Int) -> (String, _Mirror) { return _getObjCChild(i, data) } public var summary: String { return _getObjCSummary(data) } public var quickLookObject: PlaygroundQuickLook? { let object = _swift_ClassMirror_quickLookObject(data) return _getClassPlaygroundQuickLook(object) } public var disposition: _MirrorDisposition { return .objCObject } } public // SPI(runtime) struct _ObjCSuperMirror : _Mirror { let data: _MagicMirrorData public var value: Any { return data.objcValue } public var valueType: Any.Type { return data.objcValueType } // Suppress the value identifier for super mirrors. public var objectIdentifier: ObjectIdentifier? { return nil } public var count: Int { return _getObjCCount(data) } public subscript(i: Int) -> (String, _Mirror) { return _getObjCChild(i, data) } public var summary: String { return _getObjCSummary(data) } public var quickLookObject: PlaygroundQuickLook? { let object = _swift_ClassMirror_quickLookObject(data) return _getClassPlaygroundQuickLook(object) } public var disposition: _MirrorDisposition { return .objCObject } } #endif
apache-2.0
2964812288380021c698c3a467de4621
31.948052
111
0.688214
4.285473
false
false
false
false
iot-spotted/spotted
Source/EVglobal.swift
3
1633
// // EVglobal.swift // // Created by Edwin Vermeer on 4/29/15. // Copyright (c) 2015. All rights reserved. // import Foundation /** Replacement function for NSLog that will also output the filename, linenumber and function name. - parameter object: What you want to log - parameter filename: Will be auto populated by the name of the file from where this function is called - parameter line: Will be auto populated by the line number in the file from where this function is called - parameter funcname: Will be auto populated by the function name from where this function is called */ public func EVLog<T>(_ object: T, filename: String = #file, line: Int = #line, funcname: String = #function) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss:SSS" let process = ProcessInfo.processInfo let threadId = "." //NSThread.currentThread().threadDictionary print("\(dateFormatter.string(from: Date())) \(process.processName))[\(process.processIdentifier):\(threadId)] \((filename as NSString).lastPathComponent)(\(line)) \(funcname):\r\t\(object)\n") } /** Make sure the file is not backed up to iCloud - parameter filePath: the url of the file we want to set the attribute for */ public func addSkipBackupAttributeToItemAtPath(_ filePath:String) { let url:URL = URL(fileURLWithPath: filePath) do { try (url as NSURL).setResourceValue(NSNumber(value: true as Bool), forKey: URLResourceKey.isExcludedFromBackupKey) } catch { EVLog("ERROR: Could not set 'exclude from backup' attribute for file \(filePath)\n\\tERROR:(error?.description)") } }
bsd-3-clause
cbb8881f3894d169b21f9ba7e7aed5ff
40.871795
197
0.725658
4.241558
false
false
false
false
rizumita/ResourceInstantiatable
ResourceInstantiatableTests/StoryboardInstantiatorTests.swift
1
1875
// // StoryboardInstantiatorTests.swift // ResourceInstantiatable // // Created by 和泉田 領一 on 2015/09/28. // Copyright © 2015年 CAPH. All rights reserved. // import XCTest @testable import ResourceInstantiatable class StoryboardInstantiatorTests: XCTestCase { class StoryboardsManager { static let testViewController = StoryboardInstantiator<TestViewController>(name: "Test", bundle: NSBundle(forClass: StoryboardInstantiatorTests.self)) static let secondaryViewController = StoryboardInstantiator<TestViewController>(name: "Test", bundle: NSBundle(forClass: StoryboardInstantiatorTests.self), identifier: "Secondary") } override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testInstantiate() { if let controller = try? StoryboardsManager.testViewController.instantiate() { XCTAssertEqual(controller.message, "InitialViewController") } else { XCTFail() } if let controller = try? StoryboardsManager.secondaryViewController.instantiate() { XCTAssertEqual(controller.message, "SecondaryViewController") } else { XCTFail() } } func testInstantiateWithConfigure() { func configure(inout controller: TestViewController) { controller.message = "Configured" } if let controller = try? StoryboardsManager.testViewController.instantiate(configure) { XCTAssertEqual(controller.message, "Configured") } else { XCTFail() } } }
mit
49d5534c9f465e317cb93afe41d750a2
32.854545
188
0.665414
5.215686
false
true
false
false
Draveness/DKChainableAnimationKit
DKChainableAnimationKit/Classes/DKChainableAnimationKit+Extra.swift
3
3467
// // DKChainableAnimationKit+Extra.swift // DKChainableAnimationKit // // Created by Draveness on 15/6/14. // Copyright (c) 2015年 Draveness. All rights reserved. // import Foundation public extension DKChainableAnimationKit { public func makeOpacity(_ opacity: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let opacityAnimation = self.basicAnimationForKeyPath("opacity") opacityAnimation.fromValue = view.alpha as AnyObject! opacityAnimation.toValue = opacity as AnyObject! self.addAnimationFromCalculationBlock(opacityAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.alpha = opacity } return self } public func makeAlpha(_ alpha: CGFloat) -> DKChainableAnimationKit { return makeOpacity(alpha) } public func makeBackground(_ color: UIColor) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let backgroundColorAnimation = self.basicAnimationForKeyPath("backgroundColor") backgroundColorAnimation.fromValue = view.backgroundColor backgroundColorAnimation.toValue = color self.addAnimationFromCalculationBlock(backgroundColorAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.backgroundColor = color } return self } public func makeBorderColor(_ color: UIColor) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let borderColorAnimation = self.basicAnimationForKeyPath("borderColor") borderColorAnimation.fromValue = UIColor(cgColor: view.layer.borderColor!) borderColorAnimation.toValue = color self.addAnimationFromCalculationBlock(borderColorAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.layer.borderColor = color.cgColor } return self } public func makeBorderWidth(_ width: CGFloat) -> DKChainableAnimationKit { let width = max(0, width) self.addAnimationCalculationAction { (view: UIView) -> Void in let borderColorAnimation = self.basicAnimationForKeyPath("borderWidth") borderColorAnimation.fromValue = view.layer.borderWidth as AnyObject! borderColorAnimation.toValue = width as AnyObject! self.addAnimationFromCalculationBlock(borderColorAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.layer.borderWidth = width } return self } public func makeCornerRadius(_ cornerRadius: CGFloat) -> DKChainableAnimationKit { let cornerRadius = max(0, cornerRadius) self.addAnimationCalculationAction { (view: UIView) -> Void in let cornerRadiusAnimation = self.basicAnimationForKeyPath("cornerRadius") cornerRadiusAnimation.fromValue = view.layer.cornerRadius as AnyObject! cornerRadiusAnimation.toValue = cornerRadius as AnyObject! self.addAnimationFromCalculationBlock(cornerRadiusAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.layer.cornerRadius = cornerRadius } return self } }
mit
f270c56f2348dce5d95659754077234c
37.932584
91
0.677633
5.322581
false
false
false
false
stolycizmus/WowToken
WowToken/HistoryViewController.swift
1
7075
// // HistoryViewController.swift // WowToken // // Created by Kadasi Mate on 2015. 11. 28.. // Copyright © 2015. Tairpake Inc. All rights reserved. // import UIKit import CoreData class HistoryViewController: UIViewController { @IBOutlet weak var dailyMinLabel: UILabel? @IBOutlet weak var dailyMaxLabel: UILabel? @IBOutlet weak var averageLabel: UILabel? @IBOutlet weak var intervallumPicker: UISegmentedControl! @IBOutlet weak var graphView: GraphView! @IBOutlet weak var graphTitleLabel: UILabel! @IBOutlet weak var endDateLabel: UILabel! @IBOutlet weak var middleDateLabel: UILabel! @IBOutlet weak var startDateLabel: UILabel! @IBOutlet weak var middleLabel: UILabel! @IBOutlet weak var minLabel: UILabel! @IBOutlet weak var maxLabel: UILabel! @IBOutlet weak var noDataLabel: UILabel! let intervallums: [Double] = [10800, 43200, 86400, 604800] var navigated = false override func viewDidLoad() { super.viewDidLoad() if navigated { self.navigationItem.title = "History" fetchGraphData(intervallumPicker) if averageLabel != nil { fetchLabelsData() } } } @IBAction func fetchGraphData(_ sender: UISegmentedControl){ let prefferedRegion = AppDelegate.sharedAppDelegate.userDefaults.value(forKey: "prefferedRegion") as! String var graphPoints = [Double]() var graphPointsLabelText = [String]() let bottomTime = Date(timeIntervalSinceNow: 0).timeIntervalSince1970-intervallums[intervallumPicker.selectedSegmentIndex] let dateFormatter = DateFormatter() switch sender.selectedSegmentIndex { case 0: dateFormatter.dateFormat = "HH:mm" graphTitleLabel.text = "Buyprice in the last 3 hours" case 1: dateFormatter.dateFormat = "MMM dd. HH:mm" graphTitleLabel.text = "Buyprice in the last 12 hours" case 2: dateFormatter.dateFormat = "MMM dd. HH:mm" graphTitleLabel.text = "Buyprice in the past 1 day" case 3: dateFormatter.dateFormat = "MMM dd." graphTitleLabel.text = "Buyprice in the past 1 week" default: break } let moc = AppDelegate.sharedAppDelegate.managedObjectContext let fetchRequestHistory: NSFetchRequest<History> = NSFetchRequest(entityName: "History") fetchRequestHistory.predicate = NSPredicate(format: "region.shortName == %@ AND time>=\(Int(bottomTime))" ,prefferedRegion) fetchRequestHistory.sortDescriptors = [NSSortDescriptor(key: "time", ascending: true)] do { if let result = try moc.fetch(fetchRequestHistory) as? [History] { for history in result { if graphPoints.last != (history.gold as! Double) { graphPoints.append(history.gold as! Double) let timeInterval = history.time as! Double graphPointsLabelText.append(dateFormatter.string(from: Date(timeIntervalSince1970: timeInterval))) } } } } catch {} //if no data fetched from core data - eg. the server not provided data back to bottomtime if !graphPoints.isEmpty { //load graphview with data points graphView.nodata = false for subview in graphView.subviews { subview.isHidden = false } //9-member moving average for "1 week" datapoints if sender.selectedSegmentIndex == 3 { var avgPoints: [Double] = [] for index in 4...(graphPoints.count-5) { var newElement = Double(0) for _index in index-4...index+4 { newElement += graphPoints[_index] } newElement = newElement/9 avgPoints.append(newElement) } graphPoints = avgPoints } noDataLabel.isHidden = true startDateLabel.text = graphPointsLabelText.first endDateLabel.text = graphPointsLabelText.last middleDateLabel.text = graphPointsLabelText[graphPointsLabelText.count/2] graphView.graphPoints = graphPoints let maxValue = round(graphPoints.max()!/100) let minValue = round(graphPoints.min()!/100) let middleValue = (maxValue-minValue)/2 + minValue maxLabel.text = (maxValue/10).description + "k" minLabel.text = (minValue/10).description + "k" middleLabel.text = (middleValue/10).description + "k" graphView.setNeedsDisplay() } else { //do this if no data points fetched graphView.nodata = true for subview in graphView.subviews { //if subview.tag = 10 then its the title of the graphview, that shouldn't be hidden if subview.tag != 10 { subview.isHidden = true } } noDataLabel.isHidden = false graphView.setNeedsDisplay() } } func fetchLabelsData() { let prefferedRegion = AppDelegate.sharedAppDelegate.userDefaults.value(forKey: "prefferedRegion") as! String var data = [Int]() let bottomTime = Date(timeIntervalSinceNow: 0).timeIntervalSince1970-86400 let moc = AppDelegate.sharedAppDelegate.managedObjectContext let fetchRequestHistory: NSFetchRequest<History> = NSFetchRequest(entityName: "History") fetchRequestHistory.predicate = NSPredicate(format: "region.shortName == %@ AND time>=\(Int(bottomTime))" ,prefferedRegion) fetchRequestHistory.sortDescriptors = [NSSortDescriptor(key: "time", ascending: true)] do { if let result = try moc.fetch(fetchRequestHistory) as? [History] { for history in result { data.append(history.gold as! Int) } } } catch {} if !data.isEmpty { var average = 0 for item in data { average += item } average = average/data.count averageLabel?.text = "Daily average: \(average) gold" dailyMaxLabel?.text = "Daily maximum: \(data.max()!) gold" dailyMinLabel?.text = "Daily minimum: \(data.min()!) gold" } else { averageLabel?.text = "" dailyMaxLabel?.text = "" dailyMinLabel?.text = "" } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
d3c1214eda6b77bc2ec6e933ff0020a7
40.127907
131
0.600226
4.988717
false
false
false
false
hooman/swift
test/SILGen/foreach_async.swift
3
8535
// RUN: %target-swift-emit-silgen %s -module-name foreach_async -swift-version 5 -disable-availability-checking | %FileCheck %s // REQUIRES: concurrency ////////////////// // Declarations // ////////////////// class C {} @_silgen_name("loopBodyEnd") func loopBodyEnd() -> () @_silgen_name("condition") func condition() -> Bool @_silgen_name("loopContinueEnd") func loopContinueEnd() -> () @_silgen_name("loopBreakEnd") func loopBreakEnd() -> () @_silgen_name("funcEnd") func funcEnd() -> () struct TrivialStruct { var value: Int32 } struct NonTrivialStruct { var value: C } struct GenericStruct<T> { var value: T var value2: C } protocol P {} protocol ClassP : AnyObject {} protocol GenericCollection : Collection { } struct AsyncLazySequence<S: Sequence>: AsyncSequence { typealias Element = S.Element typealias AsyncIterator = Iterator struct Iterator: AsyncIteratorProtocol { typealias Element = S.Element var iterator: S.Iterator? mutating func next() async -> S.Element? { return iterator?.next() } } var sequence: S func makeAsyncIterator() -> Iterator { return Iterator(iterator: sequence.makeIterator()) } } /////////// // Tests // /////////// //===----------------------------------------------------------------------===// // Trivial Struct //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden [ossa] @$s13foreach_async13trivialStructyyAA17AsyncLazySequenceVySaySiGGYaF : $@convention(thin) @async (@guaranteed AsyncLazySequence<Array<Int>>) -> () { // CHECK: bb0([[SOURCE:%.*]] : @guaranteed $AsyncLazySequence<Array<Int>>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var AsyncLazySequence<Array<Int>>.Iterator }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: br [[LOOP_DEST:bb[0-9]+]] // CHECK: [[LOOP_DEST]]: // CHECK: [[NEXT_RESULT:%.*]] = alloc_stack $Optional<Int> // CHECK: [[MUTATION:%.*]] = begin_access // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $AsyncLazySequence<Array<Int>>.Iterator, #AsyncIteratorProtocol.next : <Self where Self : AsyncIteratorProtocol> (inout Self) -> () async throws -> Self.Element? : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error) // CHECK: try_apply [[WITNESS_METHOD]]<AsyncLazySequence<[Int]>.Iterator>([[NEXT_RESULT]], [[MUTATION]]) : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // CHECK: [[NORMAL_BB]]([[VAR:%.*]] : $()): // CHECK: end_access [[MUTATION]] // CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: loopBodyEnd // CHECK: br [[LOOP_DEST]] // CHECK: [[NONE_BB]]: // CHECK: funcEnd // CHECK return // CHECK: [[ERROR_BB]]([[VAR:%.*]] : @owned $Error): // CHECK: unreachable // CHECK: } // end sil function '$s13foreach_async13trivialStructyyAA17AsyncLazySequenceVySaySiGGYaF' func trivialStruct(_ xx: AsyncLazySequence<[Int]>) async { for await x in xx { loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s13foreach_async21trivialStructContinueyyAA17AsyncLazySequenceVySaySiGGYaF : $@convention(thin) @async (@guaranteed AsyncLazySequence<Array<Int>>) -> () { // CHECK: bb0([[SOURCE:%.*]] : @guaranteed $AsyncLazySequence<Array<Int>>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var AsyncLazySequence<Array<Int>>.Iterator }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: br [[LOOP_DEST:bb[0-9]+]] // CHECK: [[LOOP_DEST]]: // CHECK: [[NEXT_RESULT:%.*]] = alloc_stack $Optional<Int> // CHECK: [[MUTATION:%.*]] = begin_access // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $AsyncLazySequence<Array<Int>>.Iterator, #AsyncIteratorProtocol.next : <Self where Self : AsyncIteratorProtocol> (inout Self) -> () async throws -> Self.Element? : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error) // CHECK: try_apply [[WITNESS_METHOD]]<AsyncLazySequence<[Int]>.Iterator>([[NEXT_RESULT]], [[MUTATION]]) : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // CHECK: [[NORMAL_BB]]([[VAR:%.*]] : $()): // CHECK: end_access [[MUTATION]] // CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: condition // CHECK: cond_br [[VAR:%.*]], [[COND_TRUE:bb[0-9]+]], [[COND_FALSE:bb[0-9]+]] // CHECK: [[COND_TRUE]]: // CHECK: loopContinueEnd // CHECK: br [[LOOP_DEST]] // CHECK: [[COND_FALSE]]: // CHECK: loopBodyEnd // CHECK: br [[LOOP_DEST]] // CHECK: [[NONE_BB]]: // CHECK: funcEnd // CHECK return // CHECK: [[ERROR_BB]]([[VAR:%.*]] : @owned $Error): // CHECK: unreachable // CHECK: } // end sil function '$s13foreach_async21trivialStructContinueyyAA17AsyncLazySequenceVySaySiGGYaF' func trivialStructContinue(_ xx: AsyncLazySequence<[Int]>) async { for await x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructBreak(_ xx: AsyncLazySequence<[Int]>) async { for await x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s13foreach_async26trivialStructContinueBreakyyAA17AsyncLazySequenceVySaySiGGYaF : $@convention(thin) @async (@guaranteed AsyncLazySequence<Array<Int>>) -> () // CHECK: bb0([[SOURCE:%.*]] : @guaranteed $AsyncLazySequence<Array<Int>>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var AsyncLazySequence<Array<Int>>.Iterator }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: br [[LOOP_DEST:bb[0-9]+]] // CHECK: [[LOOP_DEST]]: // CHECK: [[NEXT_RESULT:%.*]] = alloc_stack $Optional<Int> // CHECK: [[MUTATION:%.*]] = begin_access // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $AsyncLazySequence<Array<Int>>.Iterator, #AsyncIteratorProtocol.next : <Self where Self : AsyncIteratorProtocol> (inout Self) -> () async throws -> Self.Element? : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error) // CHECK: try_apply [[WITNESS_METHOD]]<AsyncLazySequence<[Int]>.Iterator>([[NEXT_RESULT]], [[MUTATION]]) : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // CHECK: [[NORMAL_BB]]([[VAR:%.*]] : $()): // CHECK: end_access [[MUTATION]] // CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: condition // CHECK: cond_br [[VAR:%.*]], [[COND_TRUE:bb[0-9]+]], [[COND_FALSE:bb[0-9]+]] // CHECK: [[COND_TRUE]]: // CHECK: loopBreakEnd // CHECK: br [[LOOP_EXIT:bb[0-9]+]] // CHECK: [[COND_FALSE]]: // CHECK: condition // CHECK: cond_br [[VAR:%.*]], [[COND_TRUE2:bb[0-9]+]], [[COND_FALSE2:bb[0-9]+]] // CHECK: [[COND_TRUE2]]: // CHECK: loopContinueEnd // CHECK: br [[LOOP_DEST]] // CHECK: [[COND_FALSE2]]: // CHECK: br [[LOOP_DEST]] // CHECK: [[LOOP_EXIT]]: // CHECK: return // CHECK: } // end sil function '$s13foreach_async26trivialStructContinueBreakyyAA17AsyncLazySequenceVySaySiGGYaF' func trivialStructContinueBreak(_ xx: AsyncLazySequence<[Int]>) async { for await x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() }
apache-2.0
a981a81a982d4c42fcfefb0dc0195a8d
37.165919
381
0.627893
3.574549
false
false
false
false
GoldRong/LiveProject
LiveDemo/LiveDemo/Classes/Home/Controller/HomeViewController.swift
1
4630
// // HomeViewController.swift // LiveDemo // // Created by Yang on 2017/7/24. // Copyright © 2017年 Mr.Yang. All rights reserved. // import UIKit private let kTitleViewH: CGFloat = 40 class HomeViewController: UIViewController { //MARK:- 懒加载属性 fileprivate lazy var pageTitleView: PageTitleView = { [weak self] in let titleFrame = CGRect(x: 0, y: 64, width: kScreenW, height: kTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() fileprivate lazy var pageContentView : PageContentView = { [weak self] in //1.确定内容frame let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH) //2.确定所有的子控制器 var childVcs = [UIViewController]() for _ in 0..<4{ let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVcs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) return contentView }() override func viewDidLoad() { super.viewDidLoad() //设置UI界面 setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK:- 设置UI界面 extension HomeViewController{ fileprivate func setupUI(){ //0.不需要调整ScrollView内边距 automaticallyAdjustsScrollViewInsets = false // 1.设置导航栏 setupNavigationBar() // 2.添加titleView view.addSubview(pageTitleView) //3.添加ContentView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.purple } fileprivate func setupNavigationBar(){ // 1.设置左侧Item /*//基础用法 let btn = UIButton() btn.setImage(UIImage.init(named: "logo"), for: UIControlState.normal) btn.sizeToFit() navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: btn) // 2.设置右侧Item let size = CGSize.init(width: 40, height: 40) let historyBtn = UIButton() historyBtn.setImage(UIImage.init(named: "image_my_history"), for: .normal) historyBtn.setImage(UIImage.init(named: "Image_my_history_click"), for: .highlighted) historyBtn.frame = CGRect.init(origin: CGPoint.zero, size: size) let histroyItem = UIBarButtonItem.init(customView: historyBtn) let searchBtn = UIButton() searchBtn.setImage(UIImage.init(named: "btn_search"), for: .normal) searchBtn.setImage(UIImage.init(named: "btn_search_clicked"), for: .highlighted) searchBtn.frame = CGRect.init(origin: CGPoint.zero, size: size) let searchItem = UIBarButtonItem.init(customView: searchBtn) let qrcodeBtn = UIButton() qrcodeBtn.setImage(UIImage.init(named: "Image_scan"), for: .normal) qrcodeBtn.setImage(UIImage.init(named: "Image_scan_click"), for: .highlighted) qrcodeBtn.frame = CGRect.init(origin: CGPoint.zero, size: size) let qrcodeItem = UIBarButtonItem.init(customView: qrcodeBtn) */ //高级用法 //1.设置左侧Item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") //2.设置右侧Item let size = CGSize.init(width: 40, height: 40) let histroyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [histroyItem, searchItem, qrcodeItem] } } //MARK:- 遵循PageTitleViewDelegate协议 extension HomeViewController : PageTitleViewDelegate{ func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } }
mit
677d8deba66bae34a544033000c55429
35.040323
156
0.645111
4.650364
false
false
false
false
aiwalle/LiveProject
LiveProject/CommonViews/LJPageView/LJPageCollectionView.swift
1
7035
// // LJPageCollectionView.swift // LiveProject // // Created by liang on 2017/8/4. // Copyright © 2017年 liang. All rights reserved. // import UIKit protocol LJPageCollectionViewDataSource: class { func numberOfSectionInPageCollectionView(_ pageCollectionView : LJPageCollectionView) -> Int func pageCollectionView(_ pageCollectionView : LJPageCollectionView, numberOfItemsInSection section: Int) -> Int func pageCollectionView(_ pageCollectionView : LJPageCollectionView,_ collectionView : UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell } protocol LJPageCollectionViewDelegate: class { func pageCollectionView(_ pageCollectionView : LJPageCollectionView, didSelectItemAt indexPath: IndexPath) } class LJPageCollectionView: UIView { weak open var dataSource: LJPageCollectionViewDataSource? weak open var delegate: LJPageCollectionViewDelegate? fileprivate var titles : [String] fileprivate var style : LJPageStyle fileprivate var isTitleInTop : Bool fileprivate lazy var currentIndex : IndexPath = IndexPath(item: 0, section: 0) fileprivate var titleView : LJTitleView! fileprivate var collectionView : UICollectionView! fileprivate var pageControl : UIPageControl! fileprivate var layout : LJPageCollectionLayout init(frame: CGRect, titles: [String], style: LJPageStyle, isTitleInTop: Bool, layout: LJPageCollectionLayout) { self.titles = titles self.style = style self.isTitleInTop = isTitleInTop self.layout = layout super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension LJPageCollectionView { func setupUI() { let titleY = isTitleInTop ? 0 : bounds.height - style.titleHeight let titleViewFrame = CGRect(x: 0, y: titleY, width: bounds.width, height: style.titleHeight) titleView = LJTitleView(frame: titleViewFrame, titles: self.titles, style: self.style) titleView.delegate = self addSubview(titleView) let pageH : CGFloat = 20.0 let pageY = isTitleInTop ? bounds.height - pageH : bounds.height - pageH - titleViewFrame.size.height let pageControlFrame = CGRect(x: 0, y: pageY, width: bounds.width, height: pageH) pageControl = UIPageControl(frame: pageControlFrame) pageControl.numberOfPages = 4 pageControl.currentPage = 0 addSubview(pageControl) let collectionY = isTitleInTop ? style.titleHeight : 0 let collectionH = bounds.height - style.titleHeight - pageControl.frame.size.height let collectionViewFrame = CGRect(x: 0, y: collectionY, width: bounds.width, height: collectionH) collectionView = UICollectionView(frame: collectionViewFrame, collectionViewLayout: layout) collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self addSubview(collectionView) titleView.backgroundColor = UIColor.getRandomColor() pageControl.backgroundColor = UIColor.getRandomColor() collectionView.backgroundColor = UIColor.getRandomColor() } } extension LJPageCollectionView { open func register(_ cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String) { collectionView.register(cellClass, forCellWithReuseIdentifier: identifier) } open func registerNib(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) { collectionView.register(nib, forCellWithReuseIdentifier: identifier) } open func reloadData() { collectionView.reloadData() } } extension LJPageCollectionView : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource?.numberOfSectionInPageCollectionView(self) ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let sectionItemCounts = dataSource?.pageCollectionView(self, numberOfItemsInSection: section) ?? 0 if section == 0 { pageControl.numberOfPages = (sectionItemCounts - 1) / (layout.cols * layout.rows) + 1 } return sectionItemCounts } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return dataSource!.pageCollectionView(self, collectionView, cellForItemAt: indexPath) } } extension LJPageCollectionView : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.pageCollectionView(self, didSelectItemAt: indexPath) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewEndScroll() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { scrollViewEndScroll() } } private func scrollViewEndScroll() { let point = CGPoint(x: layout.sectionInset.left + 1 + collectionView.contentOffset.x, y: layout.sectionInset.top + 1) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } if indexPath.section != currentIndex.section { let itemsCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: indexPath.section) ?? 0 pageControl.numberOfPages = (itemsCount - 1) / (layout.cols * layout.rows) + 1 titleView.setCurrentIndex(indexPath.section) currentIndex = indexPath } pageControl.currentPage = indexPath.item / (layout.cols * layout.rows) } } extension LJPageCollectionView : LJTitleViewDelegate { func titleView(_ titleView: LJTitleView, targetIndex: Int) { let indexPath = IndexPath(item: 0, section: targetIndex) // scrollTo 只能滚动到collectionView的contentSize,不可能超过滚动范围,所以如果再设置contentOffset就会有问题 collectionView.scrollToItem(at: indexPath, at: .left, animated: false) // 调整间距偏移量,这里的代码是来解决👆的问题 let itemsCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: targetIndex) ?? 0 pageControl.numberOfPages = (itemsCount - 1) / (layout.cols * layout.rows) + 1 pageControl.currentPage = 0 currentIndex = indexPath if (targetIndex == collectionView.numberOfSections - 1) && itemsCount <= layout.cols * layout.rows{ return } collectionView.contentOffset.x -= layout.sectionInset.left } }
mit
49e3f71f7a1eb5b5233dae96f5d4fbf0
39.770588
168
0.701486
5.377036
false
false
false
false
dclelland/Gong
Sources/Gong/Constants/MIDIVelocity.swift
1
378
// // MIDIVelocity.swift // Gong // // Created by Daniel Clelland on 7/10/17. // Copyright © 2017 Daniel Clelland. All rights reserved. // import Foundation public let pianississimo = 16 public let pianissimo = 33 public let piano = 49 public let mezzopiano = 64 public let mezzoforte = 80 public let forte = 96 public let fortissimo = 112 public let fortississimo = 127
mit
1c188e06eb750ffa74289500207f5749
19.944444
58
0.734748
3.25
false
false
false
false
doncl/shortness-of-pants
BBPTable/BBPTable/BBPTableCell.swift
1
5445
// // BBPTableCellCollectionViewCell.swift // BBPTable // // Created by Don Clore on 8/3/15. // Copyright (c) 2015 Beer Barrel Poker Studios. All rights reserved. // import UIKit enum CellType : Int { case columnHeading = 1 case dataOdd = 2 case dataEven = 4 } class BBPTableCell: UICollectionViewCell { // MARK: Default cell values // Header characteristics. static var headerFontName: String = "HelveticaNeue-Bold" static var headerFontSize: CGFloat = 12.0 static var headerTextColor: UIColor = UIColor(red:0.976, green: 0.976, blue: 0.976, alpha: 1.0) static var headerColor: UIColor = UIColor(red:0.271, green: 0.271, blue: 0.271, alpha: 1.0) // Data cell characteristics. static var dataCellFontName: String = "HelveticaNeue" static var dataCellFontSize: CGFloat = 10.0 static var dataCellTextColor: UIColor = UIColor(red:0.271, green:0.271, blue:0.271, alpha:1.0) static var oddRowColor: UIColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:1.0) static var evenRowColor: UIColor = UIColor(red:0.976, green:0.976, blue:0.976, alpha: 1.0) static var borderColor: UIColor = UIColor(red:223.0/255.0, green:223.0/255.0, blue:223.0/255.0, alpha:1.0) static var borderWidth: CGFloat = 0.5 // MARK: Cell instance data var label : UILabel! // MARK: initializers override init(frame: CGRect) { super.init(frame: frame) label = UILabel(frame: self.contentView.bounds) label.setContentHuggingPriority(UILayoutPriority(rawValue: 0), for:.horizontal) label.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for:.horizontal) label.numberOfLines = 0 setupCellInfo(.dataOdd) contentView.translatesAutoresizingMaskIntoConstraints = false label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) setupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } static func initializeCellProperties(_ props: CellProperties) { headerColor = props.headerColor! headerFontName = props.headerFontName! headerFontSize = props.headerFontSize! headerTextColor = props.headerTextColor! dataCellFontName = props.dataCellFontName! dataCellFontSize = props.dataCellFontSize! dataCellTextColor = props.dataCellTextColor! oddRowColor = props.oddRowColor! evenRowColor = props.evenRowColor! borderColor = props.borderColor! borderWidth = props.borderWidth! } // MARK: instance methods func setCellText(_ text: String) { label.text = text } func setupConstraints() { let viewDict = ["cellLabel" : label! as Any] let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[cellLabel]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDict) let centeringXConstraint = NSLayoutConstraint(item: self, attribute:.centerX, relatedBy:.equal, toItem:label, attribute:.centerX, multiplier:1.0, constant:0.0) let centeringYConstraint = NSLayoutConstraint(item: self, attribute:.centerY, relatedBy:.equal, toItem:label, attribute:.centerY, multiplier:1.0, constant:0.0) let centeringConstraints = [centeringXConstraint, centeringYConstraint] addConstraints(horizontalConstraints) NSLayoutConstraint.activate(horizontalConstraints) NSLayoutConstraint.activate(centeringConstraints) } func setupCellInfo(_ cellType: CellType) { let ci = BBPTableCell.getCellInfoForTypeOfCell(cellType) layer.borderWidth = ci.borderWidth layer.borderColor = ci.borderColor.cgColor label.baselineAdjustment = ci.baselineAdjustment label.backgroundColor = ci.backgroundColor backgroundColor = ci.backgroundColor label.textAlignment = ci.textAlignment label.font = UIFont(name: ci.fontName, size: ci.fontSize) label.textColor = ci.textColor } static func getCellInfoForTypeOfCell(_ cellType: CellType) -> CellInfo { let fontSize: CGFloat let textColor: UIColor let fontName: String let backgroundColor: UIColor switch cellType { case .columnHeading: fontSize = BBPTableCell.headerFontSize textColor = BBPTableCell.headerTextColor fontName = BBPTableCell.headerFontName backgroundColor = BBPTableCell.headerColor case .dataOdd, .dataEven: fontSize = BBPTableCell.dataCellFontSize fontName = BBPTableCell.dataCellFontName backgroundColor = cellType == .dataOdd ? BBPTableCell.oddRowColor : BBPTableCell.evenRowColor textColor = BBPTableCell.dataCellTextColor } return CellInfo(fontSize: fontSize, fontName: fontName, textColor: textColor, backgroundColor: backgroundColor, borderColor: BBPTableCell.borderColor, borderWidth: BBPTableCell.borderWidth, textAlignment: NSTextAlignment.center, baselineAdjustment: UIBaselineAdjustment.alignCenters) } }
mit
02ffde03689216e217b0d41ef1a5ee79
36.040816
104
0.670156
4.714286
false
false
false
false