repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
takeo-asai/math-puzzle
problems/23.swift
1
871
enum Game { case Win case Lose } // (Int, Int)はDictionaryに使えない. 一度何かしら変換が必要 struct Status: Hashable { let coin: Int let game: Int init(_ c: Int, _ g: Int) { coin = c game = g } var hashValue: Int { return String("\(coin),\(game)").hashValue } } func == (lhs: Status, rhs: Status) -> Bool { return lhs.coin == rhs.coin && lhs.game == rhs.game } let games: [Game] = [.Win, .Lose] var memo: [Status: Int] = Dictionary() func blackjack(coin: Int, _ game: Int) -> Int { if let m = memo[Status(coin, game)] { return m } if game == 0 { return 1 } if coin == 0 { return 0 } var count = 0 for g in games { switch g { case .Win: count += blackjack(coin+1, game-1) case .Lose: count += blackjack(coin-1, game-1) } } memo[Status(coin, game)] = count return count } let c = blackjack(10, 24) print(c)
mit
f14f02db439c04e13472b0a87b370b51
16.4375
52
0.600956
2.491071
false
false
false
false
JCount/brew
Library/Homebrew/cask/utils/quarantine.swift
4
1352
#!/usr/bin/swift import Foundation struct SwiftErr: TextOutputStream { public static var stream = SwiftErr() mutating func write(_ string: String) { fputs(string, stderr) } } // TODO: tell which arguments have to be provided guard CommandLine.arguments.count >= 4 else { exit(2) } var dataLocationURL = URL(fileURLWithPath: CommandLine.arguments[1]) let quarantineProperties: [String: Any] = [ kLSQuarantineAgentNameKey as String: "Homebrew Cask", kLSQuarantineTypeKey as String: kLSQuarantineTypeWebDownload, kLSQuarantineDataURLKey as String: CommandLine.arguments[2], kLSQuarantineOriginURLKey as String: CommandLine.arguments[3] ] // Check for if the data location URL is reachable do { let isDataLocationURLReachable = try dataLocationURL.checkResourceIsReachable() guard isDataLocationURLReachable else { print("URL \(dataLocationURL.path) is not reachable. Not proceeding.", to: &SwiftErr.stream) exit(1) } } catch { print(error.localizedDescription, to: &SwiftErr.stream) exit(1) } // Quarantine the file do { var resourceValues = URLResourceValues() resourceValues.quarantineProperties = quarantineProperties try dataLocationURL.setResourceValues(resourceValues) } catch { print(error.localizedDescription, to: &SwiftErr.stream) exit(1) }
bsd-2-clause
3da56f9e80f8f369df27b9f0579f5494
27.765957
100
0.736686
4.251572
false
false
false
false
loganSims/wsdot-ios-app
wsdot/CameraViewController.swift
1
7278
// // CameraViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // 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 GoogleMobileAds class CameraViewController: UIViewController, GADBannerViewDelegate, MapMarkerDelegate, GMSMapViewDelegate { @IBOutlet weak var cameraImage: UIImageView! fileprivate let cameraMarker = GMSMarker(position: CLLocationCoordinate2D(latitude: 0, longitude: 0)) @IBOutlet weak var favoriteBarButton: UIBarButtonItem! @IBOutlet weak var bannerView: DFPBannerView! @IBOutlet weak var directionLabel: UILabel! @IBOutlet weak var milepostLabel: UILabel! @IBOutlet weak var cameraImageHeightConstraint: NSLayoutConstraint! weak fileprivate var embeddedMapViewController: SimpleMapViewController! var cameraItem: CameraItem = CameraItem() var adTarget: String = "other" var adsEnabled = true override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = cameraItem.title; embeddedMapViewController.view.isHidden = false if (cameraItem.selected) { favoriteBarButton.image = UIImage(named: "icStarSmallFilled") favoriteBarButton.accessibilityLabel = "remove from favorites" } else { favoriteBarButton.image = UIImage(named: "icStarSmall") favoriteBarButton.accessibilityLabel = "add to favorites" } switch (cameraItem.direction) { case "N": directionLabel.text = "This camera faces north" break case "S": directionLabel.text = "This camera faces south" break case "E": directionLabel.text = "This camera faces east" break case "W": directionLabel.text = "This camera faces west" break case "B": directionLabel.text = "This camera could be pointing in a number of directions for operational reasons." break default: directionLabel.isHidden = true break } if (cameraItem.milepost == -1) { milepostLabel.isHidden = true } else { milepostLabel.isHidden = false milepostLabel.text = "near milepost \(cameraItem.milepost)" } favoriteBarButton.tintColor = Colors.yellow // Set up map marker cameraMarker.position = CLLocationCoordinate2D(latitude: self.cameraItem.latitude, longitude: self.cameraItem.longitude) cameraMarker.icon = UIImage(named: "icMapCamera") self.embeddedMapViewController.view.isHidden = false // Ad Banner if (adsEnabled) { bannerView.adUnitID = ApiKeys.getAdId() bannerView.rootViewController = self bannerView.adSize = getFullWidthAdaptiveAdSize() let request = DFPRequest() request.customTargeting = ["wsdotapp":adTarget] bannerView.load(request) bannerView.delegate = self } else { bannerView.isHidden = true } } func adViewDidReceiveAd(_ bannerView: GADBannerView) { bannerView.isAccessibilityElement = true bannerView.accessibilityLabel = "advertisement banner." } override func viewWillAppear(_ animated: Bool) { // This is incase the camera is in a pager view // and needs to add the marker again because it // isn't properly added when the pager sets up the // side page views. if let mapView = embeddedMapViewController.view as? GMSMapView{ cameraMarker.map = mapView mapView.settings.setAllGesturesEnabled(false) mapView.moveCamera(GMSCameraUpdate.setTarget(CLLocationCoordinate2D(latitude: self.cameraItem.latitude, longitude: self.cameraItem.longitude), zoom: 14)) } let placeholder: UIImage? = UIImage(named: "imagePlaceholder") // Add timestamp to help prevent caching let urlString = cameraItem.url + "?" + String(Int(Date().timeIntervalSince1970 / 60)) cameraImage.sd_setImage(with: URL(string: urlString), placeholderImage: placeholder, options: .refreshCached, completed: { image, error, cacheType, imageURL in let superViewWidth = self.view.frame.size.width - 16 if (error != nil) { self.cameraImage.image = UIImage(named: "cameraOffline") } else { let ratio = image!.size.width / image!.size.height let newHeight = superViewWidth / ratio print(newHeight) self.cameraImageHeightConstraint.constant = newHeight } } ) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MyAnalytics.screenView(screenName: "CameraImage") } // MARK: Naviagtion // Get refrence to child VC override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? SimpleMapViewController, segue.identifier == "EmbedMapSegue" { vc.markerDelegate = self vc.mapDelegate = self self.embeddedMapViewController = vc } } func mapReady() { if let mapView = embeddedMapViewController.view as? GMSMapView{ cameraMarker.map = mapView mapView.settings.setAllGesturesEnabled(false) mapView.moveCamera(GMSCameraUpdate.setTarget(CLLocationCoordinate2D(latitude: self.cameraItem.latitude, longitude: self.cameraItem.longitude), zoom: 14)) } } @IBAction func updateFavorite(_ sender: UIBarButtonItem) { if (cameraItem.selected){ CamerasStore.updateFavorite(cameraItem, newValue: false) favoriteBarButton.image = UIImage(named: "icStarSmall") favoriteBarButton.accessibilityLabel = "add to favorites" }else { CamerasStore.updateFavorite(cameraItem, newValue: true) favoriteBarButton.image = UIImage(named: "icStarSmallFilled") favoriteBarButton.accessibilityLabel = "remove from favorites" } } }
gpl-3.0
dee5842ce8df7c0b2a8248223f77a650
37.305263
167
0.615416
5.415179
false
false
false
false
BareFeetWare/BFWDrawView
BFWDrawView/Modules/Draw/View/DrawingView.swift
1
12906
// // DrawingView.swift // BFWDrawView // // Created by Tom Brodhurst-Hill on 30/04/2016. // Copyright © 2016 BareFeetWare. All rights reserved. // Free to use at your own risk, with acknowledgement to BareFeetWare. import UIKit @IBDesignable open class DrawingView: UIView { // MARK: - Init public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear contentMode = .redraw // forces redraw when view is resized, eg when device is rotated commonInit() } public required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } /// Called by init(frame:) and init(coder:), after super.init. Implement in subclass if required, and call super. open func commonInit() { } // MARK: - Variables open var drawing: Drawing? { didSet { setNeedsDraw() }} @IBInspectable open var name: String? { didSet { updateDrawing() }} @IBInspectable open var styleKit: String? { didSet { updateDrawing() }} var styleKitClass: AnyClass? { return drawing?.styleKit.paintCodeClass } // MARK: - Frame calculations open var drawnSize: CGSize { return drawInFrameSize } var drawInFrameSize: CGSize { return drawing?.drawnSize ?? frame.size } var drawFrame: CGRect { let drawFrame: CGRect switch contentMode { case .scaleAspectFit, .scaleAspectFill: let widthScale = frame.size.width / drawInFrameSize.width let heightScale = frame.size.height / drawInFrameSize.height let scale: CGFloat if contentMode == .scaleAspectFit { scale = widthScale > heightScale ? heightScale : widthScale } else { scale = widthScale > heightScale ? widthScale : heightScale } let width = drawInFrameSize.width * scale let height = drawInFrameSize.height * scale drawFrame = CGRect(x: (frame.size.width - width) / 2.0, y: (frame.size.height - height) / 2.0, width: width, height: height) case .scaleToFill, .redraw: drawFrame = bounds default: let x: CGFloat let y: CGFloat switch contentMode { case .topLeft, .bottomLeft, .left: x = 0.0 case .topRight, .bottomRight, .right: x = bounds.size.width - drawInFrameSize.width case .center, .top, .bottom: x = (frame.size.width - drawInFrameSize.width) / 2 default: // Should never happen. x = 0.0 } switch contentMode { case .topLeft, .topRight, .top: y = 0.0 case .bottomLeft, .bottomRight, .bottom: y = bounds.size.height - drawInFrameSize.height case .center, .left, .right: y = (frame.size.height - drawInFrameSize.height) / 2 default: // Should never happen. y = 0.0 } drawFrame = CGRect(origin: CGPoint(x: x, y: y), size: drawInFrameSize) } return drawFrame } // MARK: - Module static var classNameComponents: [String] { let fullClassName = NSStringFromClass(self) // Note: String(describing: self) does not include the moduleName prefix. return fullClassName.components(separatedBy: ".") } static var moduleName: String? { let components = classNameComponents return components.count > 1 ? components.first! : nil } static var isSubclass: Bool { // TODO: Dynamic return moduleName != "BFWDrawView" } static var styleKitNameFromModule: String? { // TODO: More robust getting of the framework name. guard isSubclass, let styleKitName = Bundle(for: self) .bundleIdentifier? .components(separatedBy: ".") .last else { return nil } return styleKitName } // MARK: - Update drawing fileprivate func updateDrawing() { // TODO: Call this only once for each stylekit and drawing name pair change. guard let name = name, let styleKitName = styleKit // TODO: If the view exists in a subclass of the stylekit, perhaps default to: ?? type(of: self).styleKitNameFromModule else { return } drawing = StyleKit.drawing(forStyleKitName: styleKitName, drawingName: name) } func setNeedsDraw() { setNeedsDisplay() } // MARK: - Image rendering static var imageCache = [String: UIImage]() fileprivate var cacheKey: String { let components: [String] = [drawing!.name, drawing!.styleKit.name, NSCoder.string(for: frame.size), tintColor.description] let key = components.joined(separator:".") return key } fileprivate func cachedImage(for key: String) -> UIImage? { return type(of: self).imageCache[key] } fileprivate func cache(image: UIImage, for key: String) { type(of: self).imageCache[key] = image } var imageFromView: UIImage? { var image: UIImage? if drawing != nil { if let cachedImage = cachedImage(for: cacheKey) { image = cachedImage } else if let cachedImage = UIImage(of: self, size: bounds.size) { image = cachedImage cache(image: cachedImage, for: cacheKey) } } return image } open var image: UIImage? { return imageFromView } open func writeImage(at scale: CGFloat, isOpaque: Bool, to file: URL) -> Bool { var success = false let directory = file.deletingLastPathComponent() let directoryPath = directory.path if !FileManager.default.fileExists(atPath: directoryPath) { do { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil) success = true } catch { success = false } } else { success = true } if success, let image = image(at: scale, isOpaque: isOpaque) { do { try image.pngData()?.write(to: file, options: Data.WritingOptions.atomic) success = true } catch { success = false } } return success } open func image(at scale: CGFloat, isOpaque: Bool) -> UIImage? { let image: UIImage? if canDraw { let savedContentsScale = contentScaleFactor contentScaleFactor = scale UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, scale) layer.render(in: UIGraphicsGetCurrentContext()!) image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() contentScaleFactor = savedContentsScale } else { image = nil } return image } // MARK: - UIView open override var intrinsicContentSize: CGSize { return drawing?.drawnSize ?? CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric) } open override var tintColor: UIColor! { didSet { setNeedsDraw() } } open override func layoutSubviews() { // layoutSubviews is called when constraints change. Since new constraints might resize this view, we need to redraw. // TODO: only redraw if size actually changed setNeedsDraw() super.layoutSubviews() } open override func draw(_ rect: CGRect) { let _ = draw(parameters: parameters) } } // Introspection extension DrawingView { var parameters: [String] { return drawing?.methodParameters ?? [] } var drawingSelector: Selector? { guard let drawing = self.drawing, let methodName = drawing.methodName else { return nil } return NSSelectorFromString(methodName) } var parametersFunctionTuple: [(parameters: [String], function: Any)] { // TODO: Cache. Make use of it? guard let drawingSelector = drawingSelector, let styleKitClass = styleKitClass else { return [] } return [ ([], { self.drawFunction(from: styleKitClass, selector: drawingSelector) }), (["frame"], { self.drawRectFunction(from: styleKitClass, selector: drawingSelector)!(self.drawFrame) }), (["frame", "tintColor"], { self.drawRectColorFunction(from: styleKitClass, selector: drawingSelector)!(self.drawFrame, self.tintColor) }) ] } @objc var handledParametersArray: [[String]] { return [[], ["frame"], ["frame", "tintColor"]] } var canDraw: Bool { return handledParametersArray.contains(where: { (parameters) -> Bool in parameters == self.parameters }) } @objc func draw(parameters: [String]) -> Bool { guard let drawingSelector = drawingSelector, let styleKitClass = styleKitClass else { return false } var success = true if parameters == [] { if let drawFunction = drawFunction(from: styleKitClass, selector: drawingSelector) { drawFunction() } } else if parameters == ["frame"] { if let drawFunction = drawRectFunction(from: styleKitClass, selector: drawingSelector) { drawFunction(drawFrame) } } else if parameters == ["frame", "tintColor"] { if let drawFunction = drawRectColorFunction(from: styleKitClass, selector: drawingSelector) { drawFunction(drawFrame, tintColor) } } else { debugPrint("**** error: Failed to find a drawing for " + NSStringFromSelector(drawingSelector) + " with parameters [" + parameters.joined(separator: ", ") + "]") success = false } return success } // Similar to: http://codelle.com/blog/2016/2/calling-methods-from-strings-in-swift/ func implementation(for owner: AnyObject, selector: Selector) -> IMP? { let method: Method? if let ownerClass = owner as? AnyClass { method = class_getClassMethod(ownerClass, selector) } else { method = class_getInstanceMethod(type(of: owner), selector) } return method_getImplementation(method!) } func imageFunction(from owner: AnyObject, selector: Selector) -> ((Bool) -> UIImage)? { guard let implementation = self.implementation(for: owner, selector: selector) else { return nil } typealias CFunction = @convention(c) (AnyObject, Selector, Bool) -> Unmanaged<UIImage> let cFunction = unsafeBitCast(implementation, to: CFunction.self) return { bool in cFunction(owner, selector, bool).takeUnretainedValue() } } func drawFunction(from owner: AnyObject, selector: Selector) -> (() -> Void)? { guard let implementation = self.implementation(for: owner, selector: selector) else { return nil } typealias CFunction = @convention(c) (AnyObject, Selector) -> Void let cFunction = unsafeBitCast(implementation, to: CFunction.self) return { cFunction(owner, selector) } } func drawRectFunction(from owner: AnyObject, selector: Selector) -> ((CGRect) -> Void)? { guard let implementation = self.implementation(for: owner, selector: selector) else { return nil } typealias CFunction = @convention(c) (AnyObject, Selector, CGRect) -> Void let cFunction = unsafeBitCast(implementation, to: CFunction.self) return { rect in cFunction(owner, selector, rect) } } func drawRectColorFunction(from owner: AnyObject, selector: Selector) -> ((CGRect, UIColor) -> Void)? { guard let implementation = self.implementation(for: owner, selector: selector) else { return nil } typealias CFunction = @convention(c) (AnyObject, Selector, CGRect, UIColor) -> Void let cFunction = unsafeBitCast(implementation, to: CFunction.self) return { rect, tintColor in cFunction(owner, selector, rect, tintColor) } } }
mit
0405178039fb0ff70d3d03596c915e05
34.259563
149
0.577683
5.129173
false
false
false
false
Mahmoud333/FileManager-Swift
FileManager-Swift/Classes/Utilities.swift
1
1724
// // Utilities.swift // FileManager-Swift // // Created by Algorithm on 7/16/18. // import Foundation internal func printFM(_ msg: String) { print("FileManager: \(msg)") } internal func debugFM(_ msg: String) { print("FM Debug: \(msg)") //NSLog("FM Debug: %@", msg) } //Get File Size func fileSize(fromPath path: String) -> String? { var size: Any? do { size = try FileManager.default.attributesOfItem(atPath: path)[FileAttributeKey.size] } catch (let error) { printFM("File size error: \(error)") return nil } guard let fileSize = size as? UInt64 else { return nil } // bytes if fileSize < 1023 { return String(format: "%lu bytes", CUnsignedLong(fileSize)) } // KB var floatSize = Float(fileSize / 1024) if floatSize < 1023 { return String(format: "%.1f KB", floatSize) } // MB floatSize = floatSize / 1024 if floatSize < 1023 { return String(format: "%.1f MB", floatSize) } // GB floatSize = floatSize / 1024 return String(format: "%.1f GB", floatSize) } //getDirectoryPath func getDirectoryPath() -> String { debugFM("VC getDirectoryPath") let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentsDirectory = paths[0] return documentsDirectory } //get the contents of the file at path func contentsOfDirectoryAtPath(path: String) -> [String]? { debugFM("VC contentsOfDirectoryAtPath") guard let paths = try? FileManager.default.contentsOfDirectory(atPath: path) else { return nil} return paths.map { aContent in (path as NSString).appendingPathComponent(aContent)} }
mit
06d76d5258b9a14d50e73f0d37e1144c
24.352941
99
0.643271
4.204878
false
false
false
false
PureSwift/GATT
Sources/DarwinGATT/DarwinPeripheral.swift
1
24838
// // DarwinPeripheral.swift // GATT // // Created by Alsey Coleman Miller on 4/1/16. // Copyright © 2016 PureSwift. All rights reserved. // #if (os(macOS) || os(iOS)) && canImport(BluetoothGATT) import Foundation import Dispatch import Bluetooth import BluetoothGATT import GATT import CoreBluetooth import CoreLocation public final class DarwinPeripheral: PeripheralManager { // MARK: - Properties /// Logging public var log: ((String) -> ())? public let options: Options public var state: DarwinBluetoothState { get async { return await withUnsafeContinuation { [unowned self] continuation in self.queue.async { [unowned self] in let state = unsafeBitCast(self.peripheralManager.state, to: DarwinBluetoothState.self) continuation.resume(returning: state) } } } } public var willRead: ((GATTReadRequest<Central>) async -> ATTError?)? public var willWrite: ((GATTWriteRequest<Central>) async -> ATTError?)? public var didWrite: ((GATTWriteConfirmation<Central>) async -> ())? private var database = Database() private var peripheralManager: CBPeripheralManager! private var delegate: Delegate! private let queue = DispatchQueue(label: "org.pureswift.DarwinGATT.DarwinPeripheral", attributes: []) private var continuation = Continuation() // MARK: - Initialization public init( options: Options = Options() ) { self.options = options let delegate = Delegate(self) let peripheralManager = CBPeripheralManager( delegate: delegate, queue: queue, options: options.optionsDictionary ) self.delegate = delegate self.peripheralManager = peripheralManager } // MARK: - Methods public func start() async throws { let options = AdvertisingOptions() try await start(options: options) } public func start(options: AdvertisingOptions) async throws { let options = options.optionsDictionary return try await withCheckedThrowingContinuation { [unowned self] continuation in self.queue.async { [unowned self] in self.continuation.startAdvertising = continuation self.peripheralManager.startAdvertising(options) } } } public func stop() { self.queue.async { [unowned self] in peripheralManager.stopAdvertising() } } public func add(service: GATTAttribute.Service) async throws -> UInt16 { let serviceObject = service.toCoreBluetooth() // add service try await withCheckedThrowingContinuation { [unowned self] (continuation: CheckedContinuation<(), Error>) in self.queue.async { [unowned self] in self.continuation.addService = continuation peripheralManager.add(serviceObject) } } // update DB return await withUnsafeContinuation { [unowned self] continuation in self.queue.async { [unowned self] in let handle = database.add(service: service, serviceObject) continuation.resume(returning: handle) } } } public func remove(service handle: UInt16) { self.queue.async { [unowned self] in // remove from daemon let serviceObject = database.service(for: handle) peripheralManager.remove(serviceObject) // remove from cache database.remove(service: handle) } } public func removeAllServices() { self.queue.async { [unowned self] in // remove from daemon peripheralManager.removeAllServices() // clear cache database.removeAll() } } /// Modify the value of a characteristic, optionally emiting notifications if configured on active connections. public func write(_ newValue: Data, forCharacteristic handle: UInt16) async { await withUnsafeContinuation { [unowned self] (continuation: UnsafeContinuation<(), Never>) in self.queue.async { [unowned self] in // update GATT DB database[characteristic: handle] = newValue continuation.resume() } } // send notifications await notify(newValue, forCharacteristic: handle) } /// Read the value of the characteristic with specified handle. public subscript(characteristic handle: UInt16) -> Data { get async { return await withUnsafeContinuation { [unowned self] continuation in self.queue.async { [unowned self] in let value = self.database[characteristic: handle] continuation.resume(returning: value) } } } } /// Return the handles of the characteristics matching the specified UUID. public func characteristics(for uuid: BluetoothUUID) async -> [UInt16] { return await withUnsafeContinuation { [unowned self] continuation in self.queue.async { [unowned self] in let handles = database.characteristics(for: uuid) continuation.resume(returning: handles) } } } // MARK: - Private Methods private func notify(_ value: Data, forCharacteristic handle: UInt16) async { // attempt to write notifications var didNotify = await updateValue(value, forCharacteristic: handle) while didNotify == false { await waitPeripheralReadyUpdateSubcribers() didNotify = await updateValue(value, forCharacteristic: handle) } } private func waitPeripheralReadyUpdateSubcribers() async { await withCheckedContinuation { [unowned self] continuation in self.queue.async { [unowned self] in self.continuation.canNotify = continuation } } } private func updateValue(_ value: Data, forCharacteristic handle: UInt16) async -> Bool { return await withUnsafeContinuation { [unowned self] continuation in self.queue.async { [unowned self] in let characteristicObject = database.characteristic(for: handle) // sends an updated characteristic value to one or more subscribed centrals, via a notification or indication. let didNotify = peripheralManager.updateValue( value, for: characteristicObject, onSubscribedCentrals: nil ) // The underlying transmit queue is full if didNotify == false { // send later in `peripheralManagerIsReady(toUpdateSubscribers:)` method is invoked // when more space in the transmit queue becomes available. //log("Did queue notification for \((characteristic as CBCharacteristic).uuid)") } else { //log("Did send notification for \((characteristic as CBCharacteristic).uuid)") } continuation.resume(returning: didNotify) } } } } // MARK: - Supporting Types public extension DarwinPeripheral { /// Peripheral Peer /// /// Represents a remote peripheral device that has been discovered. struct Central: Peer { public let id: UUID init(_ central: CBCentral) { self.id = central.id } } } public extension DarwinPeripheral { struct Options { public let showPowerAlert: Bool public let restoreIdentifier: String public init( showPowerAlert: Bool = false, restoreIdentifier: String = Bundle.main.bundleIdentifier ?? "org.pureswift.GATT.DarwinPeripheral" ) { self.showPowerAlert = showPowerAlert self.restoreIdentifier = restoreIdentifier } internal var optionsDictionary: [String: Any] { var options = [String: Any](minimumCapacity: 2) if showPowerAlert { options[CBPeripheralManagerOptionShowPowerAlertKey] = showPowerAlert as NSNumber } options[CBPeripheralManagerOptionRestoreIdentifierKey] = self.restoreIdentifier return options } } struct AdvertisingOptions { /// The local name of the peripheral. public let localName: String? /// An array of service UUIDs. public let serviceUUIDs: [BluetoothUUID] #if os(iOS) public let beacon: AppleBeacon? #endif #if os(iOS) public init(localName: String? = nil, serviceUUIDs: [BluetoothUUID] = [], beacon: AppleBeacon? = nil) { self.localName = localName self.beacon = beacon self.serviceUUIDs = serviceUUIDs } #else public init(localName: String? = nil, serviceUUIDs: [BluetoothUUID] = []) { self.localName = localName self.serviceUUIDs = serviceUUIDs } #endif internal var optionsDictionary: [String: Any] { var options = [String: Any](minimumCapacity: 2) if let localName = self.localName { options[CBAdvertisementDataLocalNameKey] = localName } if serviceUUIDs.isEmpty == false { options[CBAdvertisementDataServiceUUIDsKey] = serviceUUIDs.map { CBUUID($0) } } #if os(iOS) if let beacon = self.beacon { let beaconRegion = CLBeaconRegion( uuid: beacon.uuid, major: beacon.major, minor: beacon.minor, identifier: beacon.uuid.uuidString ) let peripheralData = beaconRegion.peripheralData(withMeasuredPower: NSNumber(value: beacon.rssi)) // copy key values peripheralData.forEach { (key, value) in options[key as! String] = value } } #endif return options } } } internal extension DarwinPeripheral { struct Continuation { var startAdvertising: CheckedContinuation<(), Error>? var addService: CheckedContinuation<(), Error>? var canNotify: CheckedContinuation<(), Never>? fileprivate init() { } } } internal extension DarwinPeripheral { @objc(DarwinPeripheralDelegate) final class Delegate: NSObject, CBPeripheralManagerDelegate { unowned let peripheral: DarwinPeripheral init(_ peripheral: DarwinPeripheral) { self.peripheral = peripheral } private func log(_ message: String) { peripheral.log?(message) } // MARK: - CBPeripheralManagerDelegate @objc(peripheralManagerDidUpdateState:) public func peripheralManagerDidUpdateState(_ peripheralManager: CBPeripheralManager) { let state = unsafeBitCast(peripheralManager.state, to: DarwinBluetoothState.self) log("Did update state \(state)") //stateChanged(state) } @objc(peripheralManager:willRestoreState:) public func peripheralManager(_ peripheralManager: CBPeripheralManager, willRestoreState state: [String : Any]) { log("Will restore state \(state)") } @objc(peripheralManagerDidStartAdvertising:error:) public func peripheralManagerDidStartAdvertising(_ peripheralManager: CBPeripheralManager, error: Error?) { if let error = error { log("Could not advertise (\(error))") self.peripheral.continuation.startAdvertising?.resume(throwing: error) } else { log("Did start advertising") self.peripheral.continuation.startAdvertising?.resume() } } @objc(peripheralManager:didAddService:error:) public func peripheralManager(_ peripheralManager: CBPeripheralManager, didAdd service: CBService, error: Error?) { if let error = error { log("Could not add service \(service.uuid) (\(error))") self.peripheral.continuation.addService?.resume(throwing: error) } else { log("Added service \(service.uuid)") self.peripheral.continuation.addService?.resume() } } @objc(peripheralManager:didReceiveReadRequest:) public func peripheralManager(_ peripheralManager: CBPeripheralManager, didReceiveRead request: CBATTRequest) { log("Did receive read request for \(request.characteristic.uuid)") let peer = Central(request.central) let characteristic = self.peripheral.database[characteristic: request.characteristic] let uuid = BluetoothUUID(request.characteristic.uuid) let value = characteristic.value let readRequest = GATTReadRequest( central: peer, maximumUpdateValueLength: request.central.maximumUpdateValueLength, uuid: uuid, handle: characteristic.handle, value: value, offset: request.offset ) guard request.offset <= value.count else { peripheralManager.respond(to: request, withResult: .invalidOffset) return } Task { if let error = await self.peripheral.willRead?(readRequest) { peripheral.queue.async { peripheralManager.respond(to: request, withResult: CBATTError.Code(rawValue: Int(error.rawValue))!) } return } peripheral.queue.async { let requestedValue = request.offset == 0 ? value : Data(value.suffix(request.offset)) request.value = requestedValue peripheralManager.respond(to: request, withResult: .success) } } } @objc(peripheralManager:didReceiveWriteRequests:) public func peripheralManager(_ peripheralManager: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { log("Did receive write requests for \(requests.map { $0.characteristic.uuid })") assert(requests.isEmpty == false) Task { var writeRequests = [GATTWriteRequest<Central>]() writeRequests.reserveCapacity(requests.count) // validate write requests for request in requests { let peer = Central(request.central) let characteristic = self.peripheral.database[characteristic: request.characteristic] let value = characteristic.value let uuid = BluetoothUUID(request.characteristic.uuid) let newValue = request.value ?? Data() let writeRequest = GATTWriteRequest( central: peer, maximumUpdateValueLength: request.central.maximumUpdateValueLength, uuid: uuid, handle: characteristic.handle, value: value, newValue: newValue ) // check if write is possible if let error = await self.peripheral.willWrite?(writeRequest) { peripheral.queue.async { peripheralManager.respond(to: requests[0], withResult: CBATTError.Code(rawValue: Int(error.rawValue))!) } return } // compute new data writeRequests.append(writeRequest) } // write new values for request in writeRequests { // update GATT DB self.peripheral.database[characteristic: request.handle] = request.newValue let confirmation = GATTWriteConfirmation( central: request.central, maximumUpdateValueLength: request.maximumUpdateValueLength, uuid: request.uuid, handle: request.handle, value: request.newValue ) // did write callback await self.peripheral.didWrite?(confirmation) } peripheral.queue.async { peripheralManager.respond(to: requests[0], withResult: .success) } } } @objc(peripheralManager:central:didSubscribeToCharacteristic:) public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) { log("Central \(central.id) did subscribe to \(characteristic.uuid)") } @objc public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) { log("Central \(central.id) did unsubscribe from \(characteristic.uuid)") } @objc public func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) { log("Ready to send notifications") self.peripheral.continuation.canNotify?.resume() } } } private extension DarwinPeripheral { struct Database { struct Service { let handle: UInt16 } struct Characteristic { let handle: UInt16 let serviceHandle: UInt16 var value: Data } private var services = [CBMutableService: Service]() private var characteristics = [CBMutableCharacteristic: Characteristic]() /// Do not access directly, use `newHandle()` private var lastHandle: UInt16 = 0x0000 /// Simulate a GATT database. private mutating func newHandle() -> UInt16 { assert(lastHandle != .max) // starts at 0x0001 lastHandle += 1 return lastHandle } mutating func add(service: GATTAttribute.Service, _ coreService: CBMutableService) -> UInt16 { let serviceHandle = newHandle() services[coreService] = Service(handle: serviceHandle) for (index, characteristic) in ((coreService.characteristics ?? []) as! [CBMutableCharacteristic]).enumerated() { let data = service.characteristics[index].value let characteristicHandle = newHandle() characteristics[characteristic] = Characteristic(handle: characteristicHandle, serviceHandle: serviceHandle, value: data) } return serviceHandle } mutating func remove(service handle: UInt16) { let coreService = service(for: handle) // remove service services[coreService] = nil (coreService.characteristics as? [CBMutableCharacteristic])?.forEach { characteristics[$0] = nil } // remove characteristics while let index = characteristics.firstIndex(where: { $0.value.serviceHandle == handle }) { characteristics.remove(at: index) } } mutating func removeAll() { services.removeAll() characteristics.removeAll() } /// Find the service with the specified handle func service(for handle: UInt16) -> CBMutableService { guard let coreService = services.first(where: { $0.value.handle == handle })?.key else { fatalError("Invalid handle \(handle)") } return coreService } /// Return the handles of the characteristics matching the specified UUID. func characteristics(for uuid: BluetoothUUID) -> [UInt16] { let characteristicUUID = CBUUID(uuid) return characteristics .filter { $0.key.uuid == characteristicUUID } .map { $0.value.handle } } func characteristic(for handle: UInt16) -> CBMutableCharacteristic { guard let characteristic = characteristics.first(where: { $0.value.handle == handle })?.key else { fatalError("Invalid handle \(handle)") } return characteristic } subscript(characteristic handle: UInt16) -> Data { get { guard let value = characteristics.values.first(where: { $0.handle == handle })?.value else { fatalError("Invalid handle \(handle)") } return value } set { guard let key = characteristics.first(where: { $0.value.handle == handle })?.key else { fatalError("Invalid handle \(handle)") } characteristics[key]?.value = newValue } } subscript(characteristic uuid: BluetoothUUID) -> Data { get { let characteristicUUID = CBUUID(uuid) guard let characteristic = characteristics.first(where: { $0.key.uuid == characteristicUUID })?.value else { fatalError("Invalid UUID \(uuid)") } return characteristic.value } set { let characteristicUUID = CBUUID(uuid) guard let key = characteristics.keys.first(where: { $0.uuid == characteristicUUID }) else { fatalError("Invalid UUID \(uuid)") } characteristics[key]?.value = newValue } } private(set) subscript(characteristic characteristic: CBCharacteristic) -> Characteristic { get { guard let key = characteristic as? CBMutableCharacteristic else { fatalError("Invalid key") } guard let value = characteristics[key] else { fatalError("No stored characteristic matches \(characteristic)") } return value } set { guard let key = characteristic as? CBMutableCharacteristic else { fatalError("Invalid key") } characteristics[key] = newValue } } subscript(data characteristic: CBCharacteristic) -> Data { get { guard let key = characteristic as? CBMutableCharacteristic else { fatalError("Invalid key") } guard let cache = characteristics[key] else { fatalError("No stored characteristic matches \(characteristic)") } return cache.value } set { self[characteristic: characteristic].value = newValue } } } } #endif
mit
26d621fdba1bb269661d211dfc066d93
35.578792
147
0.545154
6.24359
false
false
false
false
jonnguy/HSTracker
HSTracker/Logging/LogLine.swift
1
4108
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 13/02/16. */ import Foundation import RegexUtil class LogDateFormatter: DateFormatter { private static let subsecRegex: RegexPattern = "(S+)" func string(from date: LogDate) -> String { var str = self.string(from: date.date) let matches = self.dateFormat.matches(LogDateFormatter.subsecRegex) for match in matches { let len = match.value.count let rcen = 10^^(7-len) let roundedss = (date.subseconds + (rcen/2))/rcen * rcen let subsecstr = String(format: "%07d", roundedss).substring(from: 0, to: len) str.replaceSubrange(match.range, with: subsecstr) } return str } func date(from str: String) -> LogDate? { if let d: Date = self.date(from: str) { return LogDate(date: d) } return nil } } struct LogDate: Comparable, Equatable { fileprivate let date: Date let subseconds: Int var timeIntervalSinceNow: TimeInterval { return date.timeIntervalSinceNow } var hour: Int { return self.date.hour } var minute: Int { return self.date.minute } var second: Int { return self.date.second } init() { self.init(date: Date()) } init(date: Date, subseconds: Int = 0) { self.date = date self.subseconds = subseconds } init(stringcomponents: [String]) { var d: Date = Date() var subsec: Int = 0 if stringcomponents.count > 0 { LogLine.dateStringFormatter.defaultDate = LogLine.DateNoTime(date: d) if let date = LogLine.dateStringFormatter.date(from: stringcomponents[0]) { d = date } if stringcomponents.count > 1 { if let ss = Int(stringcomponents[1]) { subsec = ss } } } self.init(date: d, subseconds: subsec) } static func < (lhs: LogDate, rhs: LogDate) -> Bool { if lhs.date != rhs.date { return lhs.date < rhs.date } else { return lhs.subseconds < rhs.subseconds } } static func LogDateByAdding(component: Calendar.Component, value: Int, to date: LogDate, from calendar: Calendar ) -> LogDate { if let datePlusOne = calendar.date(byAdding: component, value: value, to: date.date) { return LogDate(date: datePlusOne, subseconds: date.subseconds) } else { return date } } } struct LogLine { let namespace: LogLineNamespace let time: LogDate let content: String let line: String @nonobjc fileprivate static let dateStringFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "HH:mm:ss" formatter.timeZone = TimeZone.current return formatter }() @nonobjc private static let trimFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = DateFormatter.Style.none formatter.dateStyle = DateFormatter.Style.short return formatter }() static func DateNoTime(date: Date) -> Date { let str = LogLine.trimFormatter.string(from: date) // 12/15/16 return LogLine.trimFormatter.date(from: str)! } init(namespace: LogLineNamespace, line: String) { self.namespace = namespace self.line = line if line.count <= 20 { self.time = LogDate() self.content = "" return } let linecomponents = line.components(separatedBy: " ") if linecomponents.count < 3 { self.time = LogDate() self.content = "" return } // parse time let timecomponents = linecomponents[1].components(separatedBy: ".") var _time = LogDate(stringcomponents: timecomponents) if _time > LogDate() { _time = LogDate.LogDateByAdding(component: .day, value: -1, to: _time, from: LogReaderManager.calendar) } self.time = _time self.content = linecomponents[2..<linecomponents.count].joined(separator: " ") } } extension LogLine: CustomStringConvertible { var description: String { let dateStr = LogReaderManager.fullDateStringFormatter.string(from: self.time) return "\(namespace): \(dateStr): \(content)" } }
mit
fa8f70f1884e6c0ee11527906a9a38b5
23.164706
106
0.685492
3.41196
false
false
false
false
panyam/SwiftIO
Sources/CFSocketServer.swift
1
6281
// // This source file is part of the Swiftli open source http2.0 server project // // Copyright (c) 2015-2016 Sriram Panyam // Licensed under Apache License v2.0 with Runtime Library Exception // // //===----------------------------------------------------------------------===// // // This file implements a server transport and runloop on top of CFSocketNativeHandle. // //===----------------------------------------------------------------------===// import Foundation import Darwin // //#if os(Linux) // import SwiftGlibc //#endif let DEFAULT_SERVER_PORT : UInt16 = 9999 private func handleConnectionAccept(socket: CFSocket!, callbackType: CFSocketCallBackType, address: CFData!, data: UnsafePointer<Void>, info: UnsafeMutablePointer<Void>) { if (callbackType == CFSocketCallBackType.AcceptCallBack) { let socketTransport = Unmanaged<CFSocketServer>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() let clientSocket = UnsafePointer<CFSocketNativeHandle>(data) let clientSocketNativeHandle = clientSocket[0] socketTransport.handleConnection(clientSocketNativeHandle); } } public class CFSocketServer : StreamServer { /** * Option to ignore a request if header's exceed this length> */ private var isRunning = false private var stopped = false public var serverPort : UInt16 = DEFAULT_SERVER_PORT public var serverPortV6 : UInt16 = DEFAULT_SERVER_PORT private var serverSocket : CFSocket? private var serverSocketV6 : CFSocket? public var streamHandler : StreamHandler? private var serverRunLoop : CFRunLoop public init(var _ runLoop : CFRunLoop?) { if runLoop == nil { runLoop = CFRunLoopGetCurrent(); } serverRunLoop = runLoop! } public func start() -> ErrorType? { if isRunning { NSLog("Server is already running") return nil } NSLog("Registered server") isRunning = true if let error = initSocket() { return error } // if let error = initSocketV6() { // return error // } return nil } public func stop() { CFSocketInvalidate(serverSocket) } func handleConnection(clientSocketNativeHandle : CFSocketNativeHandle) { let clientStream = CFSocketClient(clientSocketNativeHandle, runLoop: serverRunLoop) streamHandler?.handleStream(clientStream) } private func initSocket() -> SocketErrorType? { let (socket, error) = createSocket(serverPort, isV6: false) serverSocket = socket return error } private func initSocketV6() -> SocketErrorType? { let (socket, error) = createSocket(serverPort, isV6: true) serverSocketV6 = socket return error } private func createSocket(port: UInt16, isV6: Bool) -> (CFSocket?, SocketErrorType?) { var socketContext = CFSocketContext(version: 0, info: self.asUnsafeMutableVoid(), retain: nil, release: nil, copyDescription: nil) var outSocket : CFSocket? = nil; var error : SocketErrorType? = nil withUnsafePointer(&socketContext) { if isV6 { outSocket = CFSocketCreate(kCFAllocatorDefault, PF_INET6, 0, 0, 2, handleConnectionAccept, UnsafePointer<CFSocketContext>($0)); } else { outSocket = CFSocketCreate(kCFAllocatorDefault, PF_INET, 0, 0, 2, handleConnectionAccept, UnsafePointer<CFSocketContext>($0)); } let nativeSocket = CFSocketGetNative(outSocket) var sock_opt_on = Int32(1) setsockopt(nativeSocket, SOL_SOCKET, SO_REUSEADDR, &sock_opt_on, socklen_t(sizeofValue(sock_opt_on))) setsockopt(nativeSocket, SOL_SOCKET, SO_REUSEPORT, &sock_opt_on, socklen_t(sizeofValue(sock_opt_on))) var sincfd : CFData? if isV6 { var sin6 = sockaddr_in6(); sin6.sin6_len = UInt8(sizeof(sockaddr_in6)); sin6.sin6_family = sa_family_t(AF_INET6); sin6.sin6_port = UInt16(port).bigEndian sin6.sin6_addr = in6addr_any; let sin6_len = sizeof(sockaddr_in) withUnsafePointer(&sin6) { sincfd = CFDataCreate( kCFAllocatorDefault, UnsafePointer($0), sin6_len); } } else { var sin = sockaddr_in(); sin.sin_len = UInt8(sizeof(sockaddr_in)); sin.sin_family = sa_family_t(AF_INET); sin.sin_port = UInt16(port).bigEndian sin.sin_addr.s_addr = 0 let sin_len = sizeof(sockaddr_in) withUnsafePointer(&sin) { sincfd = CFDataCreate( kCFAllocatorDefault, UnsafePointer($0), sin_len); } } let err = CFSocketSetAddress(outSocket, sincfd); if err != CFSocketError.Success { error = SocketErrorType(message: "Unable to set address on socket") let errstr : String? = String.fromCString(strerror(errno)); NSLog ("Socket Set Address Error: \(err.rawValue), \(errno), \(errstr)") CFSocketInvalidate(outSocket) exit(1) } } if error == nil { let flags = CFSocketGetSocketFlags(outSocket) CFSocketSetSocketFlags(outSocket, flags | kCFSocketAutomaticallyReenableAcceptCallBack) let socketSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, outSocket, 0) CFRunLoopAddSource(serverRunLoop, socketSource, kCFRunLoopDefaultMode) } return (outSocket, error) } private func asUnsafeMutableVoid() -> UnsafeMutablePointer<Void> { let selfAsOpaque = Unmanaged<CFSocketServer>.passUnretained(self).toOpaque() let selfAsVoidPtr = UnsafeMutablePointer<Void>(selfAsOpaque) return selfAsVoidPtr } }
apache-2.0
b8eee9b97d5b131aa9ffe3d4a75b5991
34.891429
143
0.582391
4.949567
false
false
false
false
taewan0530/TWKit
Pod/attributedString/String+AttributedString.swift
1
2540
// // String+AttributedString.swift // TWKitDemo // // Created by kimtaewan on 2016. 4. 29.. // Copyright © 2016년 taewan. All rights reserved. // import UIKit public let TWKitUIImageAttributeName: String = "TWKitUIImageAttributeName" public let TWKitUIImageOffsetYAttributeName: String = "TWKitUIImageOffsetYAttributeName" public extension String { public func toAttributedString(_ attrs: [String: [String: Any]]) -> NSAttributedString { let searchAttr = NSMutableAttributedString(string: self) var replacesOffset = 0 for (key, value) in attrs { let ranges = searchAttr.string.rangesOfString(searchString: key) for range in ranges { //이미지를 포함하고 있는건 리플레이스! if let image = value[TWKitUIImageAttributeName] as? UIImage { let imageSize = image.size var bounds = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height) let newRange = NSMakeRange(range.location - replacesOffset, range.length) //x는 적용해도 반응이 없네. bounds.origin.y -= value[TWKitUIImageOffsetYAttributeName] as? CGFloat ?? 0 let attachment = NSTextAttachment() attachment.image = image attachment.bounds = bounds let imageAttrString = NSAttributedString(attachment: attachment) searchAttr.replaceCharacters(in: newRange, with: imageAttrString) //range를 미리 가져오기때문에 offset으로 밀어내준다. replacesOffset += range.length - 1 } else { searchAttr.addAttributes(value, range: range) } } replacesOffset = 0 } return searchAttr } public func rangesOfString(searchString: String, options mask: NSString.CompareOptions = .literal) -> [NSRange] { let nsStr = self as NSString var results = [NSRange]() var searchRange = NSMakeRange(0, nsStr.length) var range = nsStr.range(of: searchString, options: mask, range: searchRange) while range.location != NSNotFound { results.append(range) searchRange = NSMakeRange(NSMaxRange(range), nsStr.length - NSMaxRange(range)) range = nsStr.range(of: searchString, options: mask, range: searchRange) } return results } }
mit
362889d51ab7fc79f932435ca48cd185
36.707692
117
0.605467
4.695402
false
false
false
false
Snowgan/XLRefreshSwift
Example/XLRefreshSwift/ViewController.swift
1
1737
// // ViewController.swift // XLRefreshSwift // // Created by Snowgan on 04/14/2016. // Copyright (c) 2016 Snowgan. All rights reserved. // import UIKit import XLRefreshSwift class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var dataArr = ["d", "e", "f", "g", "h", "i", "j", "k", "l"] override func viewDidLoad() { super.viewDidLoad() tableView.xlheader = XLRefreshHeader(action: { self.dataArr.insert("a", atIndex: 0) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)*2)), dispatch_get_main_queue(), { self.tableView.reloadData() self.tableView.endHeaderRefresh() }) }) tableView.xlfooter = XLRefreshFooter(action: { self.dataArr.append("m") dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)*2)), dispatch_get_main_queue(), { self.tableView.reloadData() self.tableView.endFooterRefresh() }) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArr.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") cell?.textLabel?.text = dataArr[indexPath.row] return cell! } }
mit
edcd90d27442409c169c399b147e254c
30.017857
120
0.609672
4.632
false
false
false
false
eeschimosu/EasyTipView
Project/EasyTipView/EasyTipView/EasyTipView.swift
11
15439
// // EasyTipView.swift // EasyTipView // // Created by Teodor Patras on 25.03.15. // Copyright (c) 2015 Teodor Patras. All rights reserved. // import UIKit @objc protocol EasyTipViewDelegate { func easyTipViewDidDismiss(tipView : EasyTipView) } class EasyTipView: UIView, Printable { // MARK:- Nested types - enum ArrowPosition { case Top case Bottom } struct Preferences { var systemFontSize : CGFloat = 15 var textColor : UIColor = UIColor.whiteColor() var bubbleColor : UIColor = UIColor.redColor() var arrowPosition : ArrowPosition = .Bottom var font : UIFont? var textAlignment : NSTextAlignment = NSTextAlignment.Center } // MARK:- Constants - private struct Constants { static let arrowHeight : CGFloat = 5 static let arrowWidth : CGFloat = 10 static let bubbleHInset : CGFloat = 10 static let bubbleVInset : CGFloat = 1 static let textHInset : CGFloat = 10 static let textVInset : CGFloat = 5 static let bubbleCornerRadius : CGFloat = 5 static let maxWidth : CGFloat = 200 } // MARK:- Variables - override var backgroundColor : UIColor? { didSet { if let color = backgroundColor { if color != UIColor.clearColor() { self.preferences.bubbleColor = color backgroundColor = UIColor.clearColor() } } } } override var description : String { let type = _stdlib_getDemangledTypeName(self).componentsSeparatedByString(".").last! return "<< \(type) with text : '\(self.text)' >>" } private weak var presentingView : UIView? private var arrowTip = CGPointZero private var preferences : Preferences weak var delegate : EasyTipViewDelegate? private let font : UIFont private let text : NSString private lazy var textSize : CGSize = { [unowned self] in var attributes : [NSObject : AnyObject] = [NSFontAttributeName : self.font] var textSize = self.text.boundingRectWithSize(CGSizeMake(EasyTipView.Constants.maxWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).size textSize.width = ceil(textSize.width) textSize.height = ceil(textSize.height) if textSize.width < EasyTipView.Constants.arrowWidth { textSize.width = EasyTipView.Constants.arrowWidth } return textSize }() private lazy var contentSize : CGSize = { [unowned self] in var contentSize = CGSizeMake(self.textSize.width + Constants.textHInset * 2 + Constants.bubbleHInset * 2, self.textSize.height + Constants.textVInset * 2 + Constants.bubbleVInset * 2 + Constants.arrowHeight) return contentSize }() // MARK:- Static preferences - private struct GlobalPreferences { private static var preferences : Preferences = Preferences() } class func setGlobalPreferences (preferences : Preferences) { GlobalPreferences.preferences = preferences } class func globalPreferences() -> Preferences { return GlobalPreferences.preferences } // MARK:- Initializer - init (text : NSString, preferences: Preferences?, delegate : EasyTipViewDelegate?){ self.text = text if let p = preferences { self.preferences = p } else { self.preferences = EasyTipView.GlobalPreferences.preferences } if let font = self.preferences.font { self.font = font }else{ self.font = UIFont.systemFontOfSize(self.preferences.systemFontSize) } self.delegate = delegate super.init(frame : CGRectZero) self.backgroundColor = UIColor.clearColor() NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleRotation", name: UIDeviceOrientationDidChangeNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func handleRotation () { if let view = self.presentingView, sview = self.superview { UIView.animateWithDuration(0.3, animations: { () -> Void in self.arrangeInSuperview(sview) self.setNeedsDisplay() }) } } /** NSCoding not supported. Use init(text, preferences, delegate) instead! */ required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported. Use init(text, preferences, delegate) instead!") } // MARK:- Class functions - class func showAnimated(animated : Bool, forView view : UIView, withinSuperview superview : UIView?, text : NSString, preferences: Preferences?, delegate : EasyTipViewDelegate?){ var ev = EasyTipView(text: text, preferences : preferences, delegate : delegate) ev.showForView(view, withinSuperview: superview, animated: animated) } class func showAnimated(animated : Bool, forItem item : UIBarButtonItem, withinSuperview superview : UIView?, text : NSString, preferences: Preferences?, delegate : EasyTipViewDelegate?){ if let view = item.customView { self.showAnimated(animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) }else{ if let view = item.valueForKey("view") as? UIView { self.showAnimated(animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) } } } // MARK:- Instance methods - func showForItem(item : UIBarButtonItem, withinSuperView sview : UIView?, animated : Bool) { if let view = item.customView { self.showForView(view, withinSuperview: sview, animated : animated) }else{ if let view = item.valueForKey("view") as? UIView { self.showForView(view, withinSuperview: sview, animated: animated) } } } func showForView(view : UIView, withinSuperview sview : UIView?, animated : Bool) { if let v = sview { assert(view.hasSuperview(v), "The supplied superview <\(v)> is not a direct nor an indirect superview of the supplied reference view <\(view)>. The superview passed to this method should be a direct or an indirect superview of the reference view. To display the tooltip on the window, pass nil as the superview parameter.") } let superview = sview ?? UIApplication.sharedApplication().windows.last as! UIView self.presentingView = view self.arrangeInSuperview(superview) self.transform = CGAffineTransformMakeScale(0, 0) var tap = UITapGestureRecognizer(target: self, action: "handleTap") self.addGestureRecognizer(tap) superview.addSubview(self) if animated { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.transform = CGAffineTransformIdentity }, completion: nil) }else{ self.transform = CGAffineTransformIdentity } } private func arrangeInSuperview(superview : UIView) { let position = self.preferences.arrowPosition let refViewOrigin = self.presentingView!.originWithinDistantSuperView(superview) let refViewSize = self.presentingView!.frame.size let refViewCenter = CGPointMake(refViewOrigin.x + refViewSize.width / 2, refViewOrigin.y + refViewSize.height / 2) let xOrigin = refViewCenter.x - self.contentSize.width / 2 let yOrigin = position == .Bottom ? refViewOrigin.y - self.contentSize.height : refViewOrigin.y + refViewSize.height var frame = CGRectMake(xOrigin, yOrigin, self.contentSize.width, self.contentSize.height) if frame.origin.x < 0 { frame.origin.x = 0 } else if CGRectGetMaxX(frame) > CGRectGetWidth(superview.frame){ frame.origin.x = superview.frame.width - CGRectGetWidth(frame) } if position == .Top { if CGRectGetMaxY(frame) > CGRectGetHeight(superview.frame){ self.preferences.arrowPosition = .Bottom frame.origin.y = refViewOrigin.y - self.contentSize.height } }else{ if CGRectGetMinY(frame) < 0 { self.preferences.arrowPosition = .Top frame.origin.y = refViewOrigin.y + refViewSize.height } } self.arrowTip = CGPointMake(abs(frame.origin.x - refViewOrigin.x) + refViewSize.width / 2, self.preferences.arrowPosition == .Top ? Constants.bubbleVInset : self.contentSize.height - Constants.bubbleVInset) self.frame = frame } func dismissWithCompletion(completion : ((finished : Bool) -> Void)?){ UIView.animateWithDuration(0.2, animations: { () -> Void in self.transform = CGAffineTransformMakeScale(0.3, 0.3) self.alpha = 0 }) { (finished) -> Void in completion?(finished: finished) self.removeFromSuperview() } } // MARK:- Callbacks - func handleTap () { self.dismissWithCompletion { (finished) -> Void in self.delegate?.easyTipViewDidDismiss(self) } } // MARK:- Drawing - override func drawRect(rect: CGRect) { let bubbleWidth = self.contentSize.width - 2 * Constants.bubbleHInset let bubbleHeight = self.contentSize.height - 2 * Constants.bubbleVInset - Constants.arrowHeight let arrowPosition = self.preferences.arrowPosition let bubbleXOrigin = Constants.bubbleHInset let bubbleYOrigin = arrowPosition == .Bottom ? Constants.bubbleVInset : Constants.bubbleVInset + Constants.arrowHeight let context = UIGraphicsGetCurrentContext() CGContextSaveGState (context) var contourPath = CGPathCreateMutable() CGPathMoveToPoint(contourPath, nil, self.arrowTip.x, self.arrowTip.y) CGPathAddLineToPoint(contourPath, nil, self.arrowTip.x - Constants.arrowWidth / 2, self.arrowTip.y + (arrowPosition == .Bottom ? -1 : 1) * Constants.arrowHeight) if arrowPosition == .Top { CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin, bubbleYOrigin, bubbleXOrigin, bubbleYOrigin + bubbleHeight, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin, bubbleYOrigin + bubbleHeight, bubbleXOrigin + bubbleWidth, bubbleYOrigin + bubbleHeight, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin + bubbleWidth, bubbleYOrigin + bubbleHeight, bubbleXOrigin + bubbleWidth, bubbleYOrigin, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin + bubbleWidth, bubbleYOrigin, bubbleXOrigin, bubbleYOrigin, Constants.bubbleCornerRadius) } else { CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin, bubbleYOrigin + bubbleHeight, bubbleXOrigin, bubbleYOrigin, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin, bubbleYOrigin, bubbleXOrigin + bubbleWidth, bubbleYOrigin, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin + bubbleWidth, bubbleYOrigin, bubbleXOrigin + bubbleWidth, bubbleYOrigin + bubbleHeight, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin + bubbleWidth, bubbleYOrigin + bubbleHeight, bubbleXOrigin, bubbleYOrigin + bubbleHeight, Constants.bubbleCornerRadius) } CGPathAddLineToPoint(contourPath, nil, self.arrowTip.x + Constants.arrowWidth / 2, self.arrowTip.y + (arrowPosition == .Bottom ? -1 : 1) * Constants.arrowHeight) CGPathCloseSubpath(contourPath) CGContextAddPath(context, contourPath) CGContextClip(context) CGContextSetFillColorWithColor(context, self.preferences.bubbleColor.CGColor) CGContextFillRect(context, self.bounds) var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = self.preferences.textAlignment paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping var textRect = CGRectMake(bubbleXOrigin + (bubbleWidth - self.textSize.width) / 2, bubbleYOrigin + (bubbleHeight - self.textSize.height) / 2, textSize.width, textSize.height) self.text.drawInRect(textRect, withAttributes: [NSFontAttributeName : self.font, NSForegroundColorAttributeName : self.preferences.textColor, NSParagraphStyleAttributeName : paragraphStyle]) CGContextRestoreGState(context) } } // MARK:- UIView extension - private extension UIView { func originWithinDistantSuperView (superview : UIView?) -> CGPoint { if self.superview != nil { return viewOriginInSuperview(self.superview!, subviewOrigin: self.frame.origin, refSuperview : superview) }else{ return self.frame.origin } } func hasSuperview (superview : UIView) -> Bool{ return viewHasSuperview(self, superview: superview) } func viewHasSuperview (view : UIView, superview : UIView) -> Bool { if let sview = view.superview { if sview === superview { return true }else{ return viewHasSuperview(sview, superview: superview) } }else{ return false } } func viewOriginInSuperview(sview : UIView, subviewOrigin sorigin: CGPoint, refSuperview : UIView?) -> CGPoint { if let superview = sview.superview { if let ref = refSuperview { if sview === ref { return sorigin }else{ return viewOriginInSuperview(superview, subviewOrigin: CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y), refSuperview: ref) } }else{ return viewOriginInSuperview(superview, subviewOrigin: CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y), refSuperview: nil) } }else{ return CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y) } } }
mit
ae31551bb99ba3bd95eb0573fb200b0d
39.524934
335
0.621219
5.531709
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/InteractiveNotifications/MessageAlert/InteractiveMessageAlertController.swift
1
6243
import UIKit class InteractiveMessageAlertController: UIViewController { private static let buttonHeight : CGFloat = 50 private static let alertWidth : CGFloat = 270 private static let maxImageHeight : CGFloat = 180 private static let tapOutsideToDismissEnabled = true @IBOutlet weak var alertMaskBackground: UIImageView! @IBOutlet weak var shadowView: UIView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var imageView: LoadingImageView! @IBOutlet weak var headerViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var alertTitle: UILabel! @IBOutlet weak var alertText: UILabel! @IBOutlet weak var alertActionStackView: UIStackView! @IBOutlet weak var alertStackViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var titleAndMessageSpace: NSLayoutConstraint! private let titleText: String? private let messageText: String private let imageURL: URL? private let image: Image? private var buttons: [InteractiveMessageButton]! var actionHandler: ((MMNotificationAction) -> Void)? var dismissHandler: (() -> Void)? init(titleText: String?, messageText: String, imageURL: URL?, image: Image?, dismissTitle: String?, openTitle: String?, actionHandler: ((MMNotificationAction) -> Void)? = nil) { self.titleText = titleText self.messageText = messageText self.imageURL = imageURL self.image = image self.actionHandler = actionHandler super.init(nibName: "AlertController", bundle: MobileMessaging.resourceBundle) self.buttons = { let openAction = openTitle != nil ? MMNotificationAction.openAction(title: openTitle!) : MMNotificationAction.openAction() let dismissAction = dismissTitle != nil ? MMNotificationAction.dismissAction(title: dismissTitle!) : MMNotificationAction.dismissAction() let actions = [dismissAction, openAction] let ret = actions.map { action in return InteractiveMessageButton(title: action.title, style: action.options.contains(.destructive) ? .destructive : .default, isBold: action.identifier == MMNotificationAction.DefaultActionId, handler: { self.dismissAndPerformAction(action) }) } return ret }() self.modalPresentationStyle = UIModalPresentationStyle.overFullScreen self.modalTransitionStyle = UIModalTransitionStyle.crossDissolve } init(titleText: String?, messageText: String, imageURL: URL?, image: Image?, category: MMNotificationCategory, actionHandler: ((MMNotificationAction) -> Void)? = nil) { self.titleText = titleText self.messageText = messageText self.imageURL = imageURL self.image = image self.actionHandler = actionHandler super.init(nibName: "AlertController", bundle: MobileMessaging.resourceBundle) self.buttons = { let ret = category.actions.map { action in return InteractiveMessageButton( title: action.title, style: action.options.contains(.destructive) ? .destructive : .default, isBold: action.identifier == "mm_accept", handler: { self.dismissAndPerformAction(action) }) } return ret }() self.modalPresentationStyle = UIModalPresentationStyle.overFullScreen self.modalTransitionStyle = UIModalTransitionStyle.crossDissolve } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() containerView.layer.cornerRadius = 12 containerView.layer.masksToBounds = true setupImageView() setupTitle() alertText.text = messageText setShadowAlertView() addButtons(actions: buttons) if InteractiveMessageAlertController.tapOutsideToDismissEnabled { alertMaskBackground.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(InteractiveMessageAlertController.dismissAction(_:)))) } } //MARK: Private private func addButtons(actions: [InteractiveMessageButton]){ buttons.forEach { button in alertActionStackView.addArrangedSubview(button) if alertActionStackView.arrangedSubviews.count > 2 { alertStackViewHeightConstraint.constant = InteractiveMessageAlertController.buttonHeight * CGFloat(alertActionStackView.arrangedSubviews.count) alertActionStackView.axis = .vertical } else { alertStackViewHeightConstraint.constant = InteractiveMessageAlertController.buttonHeight alertActionStackView.axis = .horizontal } } } private func dismissAndPerformAction(_ action: MMNotificationAction) { dismiss(animated: true, completion: { self.dismissHandler?() self.actionHandler?(action) }) } @objc private func dismissAction(_ sender: InteractiveMessageButton){ dismissAndPerformAction(MMNotificationAction.dismissAction()) } private func setShadowAlertView(){ shadowView.layer.cornerRadius = 12 shadowView.layer.shadowOffset = CGSize.zero shadowView.layer.shadowRadius = 8 shadowView.layer.shadowOpacity = 0.4 } private func setupImageView() { guard imageURL != nil || image != nil else { headerViewHeightConstraint.constant = 0 return } if let imageURL = imageURL { imageView.loadImage(withURL: imageURL, width: InteractiveMessageAlertController.alertWidth, height: InteractiveMessageAlertController.maxImageHeight, completion: { _, _ in if let height = self.imageView.imageSize(width: InteractiveMessageAlertController.alertWidth, height: InteractiveMessageAlertController.maxImageHeight)?.height { self.headerViewHeightConstraint.constant = height } }) } else if let img = image { self.headerViewHeightConstraint.constant = imageHeight(image: img) imageView.contentImageView.contentMode = .scaleAspectFill imageView.contentImageView.clipsToBounds = true imageView.contentImageView.image = img } } private func imageHeight(image: UIImage) -> CGFloat { let scaleFactor = image.size.width < imageView.bounds.width ? 1 : imageView.bounds.width/image.size.width let imageHeight = ceil(image.size.height * scaleFactor) return imageHeight > InteractiveMessageAlertController.maxImageHeight ? InteractiveMessageAlertController.maxImageHeight : imageHeight } private func setupTitle() { alertTitle.text = titleText if titleText == nil { titleAndMessageSpace.constant = 0 } } }
apache-2.0
6c1bc333a3a5fc31361e70e7a6aa5e10
36.383234
178
0.762934
4.669409
false
false
false
false
mchakravarty/goalsapp
Goals/Goals/Changes.swift
1
14149
// // Changes.swift // Goals // // Created by Manuel M T Chakravarty on 28/06/2016. // Copyright © [2016..2017] Chakravarty & Keller. All rights reserved. // // Simple event-based change propagation (FRP-style). This simplified API omits some features to be easier to // understand. In particular, there is no support for observing on specific GCD queues and there is no distinction // between the reading and writing end of a stream of changes. // // To be self-contained, we inline some general purpose definitions, such as `WeakBox` and `Either`. import Foundation // MARK: Weak box /// Wrap an object reference such that is only weakly referenced. (This is, e.g., useful to have an array of object /// references that doesn't keep the referenced objects alive.) /// struct WeakBox<T: AnyObject> { // aka Schrödinger's Box fileprivate weak var box: T? var unbox: T? { get { return box } } init(_ value: T) { self.box = value } } func ===<T>(lhs: WeakBox<T>, rhs: WeakBox<T>) -> Bool { return lhs.box === rhs.box } /// Delayed application of a function to a value, where the application is only computed if the weakly referenced /// value is still available when the result is demanded. /// struct WeakApply<T> { fileprivate let arg: WeakBox<AnyObject> fileprivate let fun: (AnyObject) -> T var unbox: T? { get { return arg.unbox.map(fun) } } init<S: AnyObject>(_ fun: @escaping (S) -> T, _ value: S) { self.arg = WeakBox(value) self.fun = { fun(($0 as? S)!) } } } /// Two weak applications are considered equivalent if they wrap the same argument (the function is not considered). /// func ===<T>(lhs: WeakApply<T>, rhs: WeakApply<T>) -> Bool { return lhs.arg === rhs.arg } // MARK: - // MARK: Either enum Either<S, T> { case left(S) case right(T) } // MARK: - // MARK: LeftRight final class LeftRight { let left: Any let right: Any init(left: Any, right: Any) { self.left = left; self.right = right } } // MARK: - // MARK: Observables /// Observers are functions that receive an observed value together with a context in which the observation is being made. /// typealias Observer<Context, ObservedValue> = (Context, ObservedValue) -> () /// Observer that has been partially applied to its context. /// typealias ContextualObserver<ObservedValue> = (ObservedValue) -> () /// Opaque observation handle to be able to identify observations and to disable them. /// final class Observation<ObservedValue> { private let contextualObserver: WeakApply<ContextualObserver<ObservedValue>> private var disabled: Int = 0 /// Observations are observers that are applied to context objects tracked by weak references, the context object may /// go at any time, which implicitly unregisters the corresponding observer. /// fileprivate init<Context: AnyObject>(observer: @escaping Observer<Context, ObservedValue>, context: Context) { contextualObserver = WeakApply({ (context: Context) in { (change: ObservedValue) in observer(context, change) }}, context) } /// Apply the observer to an observed value, unless the observer is disabled. /// /// The return value is `false` if the observer is no longer alive (i.e., its context object got deallocated). /// fileprivate func apply(_ value: ObservedValue) -> Bool { if disabled >= 0 { guard let observer = contextualObserver.unbox else { return false } observer(value) } return true } /// Temporarily disable the given observation while performing the changes contained in the closure. Applications of /// this function can be nested. /// func disable(in performChanges: () -> ()) { disabled -= 1 performChanges() disabled += 1 } } /// Abstract interface to an observable stream of changes over time. /// protocol Observable { /// The type of observed values. /// associatedtype ObservedValue /// Registers an observer together with a context object whose lifetime determines the duration of the observation. /// /// The context object is stored using a weak reference. (It cannot be fully parametric as only objects can have /// weak references.) /// /// The observer will be called on the same thread where a new value is announced. /// @discardableResult func observe<Context: AnyObject>(withContext context: Context, observer: @escaping Observer<Context, ObservedValue>) -> Observation<ObservedValue> } /// Abstract interface to issuing announcements for a stream of changes over time. /// protocol Announcable { /// The type of anounced values. /// associatedtype AnnouncedValue /// Announce a change to all observers. /// func announce(change: AnnouncedValue) } /// Stream of ephemeral changes of which registered observers are being notified. /// class Changes<Value>: Announcable, Observable { typealias AnnouncedValue = Value typealias ObservedValue = Value /// Registered observers /// private var observers: [Observation<ObservedValue>] = [] /// In changes pipelines, we need to keep earlier stages of the pipeline alive. /// private let retainedObservedObject: Any? init() { self.retainedObservedObject = nil } init(retainObservedObject: Any) { self.retainedObservedObject = retainObservedObject } /// Announce a change to all observers. /// func announce(change: Value) { // Apply all observers to the change value and, at the same time, prune all stale observers (i.e., those whose // context object got deallocated). observers = observers.filter{ $0.apply(change) } } /// Registers an observer together with a context object whose lifetime determines the duration of the observation. /// A newly registered observer will receive change notification for every change *after* it has been registered. /// /// The context object is only stored using a weak reference. /// /// The observer will be called on the same thread as the change announcement. /// @discardableResult func observe<Context: AnyObject>(withContext context: Context, observer: @escaping Observer<Context, ObservedValue>) -> Observation<Value> { let observation = Observation(observer: observer, context: context) observers.append(observation) return observation } } /// Proxy to allow observations without the ability to announce changes. /// struct ChangesOutlet<Value>: Observable { typealias ObservedValue = Value private let changes: Changes<Value> // Swift compiler doesn't generate the right init in the face of the generic arguments. init(changes: Changes<Value>) { self.changes = changes } /// Registers an observer together with a context object whose lifetime determines the duration of the observation. /// /// The context object is stored using a weak reference. (It cannot be fully parametric as only objects can have /// weak references.) /// /// The observer will be called on the same thread where a new value is announced. /// @discardableResult func observe<Context : AnyObject>(withContext context: Context, observer: @escaping (Context, Value) -> ()) -> Observation<Value> { return changes.observe(withContext: context, observer: observer) } } /// Proxy to allow announcements without the ability to observe changes. /// struct ChangesInlet<Value>: Announcable { typealias AnnouncedValue = Value private let changes: Changes<Value> // Swift compiler doesn't generate the right init in the face of the generic arguments. init(changes: Changes<Value>) { self.changes = changes } /// Announce a change to all observers. /// internal func announce(change: Value) { changes.announce(change: change) } } extension Changes { /// An inlet for the steam of changes. /// var inlet: ChangesInlet<Value> { return ChangesInlet(changes: self) } /// An outlet for the steam of changes. /// var outlet: ChangesOutlet<Value> { return ChangesOutlet(changes: self) } } /// Trigger streams are changes that only convey a point in time. /// typealias Triggers = Changes<()> /// An accumulating value combines a stream of changes into an evolving value that may be observed by registered /// observers. /// class Changing<Value>: Observable { typealias ObservedValue = Value private let retainedObserved: Any // This is to keep the observed object alive. fileprivate var accumulator: Value // Encapsulated accumulator value private var changes: Changes<Value> // Stream of accumulator changes /// Constructs an accumulator with the given initial value, which is fed by an observed object by applying an /// accumulation function to the current accumulator value and the observed change to determine the new accumulator /// value. /// init<Observed: Observable> (observing observed: Observed, startingFrom initial: Value, accumulateWith accumulate: @escaping (Observed.ObservedValue, Value) -> Value) { retainedObserved = observed accumulator = initial changes = Changes<Value>() observed.observe(withContext: self){ (context: Changing<ObservedValue>, value: Observed.ObservedValue) in context.accumulator = accumulate(value, context.accumulator) context.changes.announce(change: context.accumulator) } } /// Registers an observer together with a context object whose lifetime determines the duration of the observation. /// A newly registered observer will receive a change notification immediately on registering for the current /// accumulator value and, henceforth, for every change of the accumulator after it has been registered. /// /// The context object is only stored using a weak reference. /// /// The observer will be called on the same thread as the change announcement. /// @discardableResult func observe<Context: AnyObject>(withContext context: Context, observer: @escaping Observer<Context, ObservedValue>) -> Observation<ObservedValue> { let observation = changes.observe(withContext: context, observer: observer) observer(context, accumulator) return observation } } // MARK: - // MARK: Combinators for streams of changes extension Observable { /// Transform a stream of observations to a derived stream of changes. /// /// The derived stream will cease to announce changes if the last reference to it has been dropped. (That does not /// mean that it hasn't got any observers anymore, but that no other object keeps a strong reference to the stream /// of changes itself.) /// func map<MappedValue>(transform: @escaping (ObservedValue) -> MappedValue) -> Changes<MappedValue> { let changes = Changes<MappedValue>(retainObservedObject: self) observe(withContext: changes, observer: { changesContext, change in changesContext.announce(change: transform(change)) }) return changes } /// Filter the changes in a stream of changes through a rpedicate. /// /// The result stream will cease to announce triggers if the last reference to it has been dropped. (That does not /// mean that it hasn't got any observers anymore, but that no other object keeps a strong reference to the stream /// of triggers itself.) /// func filter(predicate: @escaping (ObservedValue) -> Bool) -> Changes<ObservedValue> { let changes = Changes<ObservedValue>(retainObservedObject: self) self.observe(withContext: changes, observer: { changesContext, change in if predicate(change) { changesContext.announce(change: change) } }) return changes } func accumulate<Accumulator>(startingFrom initial: Accumulator, accumulateWith accumulate: @escaping (ObservedValue, Accumulator) -> Accumulator) -> Changing<Accumulator> { return Changing<Accumulator>(observing: self, startingFrom: initial, accumulateWith: accumulate) } /// Merge two observation streams into one. /// /// The derived stream will cease to announce changes if the last reference to it has been dropped. (That does not /// mean that it hasn't got any observers anymore, but that no other object keeps a strong reference to the stream /// of changes itself.) /// func merge<ObservedRight: Observable>(right: ObservedRight) -> Changes<Either<ObservedValue, ObservedRight.ObservedValue>> { typealias Change = Either<ObservedValue, ObservedRight.ObservedValue> let changes = Changes<Change>(retainObservedObject: LeftRight(left: self, right: right)) self.observe(withContext: changes, observer: { changesContext, change in let leftChange: Change = .left(change) changesContext.announce(change: leftChange) }) right.observe(withContext: changes, observer: { changesContext, change in let rightChange: Change = .right(change) changesContext.announce(change: rightChange) }) return changes } } // MARK: - // MARK: Combinators for streams of changing values extension Changing { /// Transform a changing value with the given transformation function. /// func map<MappedValue>(transform: @escaping (Value) -> MappedValue) -> Changing<MappedValue> { return Changing<MappedValue>(observing: self, startingFrom: transform(accumulator)){ (change, _) in return transform(change) } } } // MARK: - // MARK: Lifting functions from plain values to changing values. func lift2<Value1, Value2, Value3>(_ changing1: Changing<Value1>, _ changing2: Changing<Value2>, combineValues: @escaping (Value1, Value2) -> Value3) -> Changing<Value3> { let initial = combineValues(changing1.accumulator, changing2.accumulator), changing12 = changing1.merge(right: changing2) return Changing(observing: changing12, startingFrom: initial){ (change, _) in switch change { case .left(let value1): return combineValues(value1, changing2.accumulator) case .right(let value2): return combineValues(changing1.accumulator, value2) } } }
bsd-2-clause
a0f9201a19be47a208fd0094d34c6e60
34.45614
122
0.706298
4.518365
false
false
false
false
nodes-vapor/sugar
Sources/Sugar/Helpers/Model.swift
1
3133
import Fluent import Vapor public extension Model { static func requireFind( _ id: ID, on worker: DatabaseConnectable ) -> Future<Self> { return Self .find(id, on: worker) .unwrap(or: Abort(.notFound, reason: "\(Self.self) with id \(id) not found")) } @available(*, deprecated, message: "use `creatOrUpdate(given:withSoftDeleted:restore:on)`") func saveOrUpdate( given filters: [FilterOperator<Self.Database, Self>], withSoftDeleted: Bool = false, restore: Bool = false, on db: DatabaseConnectable ) throws -> Future<Self> { return try createOrUpdate( given: filters, withSoftDeleted: withSoftDeleted, restore: restore, on: db ) } func createOrUpdate( given filters: [FilterOperator<Self.Database, Self>], withSoftDeleted: Bool = false, restore: Bool = false, on db: DatabaseConnectable ) throws -> Future<Self> { var query = Self.query(on: db, withSoftDeleted: withSoftDeleted) for filter in filters { query = query.filter(filter) } return query.first().flatMap(to: Self.self) { result in guard let result = result else { return self.create(on: db) } var copy = self copy.fluentID = result.fluentID copy.fluentCreatedAt = result.fluentCreatedAt copy.fluentDeletedAt = result.fluentDeletedAt let future = copy.update(on: db) guard restore else { return future } return future.flatMap { $0.restore(on: db) } } } } extension Model where Database: SchemaSupporting { public static func addProperties( to builder: SchemaCreator<Self>, excluding excludedProperties: [ReflectedProperty?] ) throws { guard let idProperty = try Self.reflectProperty(forKey: idKey) else { throw FluentError( identifier: "idProperty", reason: "Unable to reflect ID property for `\(Self.self)`." ) } let properties = try Self.reflectProperties(depth: 0).filter { property in !excludedProperties.contains { excludedProperty in property.path == excludedProperty?.path } } for property in properties { let field = Database.schemaField( for: property.type, isIdentifier: idProperty.path == property.path, Database.queryField(.reflected(property, rootType: self)) ) Database.schemaFieldCreate(field, to: &builder.schema) } } public static func addProperties<T: Any>( to builder: SchemaCreator<Self>, excluding excludedKeyPaths: [KeyPath<Self, T>] ) throws { let excludedProperties = excludedKeyPaths .compactMap { try? Self.reflectProperty(forKey: $0) } try addProperties(to: builder, excluding: excludedProperties) } }
mit
866e41911fadf3b84b3026b0cc0ae7fd
30.646465
95
0.582828
4.79052
false
false
false
false
nifty-swift/Nifty
Sources/le.swift
2
2728
/*************************************************************************************************** * le.swift * * This file provides public functionality for less-than-or-equal-to comparison. * * Author: Philip Erickson * Creation Date: 1 May 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2016 Philip Erickson **************************************************************************************************/ public func <= <T>(left: Matrix<T>, right: Matrix<T>) -> Matrix<Double> where T: Comparable { return le(left, right) } public func <= <T>(left: Matrix<T>, right: T) -> Matrix<Double> where T: Comparable { return le(left, right) } public func <= <T>(left: T, right: Matrix<T>) -> Matrix<Double> where T: Comparable { return le(left, right) } /// Determine less than or equal to inequality. /// /// - Paramters: /// - A: Matrix to compare /// - B: Matrix to compare against /// - Returns: matrix with ones where comparison is true and zeros elsewhere public func le<T>(_ A: Matrix<T>, _ B: Matrix<T>) -> Matrix<Double> where T: Comparable { precondition(A.size == B.size, "Matrices must be same size") var m = [Double]() for i in 0..<A.count { m.append(A[i] <= B[i] ? 1 : 0) } return Matrix(A.size, m) } /// Determine less than or equal to inequality. /// /// - Paramters: /// - A: Matrix to compare /// - b: Value to compare against /// - Returns: matrix with ones where comparison is true and zeros elsewhere public func le<T>(_ A: Matrix<T>, _ b: T) -> Matrix<Double> where T: Comparable { var m = [Double]() for i in 0..<A.count { m.append(A[i] <= b ? 1 : 0) } return Matrix(A.size, m) } /// Determine less than or equal to inequality. /// /// - Paramters: /// - a: Value to compare /// - B: Matrix to compare against /// - Returns: matrix with ones where comparison is true and zeros elsewhere public func le<T>(_ a: T, _ B: Matrix<T>) -> Matrix<Double> where T: Comparable { var m = [Double]() for i in 0..<B.count { m.append(a <= B[i] ? 1 : 0) } return Matrix(B.size, m) }
apache-2.0
4f4aa607c6a3d8626b18d4b3481bc703
31.879518
101
0.575513
3.773167
false
false
false
false
BjornRuud/Swiftache
Swiftache/Template.swift
1
1024
// // Template.swift // Swiftache // // Copyright (c) 2014 Bjørn Olav Ruud. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE.txt for details. // import Foundation public class Template { public let text: NSString public let fileURL: NSURL? public let fileEncoding: NSStringEncoding? private let data: NSData! public init(text: String) { self.text = text } public init(fileURL: NSURL, encoding: NSStringEncoding) { self.fileURL = fileURL self.fileEncoding = encoding var dataError = NSErrorPointer() let possibleData: NSData? = NSData(contentsOfURL: fileURL, options: .DataReadingMappedAlways, error: dataError) data = possibleData ?? NSData() text = NSString(bytesNoCopy: UnsafeMutablePointer<Void>(data.bytes), length: data.length, encoding: encoding, freeWhenDone: false)! } public convenience init(fileURL: NSURL) { self.init(fileURL: fileURL, encoding: NSUTF8StringEncoding) } }
mit
d59d422b42a9ba7d226e844c7ebe59fa
28.228571
139
0.683284
4.428571
false
false
false
false
ivlevAstef/SIALogger
Swift/SIALogger/SIALogger/Colored/SIALogColoredConsoleOutput.swift
1
2404
// // SIALogColoredConsoleOutput.swift // SIALogger // // Created by Alexander Ivlev on 03/06/16. // Copyright © 2016 Alexander Ivlev. All rights reserved. // import Foundation public class SIALogColoredConsoleOutput : SIALogOutputProtocol { public static let defaultLogFormat = "%t %c[%3]%c {%f:%l}: %m" public convenience init() { self.init(logFormat: SIALogColoredConsoleOutput.defaultLogFormat) } public required init(logFormat: String) { formatter = SIALogColoredFormatter(format: logFormat) setDefaultColors() } public func log(msg: SIALogMessage) { print(formatter.toString(msg, coloredMethod: {self.colored($0, level: msg.level)})) } public func setForegroundColor(color : SIALogColor, level: SIALogLevel) { colorForegroundMap[level] = color } public func setBackgroundColor(color : SIALogColor, level: SIALogLevel) { colorBackgroundMap[level] = color } public func setDefaultColors() { setForegroundColor(SIALogColor(255,255,255), level: SIALogLevel.Fatal) setBackgroundColor(SIALogColor(255,0 ,0 ), level: SIALogLevel.Fatal) setForegroundColor(SIALogColor(255,0 ,0 ), level: SIALogLevel.Error) setForegroundColor(SIALogColor(255,128,0 ), level: SIALogLevel.Warning) setForegroundColor(SIALogColor(64 ,64 ,255), level: SIALogLevel.Info) setForegroundColor(SIALogColor(128,128,128), level: SIALogLevel.Trace) } public func colored(text : String, level: SIALogLevel) -> String { var fgColorStrOptional : String? if let fgColor = colorForegroundMap[level] { fgColorStrOptional = SIALogColoredConsoleOutput.ESCAPE+"fg"+fgColor.xcodeColor } var bgColorStrOptional : String? if let bgColor = colorBackgroundMap[level] { bgColorStrOptional = SIALogColoredConsoleOutput.ESCAPE+"bg"+bgColor.xcodeColor } if nil == fgColorStrOptional && nil == bgColorStrOptional { return text } let fgColorStr = fgColorStrOptional ?? "" let bgColorStr = bgColorStrOptional ?? "" return bgColorStr+fgColorStr+text+SIALogColoredConsoleOutput.RESET } private let formatter: SIALogColoredFormatter private static let ESCAPE = "\u{001b}[" private static let RESET = "\u{001b}[" + ";" private var colorForegroundMap : [SIALogLevel:SIALogColor] = [:] private var colorBackgroundMap : [SIALogLevel:SIALogColor] = [:] }
mit
d05a821bc488d16f49efa7ee8ce8a8e6
32.859155
87
0.715772
4.401099
false
false
false
false
lorismaz/LaDalle
LaDalle/LaDalle/Category.swift
1
17002
// // Category.swift // LaDalle // // Created by Loris Mazloum on 9/19/16. // Copyright © 2016 Loris Mazloum. All rights reserved. // import UIKit import CoreLocation struct Category { let title: String let alias: String static func fromDictionary(dictionary: NSDictionary) -> Category? { //Pull out each individual element from the dictionary guard let alias = dictionary["alias"] as? String, let title = dictionary["title"] as? String else { return nil } //Take the data parsed and create a Place Object from it return Category(title: title, alias: alias) } static func loadDefaults() -> [Category] { let categories: [Category] = [ Category(title: "Bagels", alias:"bagels"), Category(title: "Bakeries", alias:"bakeries"), Category(title: "Beer, Wine & Spirits", alias:"beer_and_wine"), Category(title: "Breweries", alias:"breweries"), Category(title: "Bubble Tea", alias:"bubbletea"), Category(title: "Butcher", alias:"butcher"), Category(title: "CSA", alias:"csa"), Category(title: "Cideries", alias:"cideries"), Category(title: "Coffee & Tea", alias:"coffee"), Category(title: "Coffee Roasteries", alias:"coffeeroasteries"), Category(title: "Convenience Stores", alias:"convenience"), Category(title: "Cupcakes", alias:"cupcakes"), Category(title: "Custom Cakes", alias:"customcakes"), Category(title: "Desserts", alias:"desserts"), Category(title: "Distilleries", alias:"distilleries"), Category(title: "Do-It-Yourself Food", alias:"diyfood"), Category(title: "Donuts", alias:"donuts"), Category(title: "Empanadas", alias:"empanadas"), Category(title: "Ethnic Grocery", alias:"ethnicgrocery"), Category(title: "Farmers Market", alias:"farmersmarket"), Category(title: "Food Delivery Services", alias:"fooddeliveryservices"), Category(title: "Food Trucks", alias:"foodtrucks"), Category(title: "Gelato", alias:"gelato"), Category(title: "Grocery", alias:"grocery"), Category(title: "Honey", alias:"honey"), Category(title: "Ice Cream & Frozen Yogurt", alias:"icecream"), Category(title: "Internet Cafes", alias:"internetcafe"), Category(title: "Juice Bars & Smoothies", alias:"juicebars"), Category(title: "Kombucha", alias:"kombucha"), Category(title: "Organic Stores", alias:"organic_stores"), Category(title: "Patisserie/Cake Shop", alias:"cakeshop"), Category(title: "Poke", alias:"poke"), Category(title: "Pretzels", alias:"pretzels"), Category(title: "Shaved Ice", alias:"shavedice"), Category(title: "Specialty Food", alias:"gourmet"), Category(title: "Candy Stores", alias:"candy"), Category(title: "Cheese Shops", alias:"cheese"), Category(title: "Chocolatiers & Shops", alias:"chocolate"), Category(title: "Ethnic Food", alias:"ethnicmarkets"), Category(title: "Fruits & Veggies", alias:"markets"), Category(title: "Health Markets", alias:"healthmarkets"), Category(title: "Herbs & Spices", alias:"herbsandspices"), Category(title: "Macarons", alias:"macarons"), Category(title: "Meat Shops", alias:"meats"), Category(title: "Olive Oil", alias:"oliveoil"), Category(title: "Pasta Shops", alias:"pastashops"), Category(title: "Popcorn Shops", alias:"popcorn"), Category(title: "Seafood Markets", alias:"seafoodmarkets"), Category(title: "Street Vendors", alias:"streetvendors"), Category(title: "Tea Rooms", alias:"tea"), Category(title: "Water Stores", alias:"waterstores"), Category(title: "Wineries", alias:"wineries"), Category(title: "Wine Tasting Room", alias:"winetastingroom"), Category(title: "Afghan", alias: "afghani"), Category(title: "African", alias: "african"), Category(title: "Senegalese", alias: "senegalese"), Category(title: "South African", alias: "southafrican"), Category(title: "American", alias: "New"), Category(title: "American", alias: "Traditional"), Category(title: "Arabian", alias: "arabian"), Category(title: "Argentine", alias: "argentine"), Category(title: "Armenian", alias: "armenian"), Category(title: "Asian Fusion", alias: "asianfusion"), Category(title: "Australian", alias: "australian"), Category(title: "Austrian", alias: "austrian"), Category(title: "Bangladeshi", alias: "bangladeshi"), Category(title: "Barbeque", alias: "bbq"), Category(title: "Basque", alias: "basque"), Category(title: "Belgian", alias: "belgian"), Category(title: "Brasseries", alias: "brasseries"), Category(title: "Brazilian", alias: "brazilian"), Category(title: "Breakfast & Brunch", alias: "breakfast_brunch"), Category(title: "British", alias: "british"), Category(title: "Buffets", alias: "buffets"), Category(title: "Burgers", alias: "burgers"), Category(title: "Burmese", alias: "burmese"), Category(title: "Cafes", alias: "cafes"), Category(title: "Themed Cafes", alias: "themedcafes"), Category(title: "Cafeteria", alias: "cafeteria"), Category(title: "Cajun/Creole", alias: "cajun"), Category(title: "Cambodian", alias: "cambodian"), Category(title: "Caribbean", alias: "caribbean"), Category(title: "Dominican", alias: "dominican"), Category(title: "Haitian", alias: "haitian"), Category(title: "Puerto Rican", alias: "puertorican"), Category(title: "Trinidadian", alias: "trinidadian"), Category(title: "Catalan", alias: "catalan"), Category(title: "Cheesesteaks", alias: "cheesesteaks"), Category(title: "Chicken Shop", alias: "chickenshop"), Category(title: "Chicken Wings", alias: "chicken_wings"), Category(title: "Chinese", alias: "chinese"), Category(title: "Cantonese", alias: "cantonese"), Category(title: "Dim Sum", alias: "dimsum"), Category(title: "Hainan", alias: "hainan"), Category(title: "Shanghainese", alias: "shanghainese"), Category(title: "Szechuan", alias: "szechuan"), Category(title: "Comfort Food", alias: "comfortfood"), Category(title: "Creperies", alias: "creperies"), Category(title: "Cuban", alias: "cuban"), Category(title: "Czech", alias: "czech"), Category(title: "Delis", alias: "delis"), Category(title: "Diners", alias: "diners"), Category(title: "Dinner Theater", alias: "dinnertheater"), Category(title: "Ethiopian", alias: "ethiopian"), Category(title: "Fast Food", alias: "hotdogs"), Category(title: "Filipino", alias: "filipino"), Category(title: "Fish & Chips", alias: "fishnchips"), Category(title: "Fondue", alias: "fondue"), Category(title: "Food Court", alias: "food_court"), Category(title: "Food Stands", alias: "foodstands"), Category(title: "French", alias: "french"), Category(title: "Gastropubs", alias: "gastropubs"), Category(title: "German", alias: "german"), Category(title: "Gluten-Free", alias: "gluten_free"), Category(title: "Greek", alias: "greek"), Category(title: "Halal", alias: "halal"), Category(title: "Hawaiian", alias: "hawaiian"), Category(title: "Himalayan/Nepalese", alias: "himalayan"), Category(title: "Hong Kong Style Cafe", alias: "hkcafe"), Category(title: "Hot Dogs", alias: "hotdog"), Category(title: "Hot Pot", alias: "hotpot"), Category(title: "Hungarian", alias: "hungarian"), Category(title: "Iberian", alias: "iberian"), Category(title: "Indian", alias: "indpak"), Category(title: "Indonesian", alias: "indonesian"), Category(title: "Irish", alias: "irish"), Category(title: "Italian", alias: "italian"), Category(title: "Calabrian", alias: "calabrian"), Category(title: "Sardinian", alias: "sardinian"), Category(title: "Tuscan", alias: "tuscan"), Category(title: "Japanese", alias: "japanese"), Category(title: "Izakaya", alias: "izakaya"), Category(title: "Ramen", alias: "ramen"), Category(title: "Teppanyaki", alias: "teppanyaki"), Category(title: "Korean", alias: "korean"), Category(title: "Kosher", alias: "kosher"), Category(title: "Laotian", alias: "laotian"), Category(title: "Latin American", alias: "latin"), Category(title: "Colombian", alias: "colombian"), Category(title: "Salvadoran", alias: "salvadoran"), Category(title: "Venezuelan", alias: "venezuelan"), Category(title: "Live/Raw Food", alias: "raw_food"), Category(title: "Malaysian", alias: "malaysian"), Category(title: "Mediterranean", alias: "mediterranean"), Category(title: "Falafel", alias: "falafel"), Category(title: "Mexican", alias: "mexican"), Category(title: "Middle Eastern", alias: "mideastern"), Category(title: "Egyptian", alias: "egyptian"), Category(title: "Lebanese", alias: "lebanese"), Category(title: "Modern European", alias: "modern_european"), Category(title: "Mongolian", alias: "mongolian"), Category(title: "Moroccan", alias: "moroccan"), Category(title: "New Mexican Cuisine", alias: "newmexican"), Category(title: "Nicaraguan", alias: "nicaraguan"), Category(title: "Noodles", alias: "noodles"), Category(title: "Pakistani", alias: "pakistani"), Category(title: "Persian/Iranian", alias: "persian"), Category(title: "Peruvian", alias: "peruvian"), Category(title: "Pizza", alias: "pizza"), Category(title: "Polish", alias: "polish"), Category(title: "Pop-Up Restaurants", alias: "popuprestaurants"), Category(title: "Portuguese", alias: "portuguese"), Category(title: "Poutineries", alias: "poutineries"), Category(title: "Russian", alias: "russian"), Category(title: "Salad", alias: "salad"), Category(title: "Sandwiches", alias: "sandwiches"), Category(title: "Scandinavian", alias: "scandinavian"), Category(title: "Scottish", alias: "scottish"), Category(title: "Seafood", alias: "seafood"), Category(title: "Singaporean", alias: "singaporean"), Category(title: "Slovakian", alias: "slovakian"), Category(title: "Soul Food", alias: "soulfood"), Category(title: "Soup", alias: "soup"), Category(title: "Southern", alias: "southern"), Category(title: "Spanish", alias: "spanish"), Category(title: "Sri Lankan", alias: "srilankan"), Category(title: "Steakhouses", alias: "steak"), Category(title: "Supper Clubs", alias: "supperclubs"), Category(title: "Sushi Bars", alias: "sushi"), Category(title: "Syrian", alias: "syrian"), Category(title: "Taiwanese", alias: "taiwanese"), Category(title: "Tapas Bars", alias: "tapas"), Category(title: "Tapas/Small Plates", alias: "tapasmallplates"), Category(title: "Tex-Mex", alias: "tex-mex"), Category(title: "Thai", alias: "thai"), Category(title: "Turkish", alias: "turkish"), Category(title: "Ukrainian", alias: "ukrainian"), Category(title: "Uzbek", alias: "uzbek"), Category(title: "Vegan", alias: "vegan"), Category(title: "Vegetarian", alias: "vegetarian"), Category(title: "Vietnamese", alias: "vietnamese"), Category(title: "Waffles", alias: "waffles") ] return categories } static func getCategories(for coordinates: CLLocation, categorySearchCompletionHandler: @escaping ([Category]) -> ()) { UIApplication.shared.isNetworkActivityIndicatorVisible = true var arrayOfCategories: [Category] = [] let accessToken = valueForAPIKey(named: "YELP_API_ACCESS_TOKEN") //if radius return 0 results then increase the radius let radius = 1000 // limit distance and limit to open only. let link = "https://api.yelp.com/v3/businesses/search?&latitude=\(coordinates.coordinate.latitude)&longitude=\(coordinates.coordinate.longitude)&radius=\(radius)" //&open_now=true //set headers let headers = [ "Authorization": "Bearer \(accessToken)" ] guard let url = URL(string: link) else { return } //set request var request = URLRequest.init(url: url) request.httpMethod = "GET" request.allHTTPHeaderFields = headers let sharedSession = URLSession.shared let apiCallCompletionHandler: (Data?, URLResponse?, Error?) -> Void = { data, response, error in // this is where the completion handler code goes guard let data = data, error == nil else { // check for networking error print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } //let responseString = String(data: data, encoding: .utf8) //print("responseString = \(responseString)") do { let jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) guard let result = jsonObject as? NSDictionary else { print("result is not a dictionary"); return } guard let total = result["total"] as? Int else { print("no total available"); return } guard total > 0 else { print("Search returned 0 results") ; return } guard let businesses = result["businesses"] as? NSArray else { print("business is not an array"); return } for businessObject in businesses { guard let businessDictionary = businessObject as? NSDictionary else { print("businessDict is not a dictionary"); return } guard let categories = businessDictionary["categories"] as? NSArray else { print("error parsing categories as an array"); return } for categoryObject in categories { guard let categoryDictionary = categoryObject as? NSDictionary else { return } guard let category = Category.fromDictionary(dictionary: categoryDictionary) else { print("can't create a category out of the data"); return } //if category not yet in array > print("\(category)" ) if arrayOfCategories.contains( where: { $0.alias == category.alias }) { print("Category already there") } else { print("New category, let's add it") arrayOfCategories.append(category) } } categorySearchCompletionHandler(arrayOfCategories) } } catch { print("Could not get categories") return } UIApplication.shared.isNetworkActivityIndicatorVisible = false } let task = sharedSession.dataTask(with: request, completionHandler: apiCallCompletionHandler) task.resume() } }
mit
0a7054b1d75b574ee073eca3a06e76fa
51.962617
187
0.565731
4.284526
false
false
false
false
tottokotkd/ColorPack
ColorPack/src/common/struct/HSLColor.swift
1
5602
// // HSLColor.swift // ColorPack // // Created by Shusuke Tokuda on 2016/10/27. // Copyright © 2016年 tottokotkd. All rights reserved. // import Foundation extension HSLColorInitializer { public static func create(hue: Degree?, saturation: Percentage, lightness: Percentage, alpha: Percentage = percentageMax) -> HSLColor? { return HSLColor(hue: hue, saturation: saturation, lightness: lightness, alpha: alpha) } public static func truncate(hue: Degree?, saturation: Percentage, lightness: Percentage, alpha: Percentage = percentageMax) -> HSLColor { return HSLColor(hue: hue?.asDegree, saturation: saturation.asPercentage, lightness: lightness.asPercentage, alpha: alpha.asPercentage)! } public static func truncateColorValue(_ value: Double) -> Double { return max(min(value, 1), 0) } } public struct HSLColor: HSLColorProtocol, ColorStructConvertor { public typealias T = HSLData public let rawValue: T public let alpha: Percentage public init?(rawValue: T, alpha: Percentage) { self.init(hue: rawValue.hue, saturation: rawValue.saturation, lightness: rawValue.lightness, alpha: alpha) } public init?(hue: Degree?, saturation: Percentage, lightness: Percentage, alpha: Double) { if saturation.inPercentageRange && lightness.inPercentageRange && alpha.inPercentageRange { self.rawValue = (hue?.asDegree, saturation, lightness) self.alpha = alpha } else { return nil } } public var toHSLData: T {return rawValue} public var toDoubleRGBData: (red: Percentage, green: Percentage, blue: Percentage) { let (hue, saturation, lightness) = rawValue return getRGB(hue: hue, saturation: saturation, lightness: lightness) } } extension HSLColor: ColorManipulationProtocol { public func merge(_ rhs: HSLColor, ratio: Percentage) -> HSLColor { let ratioValue = ratio.asPercentage if ratioValue == percentageMin { return self } else if ratioValue == percentageMax { return rhs.map(transformAlpha: {_ in alpha})! } func getHueGap(from: Degree, to: Degree) -> Degree { let ascGap = (to - from).asDegree return ascGap < degreeMax / 2 ? ascGap : (ascGap - degreeMax) } let rightRatio = ratioValue / percentageMax let leftRatio = 1 - rightRatio return merge(rhs) { (left: HSLData, right: HSLData) in let s = left.saturation == right.saturation ? left.saturation : (left.saturation * leftRatio + right.saturation * rightRatio).asPercentage let l = left.lightness == right.lightness ? left.lightness :(left.lightness * leftRatio + right.lightness * rightRatio).asPercentage if let leftHue = left.hue, let rightHue = right.hue { let gap = getHueGap(from: leftHue, to: rightHue) let h = leftHue + gap * rightRatio return (h, s, l) } else { return (nil, s, l) }}! } } extension HSLColor: ColorConversionProtocol { public var toInverse: HSLColor { return map({(hue: Degree?, saturation: Percentage, lightness: Percentage) in let newHue = hue.map{($0 + (degreeMax / 2)).asDegree} let newLightness = (percentageMax - lightness).asPercentage return (newHue, saturation, newLightness) })! } public var toComplementary: HSLColor { return map({(hue: Degree?, saturation: Percentage, lightness: Percentage) in let newHue = hue.map{($0 + (degreeMax / 2)).asDegree} return (newHue, saturation, lightness) })! } public var toAnalogous: (upper: HSLColor, lower: HSLColor) { let upper = map({(hue: Degree?, saturation: Percentage, lightness: Percentage) in let newHue = hue.map{($0 + (degreeMax / 12)).asDegree} return (newHue, saturation, lightness) })! let lower = map({(hue: Degree?, saturation: Percentage, lightness: Percentage) in let newHue = hue.map{($0 - (degreeMax / 12)).asDegree} return (newHue, saturation, lightness) })! return (upper, lower) } public var toTriadic: (upper: HSLColor, lower: HSLColor) { let upper = map({(hue: Degree?, saturation: Percentage, lightness: Percentage) in let newHue = hue.map{($0 + (degreeMax / 3)).asDegree} return (newHue, saturation, lightness) })! let lower = map({(hue: Degree?, saturation: Percentage, lightness: Percentage) in let newHue = hue.map{($0 - (degreeMax / 3)).asDegree} return (newHue, saturation, lightness) })! return (upper, lower) } public var toSplitComplementary: (upper: HSLColor, lower: HSLColor) { return toComplementary.toAnalogous } } extension HSLColor: Equatable { public static func ==(lhs: HSLColor, rhs: HSLColor) -> Bool { let (h1, s1, l1) = lhs.rawValue let (h2, s2, l2) = rhs.rawValue return h1 == h2 && s1 == s2 && l1 == l2 && lhs.alpha == rhs.alpha } } extension HSLColor: CustomStringConvertible { public var description: String { let (h, s, l) = rawValue let hue = h.map{String(format: "%.4f˚", $0)} ?? "undefined" let saturation = String(format: "%.4f", s) let lightness = String(format: "%.4f", l) return "HSLColor <hue: \(hue), saturation: \(saturation)%, lightness: \(lightness)%, alpha: \(alpha)%>" } }
mit
a9047a673d072bb1aad068ebab612ad1
42.061538
150
0.623258
4.359813
false
false
false
false
GongChengKuangShi/DYZB
DouYuTV/DouYuTV/Classes/Home/View/RecommandGameView.swift
1
2075
// // RecommandGameView.swift // DouYuTV // // Created by xrh on 2017/9/8. // Copyright © 2017年 xiangronghua. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class RecommandGameView: UIView { //定义数据的属性 var groups : [AnchorGroup]? { didSet { //移除前两组数据 groups?.removeFirst() groups?.removeFirst() //添加更多组 let moreGroup = AnchorGroup() moreGroup.tag_name = "更多" groups?.append(moreGroup) //刷新表格 collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() //设置不随父控件的大小改变而改变 autoresizingMask = UIViewAutoresizing(rawValue: UInt(noErr)) //注册cell collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) //给gameView添加内边距 collectionView.contentInset = UIEdgeInsetsMake(0, kEdgeInsetMargin, 0, kEdgeInsetMargin) } } extension RecommandGameView { class func recommandGameView() -> RecommandGameView { return Bundle.main.loadNibNamed("RecommandGameView", owner: nil, options: nil)!.first as! RecommandGameView } } //遵守协议 extension RecommandGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.group = groups![indexPath.item] return cell } }
mit
76a53280ec72dbc7fc5e8b0461ac1cb7
25.958904
126
0.642785
5.362398
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCSegmentedPageControl.swift
2
5182
// // NCSegmentedControl.swift // Neocom // // Created by Artem Shimanski on 12.01.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit //@IBDesignable class NCSegmentedPageControl: UIControl, UIScrollViewDelegate { @IBInspectable var spacing: CGFloat = 15 @IBInspectable var segments: String? { didSet { self.titles = segments?.components(separatedBy: "|") ?? [] } } var titles: [String] = [] { didSet { var buttons = stackView.arrangedSubviews as? [UIButton] ?? [] for title in titles { let button = !buttons.isEmpty ? buttons.removeFirst() : { let button = UIButton(frame: .zero) button.translatesAutoresizingMaskIntoConstraints = false button.setTitleColor(.white, for: .normal) button.addTarget(self, action: #selector(onButton(_:)), for: .touchUpInside) stackView.addArrangedSubview(button) return button }() button.setTitle(title, for: .normal) button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .footnote) } buttons.forEach {$0.removeFromSuperview()} setNeedsLayout() } } @IBOutlet weak var scrollView: UIScrollView? { didSet { scrollView?.delegate = self } } override init(frame: CGRect) { super.init(frame: frame) tintColor = .caption } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private lazy var contentView: UIScrollView = { let contentView = UIScrollView(frame: self.bounds) contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] contentView.delaysContentTouches = true contentView.canCancelContentTouches = true contentView.showsHorizontalScrollIndicator = false contentView.showsVerticalScrollIndicator = false self.addSubview(contentView) return contentView }() public lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.alignment = .center stackView.distribution = .fillProportionally stackView.axis = .horizontal stackView.spacing = self.spacing stackView.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(stackView) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(s)-[view]-(s)-|", options: [], metrics: ["s": self.spacing], views: ["view": stackView])) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: [], metrics: nil, views: ["view": stackView])) // NSLayoutConstraint(item: stackView, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: self.contentView, attribute: .width, multiplier: 1, constant: -self.spacing * 2).isActive = true stackView.widthAnchor.constraint(greaterThanOrEqualTo: self.contentView.widthAnchor, constant: -self.spacing * 2).isActive = true stackView.heightAnchor.constraint(equalTo: self.contentView.heightAnchor).isActive = true return stackView }() public lazy var indicator: UIView = { let indicator = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 4)) indicator.backgroundColor = self.tintColor self.contentView.addSubview(indicator) return indicator }() override func layoutSubviews() { super.layoutSubviews() var bounds = self.bounds bounds.size.height -= 4 contentView.frame = bounds guard stackView.arrangedSubviews.count > 0 else {return} stackView.layoutIfNeeded() contentView.layoutIfNeeded() guard let scrollView = scrollView, scrollView.bounds.size.width > 0 else {return} let p = scrollView.contentOffset.x / scrollView.bounds.size.width let page = Int(round(p)) let lastPage = (stackView.arrangedSubviews.count - 1) for (i, button) in (stackView.arrangedSubviews as! [UIButton]).enumerated() { button.setTitleColor(i == page ? tintColor : .lightText, for: .normal) } let fromLabel = stackView.arrangedSubviews[Int(trunc(p)).clamped(to: 0...lastPage)] let toLabel = stackView.arrangedSubviews[Int(ceil(p)).clamped(to: 0...lastPage)] var from = fromLabel.convert(fromLabel.bounds, to: contentView) var to = toLabel.convert(toLabel.bounds, to: contentView) if p < 0 { from.size.width = 0; } else if p > CGFloat(lastPage) { to.origin.x += to.size.width to.size.width = 0 } var rect = from.lerp(to: to, t: 1.0 - (ceil(p) - p)) rect.size.height = 3 rect.origin.y = bounds.size.height - rect.size.height indicator.frame = rect let x = indicator.center.x - contentView.bounds.size.width / 2 guard contentView.contentSize.width >= contentView.bounds.size.width else {return} contentView.contentOffset.x = x.clamped(to: 0...(contentView.contentSize.width - contentView.bounds.size.width)) } override var intrinsicContentSize: CGSize { var size = self.contentView.contentSize size.height += 4 return size } @IBAction private func onButton(_ sender: UIButton) { guard let i = stackView.arrangedSubviews.index(of: sender) else {return} guard let scrollView = scrollView else {return} scrollView.setContentOffset(CGPoint(x: CGFloat(i) * scrollView.bounds.size.width, y: 0), animated: true) } // MARK: UIScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { self.setNeedsLayout() } }
lgpl-2.1
a113925fd2a08af2852c27ee0db89de0
33.54
195
0.724185
3.892562
false
false
false
false
meteochu/DecisionKitchen
iOS/DecisionKitchen/GameCategoriesViewController.swift
1
2980
// // GameCategoriesViewController.swift // DecisionKitchen // // Created by Andy Liang on 2017-07-30. // Copyright © 2017 Andy Liang. All rights reserved. // import UIKit class GameCategoriesViewController: CollectionViewController, UICollectionViewDelegateFlowLayout { let allCategories = Category.allOptions var selectedCategories: [Category] { return self.collectionView!.indexPathsForSelectedItems!.map { self.allCategories[$0.item] } } var response: GameResponse! override func viewDidLoad() { super.viewDidLoad() self.collectionView!.allowsMultipleSelection = true self.collectionView!.register(CategoryItemCell.self) if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout { layout.estimatedItemSize = CGSize(width: 150, height: 45) layout.minimumInteritemSpacing = 8 layout.minimumLineSpacing = 8 } } @IBAction func didSelectCheckmark(_ sender: UIButton) { var indexes = [Int]() let selected = selectedCategories for idx in 0..<allCategories.count { indexes.append(selected.contains(allCategories[idx]) ? 1 : 0) } response.selectedCategoryIndexes = indexes self.performSegue(withIdentifier: "beginGameStage3", sender: self) } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.allCategories.count } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCell", for: indexPath) } else { return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "FooterButton", for: indexPath) } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(for: indexPath) as CategoryItemCell cell.category = self.allCategories[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 8, left: 16, bottom: 16, right: 16) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? GameDiningOptionsViewController { destination.response = response } } }
apache-2.0
bf43c279e6121926e6a1cf6ee073c91f
38.197368
171
0.701913
5.79572
false
false
false
false
OrdnanceSurvey/search-swift
OSSearch/Searchable+Implementation.swift
1
2528
// // Searchable+Implementation.swift // Search // // Created by Dave Hardiman on 11/04/2016. // Copyright © 2016 Ordnance Survey. All rights reserved. // import Foundation import Fetch import OSTransformation extension Searchable where ResponseType: Fetch.Parsable { private func urlForPath(path: String, items: [NSURLQueryItem]) -> NSURL { let components = NSURLComponents() components.scheme = "https" components.host = "api.ordnancesurvey.co.uk" components.path = "/\(apiPath)/\(path)" let queryItems = [ NSURLQueryItem(name: "key", value: apiKey) ] + items components.queryItems = queryItems return components.URL! } private func findUrlForQuery(query: String, boundingBox: OSGridRect? = nil) -> NSURL { var items = [NSURLQueryItem(name: "query", value: query)] if let bbox = boundingBox, minX = NumberFormatter.stringFromNumber(bbox.originSW.easting), minY = NumberFormatter.stringFromNumber(bbox.originSW.northing), maxX = NumberFormatter.stringFromNumber(bbox.originSW.easting + bbox.size.width), maxY = NumberFormatter.stringFromNumber(bbox.originSW.northing + bbox.size.height) { items += [NSURLQueryItem(name: "bounds", value: "\(minX),\(minY),\(maxX),\(maxY)")] } return urlForPath("find", items: items) } public func find(query: String, completion: (Result<ResponseType> -> Void)) { let request = Request(url: findUrlForQuery(query)) get(request) { result in completion(result) } } public func nearest(location: OSGridPoint, completion: (Result<ResponseType> -> Void)) { guard let easting = NumberFormatter.stringFromNumber(location.easting), northing = NumberFormatter.stringFromNumber(location.northing) else { fatalError("Couldn't convert grid point to string") } let request = Request(url: urlForPath("nearest", items: [NSURLQueryItem(name: "point", value: "\(easting),\(northing)")])) get(request) { result in completion(result) } } } extension BoundingBoxSearchable where ResponseType: Fetch.Parsable { public func find(query: String, boundingBox: OSGridRect, completion: (Result<ResponseType> -> Void)) { let request = Request(url: findUrlForQuery(query, boundingBox: boundingBox)) get(request) { result in completion(result) } } }
apache-2.0
ba0a450c17e904112cdd33921be01333
37.876923
130
0.647408
4.488455
false
false
false
false
fizx/jane
ruby/lib/vendor/grpc-swift/Sources/Examples/Simple/main.swift
1
3850
/* * Copyright 2017, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Commander import Dispatch import Foundation import SwiftGRPC let address = "localhost:8001" let host = "foo.test.google.fr" func client() throws { let message = "hello, server!".data(using: .utf8) let c = Channel(address: address, secure: false) let steps = 3 for i in 0..<steps { let sem = DispatchSemaphore(value: 0) let method = (i < steps - 1) ? "/hello" : "/quit" print("calling " + method) let call = c.makeCall(method) let metadata = try Metadata([ "x": "xylophone", "y": "yu", "z": "zither" ]) try! call.start(.unary, metadata: metadata, message: message) { response in print("status:", response.statusCode) print("statusMessage:", response.statusMessage!) if let resultData = response.resultData { print("message: \(resultData)") } let initialMetadata = response.initialMetadata! for i in 0..<initialMetadata.count() { print("INITIAL METADATA ->", initialMetadata.key(i)!, ":", initialMetadata.value(i)!) } let trailingMetadata = response.trailingMetadata! for i in 0..<trailingMetadata.count() { print("TRAILING METADATA ->", trailingMetadata.key(i)!, ":", trailingMetadata.value(i)!) } sem.signal() } _ = sem.wait() } print("Done") } func server() throws { let server = Server(address: address) var requestCount = 0 let sem = DispatchSemaphore(value: 0) server.run { requestHandler in do { requestCount += 1 print("\(requestCount): Received request " + requestHandler.host! + " " + String(describing:requestHandler.method) + " from " + String(describing:requestHandler.caller)) let initialMetadata = requestHandler.requestMetadata for i in 0..<initialMetadata.count() { print("\(requestCount): Received initial metadata -> " + initialMetadata.key(i)! + ":" + initialMetadata.value(i)!) } let initialMetadataToSend = try Metadata([ "a": "Apple", "b": "Banana", "c": "Cherry" ]) try requestHandler.receiveMessage(initialMetadata: initialMetadataToSend) { messageData in let messageString = String(data: messageData!, encoding: .utf8) print("\(requestCount): Received message: " + messageString!) } if requestHandler.method == "/quit" { print("quitting") sem.signal() } let replyMessage = "hello, client!" let trailingMetadataToSend = try Metadata([ "0": "zero", "1": "one", "2": "two" ]) try requestHandler.sendResponse(message: replyMessage.data(using: .utf8)!, status: ServerStatus(code: .ok, message: "OK", trailingMetadata: trailingMetadataToSend)) print("------------------------------") } catch { Swift.print("call error \(error)") } } server.onCompletion = { print("Server Stopped") } _ = sem.wait() } Group { $0.command("server") { gRPC.initialize() print("gRPC version", gRPC.version) try server() } $0.command("client") { gRPC.initialize() print("gRPC version", gRPC.version) try client() } }.run()
mit
807c6d571ead16a89df58a29b429ac85
27.308824
127
0.617922
4.226125
false
false
false
false
thewisecity/declarehome-ios
CookedApp/Utilities/Stats.swift
1
5584
// // Stats.swift // CookedApp // // Created by Dexter Lohnes on 11/30/15. // Copyright © 2015 The Wise City. All rights reserved. // class Stats { static let ALERTS_SCREEN = "AlertsScreen" static let MESSAGE_WALL_CATEGORY = "MessageWallCategory" static let MESSAGE_WALL_SCREEN = "MessageWallScreen" static let CREATE_GROUP_SCREEN = "CreateGroupScreen" static let GROUP_DETAILS_CATEGORY = "GroupDetailsCategory" static let GROUP_DETAILS_SCREEN = "GroupDetailsScreen" static let LOGIN_SCREEN = "LoginScreen" static let REGISTRATION_SCREEN = "RegistrationScreen" static let MY_GROUPS_SCREEN = "My_Groups_Screen" static let ALL_GROUPS_SCREEN = "All_Groups_Screen" static let EVENTS_SCREEN = "EventsScreen" static func TrackBeganMessageCreation() -> Void { SEGAnalytics.sharedAnalytics().track("Began Message Creation") } static func TrackEndedMessageCreation() -> Void { SEGAnalytics.sharedAnalytics().track("Ended Message Creation") } static func TrackOpenedNewMessageMenu() -> Void { SEGAnalytics.sharedAnalytics().track("Opened New Message Menu") } static func TrackClosedNewMessageMenu() -> Void { SEGAnalytics.sharedAnalytics().track("Closed New Message Menu") } static func TrackBeganAlertCreation() -> Void { SEGAnalytics.sharedAnalytics().track("Began Alert Creation") } static func TrackBeganAlertComposition() -> Void { SEGAnalytics.sharedAnalytics().track("Began Alert Composition") } static func TrackAttemptingGroupCreation() -> Void { SEGAnalytics.sharedAnalytics().track("Attempting Group Creation") } static func TrackGroupCreationCancelled() -> Void { SEGAnalytics.sharedAnalytics().track("Group Creation Cancelled") } static func TrackApplicationStarted() -> Void { SEGAnalytics.sharedAnalytics().track("Application Started") } static func ScreenCreateGroup() -> Void { SEGAnalytics.sharedAnalytics().screen(CREATE_GROUP_SCREEN) } static func ScreenGroupDetails(props: [NSObject : AnyObject]!) -> Void { SEGAnalytics.sharedAnalytics().screen(GROUP_DETAILS_SCREEN, properties: props) } static func ScreenAllGroups() -> Void { SEGAnalytics.sharedAnalytics().screen(ALL_GROUPS_SCREEN) } static func ScreenMessageWall(props: [NSObject : AnyObject]!) -> Void { SEGAnalytics.sharedAnalytics().screen(MESSAGE_WALL_SCREEN, properties: props) } static func ScreenMyGroups() -> Void { SEGAnalytics.sharedAnalytics().screen(MY_GROUPS_SCREEN) } static func ScreenEvents() -> Void { SEGAnalytics.sharedAnalytics().screen(EVENTS_SCREEN) } static func TrackRegistrationSuccess() { SEGAnalytics.sharedAnalytics().track("Registration Success"); } static func TrackRegistrationFailed() { SEGAnalytics.sharedAnalytics().track("Registration Failed"); } static func TrackRegistrationPicUploadFailed() { SEGAnalytics.sharedAnalytics().track("Registration Pic Upload Failed"); } static func TrackRegistrationAttempt(){ SEGAnalytics.sharedAnalytics().track("Registration Attempt"); } static func TrackInvalidRegistrationInfo(){ SEGAnalytics.sharedAnalytics().track("Invalid Registration Info"); } static func TrackLoginSuccess() -> Void { SEGAnalytics.sharedAnalytics().track("Login Success") } static func TrackLoginFailed() -> Void { SEGAnalytics.sharedAnalytics().track("Login Failed") } static func ScreenLogin() -> Void { SEGAnalytics.sharedAnalytics().screen(LOGIN_SCREEN) } static func ScreenRegistration() -> Void { SEGAnalytics.sharedAnalytics().screen(REGISTRATION_SCREEN) } static func AliasAndIdentifyUser() { SEGAnalytics.sharedAnalytics().alias(PFUser.currentUser()?.objectId) SEGAnalytics.sharedAnalytics().identify(PFUser.currentUser()?.objectId, traits: ["name" : (PFUser.currentUser()?.valueForKey("displayName") as! String), "email" : (PFUser.currentUser()?.email as String!)]) } static func ScreenAlerts() -> Void { SEGAnalytics.sharedAnalytics().screen(ALERTS_SCREEN) } static func TrackLoginAttempt() -> Void { SEGAnalytics.sharedAnalytics().track("Login Attempt") } static func TrackGroupCreationFailed() -> Void { SEGAnalytics.sharedAnalytics().track("Group Creation Failed") } static func TrackGroupCreated(props : [NSObject : AnyObject]!) -> Void { SEGAnalytics.sharedAnalytics().track("Group Created", properties: props) } static func TrackAlertCreationFailed() -> Void { SEGAnalytics.sharedAnalytics().track("Alert Creation Failed") } static func TrackMessageCreationFailed() -> Void { SEGAnalytics.sharedAnalytics().track("Message Creation Failed") } static func TrackMessageCreated() -> Void { SEGAnalytics.sharedAnalytics().track("Message Created") } static func TrackAlertCreated() -> Void { SEGAnalytics.sharedAnalytics().track("Alert Created") } static func TrackUserLoggedOut() { SEGAnalytics.sharedAnalytics().track("User Logged Out") } }
gpl-3.0
1c498447e101634b863333f53a41fc4a
27.19697
92
0.653949
5.093978
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/ImagePicker/ImagePickerController.swift
12
2390
// // ImagePickerController.swift // RxExample // // Created by Segii Shulga on 1/5/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class ImagePickerController: ViewController { @IBOutlet var imageView: UIImageView! @IBOutlet var cameraButton: UIButton! @IBOutlet var galleryButton: UIButton! @IBOutlet var cropButton: UIButton! override func viewDidLoad() { super.viewDidLoad() cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) cameraButton.rx.tap .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(self) { picker in picker.sourceType = .camera picker.allowsEditing = false } .flatMap { $0.rx.didFinishPickingMediaWithInfo } .take(1) } .map { info in return info[UIImagePickerControllerOriginalImage] as? UIImage } .bind(to: imageView.rx.image) .disposed(by: disposeBag) galleryButton.rx.tap .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(self) { picker in picker.sourceType = .photoLibrary picker.allowsEditing = false } .flatMap { $0.rx.didFinishPickingMediaWithInfo } .take(1) } .map { info in return info[UIImagePickerControllerOriginalImage] as? UIImage } .bind(to: imageView.rx.image) .disposed(by: disposeBag) cropButton.rx.tap .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(self) { picker in picker.sourceType = .photoLibrary picker.allowsEditing = true } .flatMap { $0.rx.didFinishPickingMediaWithInfo } .take(1) } .map { info in return info[UIImagePickerControllerEditedImage] as? UIImage } .bind(to: imageView.rx.image) .disposed(by: disposeBag) } }
mit
287622fd84f493850ece21225cac35aa
30.434211
87
0.554625
5.466819
false
false
false
false
kiliankoe/ParkenDD
Pods/ParkKit/Sources/ParkKit.swift
1
6086
// // ParkError.swift // ParkKit // // Created by Kilian Költzsch on 03/01/2017. // Copyright © 2017 Kilian Koeltzsch. All rights reserved. // import Foundation typealias JSON = [String: Any] /// All methods to fetch data from the server are built into this type. public struct ParkKit { internal let serverURL: URL /// Initialize a new client with a server URL. Defaults to server at parkendd.de if no URL is provided. /// /// - Parameter url: optional custom server URL public init(withURL url: URL = URL(string: "https://api.parkendd.de")!) { self.serverURL = url } /// Fetch all cities known to the server. /// /// - Parameter completion: handler given a Result containing further information public func fetchCities(completion: @escaping (Result<MetaResponse>) -> Void) { fetchJSON(url: serverURL) { result in switch result { case let .failure(error): completion(Result(failure: error)) return case let .success(json): let apiVersion = (json["api_version"] as? String) ?? "" let serverVersion = (json["server_version"] as? String) ?? "" let reference = (json["reference"] as? String) ?? "" guard let citiesDict = json["cities"] as? JSON else { completion(Result(failure: ParkError.decoding)); return } let cities = citiesDict.flatMap { (_: String, value: Any) -> City? in guard let details = value as? JSON else { return nil } return try? City(object: details) }.sorted { $0.name < $1.name } let response = MetaResponse(apiVersion: apiVersion, serverVersion: serverVersion, reference: reference, cities: cities) completion(Result(success: response)) } } } /// Fetch all known lots for a given city. /// /// - Parameters: /// - city: city name /// - completion: handler given a Result containing further information public func fetchLots(forCity city: String, completion: @escaping (Result<LotResponse>) -> Void) { guard let url = URL(string: city, relativeTo: serverURL) else { completion(Result(failure: ParkError.invalidServerURL)); return } fetchJSON(url: url) { result in switch result { case let .failure(error): completion(Result(failure: error)) return case let .success(json): let lastDownloadedStr = (json["last_downloaded"] as? String) ?? "" let lastUpdatedStr = (json["last_updated"] as? String) ?? "" let iso = DateFormatter.iso let lastDownloaded = iso.date(from: lastDownloadedStr) ?? Date() let lastUpdated = iso.date(from: lastUpdatedStr) ?? Date() guard let lotsArr = json["lots"] as? [JSON] else { completion(Result(failure: ParkError.decoding)); return } let lots = lotsArr.flatMap { return try? Lot(object: $0) } let response = LotResponse(lastDownloaded: lastDownloaded, lastUpdated: lastUpdated, lots: lots) completion(Result(success: response)) } } } /// Fetch forecast data for a given lot and city. /// /// - Parameters: /// - lot: lot identifier /// - city: city name /// - start: starting date /// - end: ending date /// - completion: handler given a Result containing further information public func fetchForecast(forLot lot: String, inCity city: String, startingAt start: Date, endingAt end: Date, completion: @escaping (Result<ForecastResponse>) -> Void) { let iso = DateFormatter.iso guard let url = URL(string: "\(city)/\(lot)/timespan?from=\(iso.string(from: start))&to=\(iso.string(from: end))", relativeTo: serverURL) else { completion(Result(failure: ParkError.invalidServerURL)); return } fetchJSON(url: url) { result in switch result { case let .failure(error): completion(Result(failure: error)) return case let .success(json): let version = (json["version"] as? Double) ?? -1 guard let data = json["data"] as? [String: String] else { completion(Result(failure: ParkError.decoding)); return } let forecast = data.flatMap { (key: String, value: String) -> (Date, Int)? in guard let date = iso.date(from: key), let load = Int(value) else { return nil } return (date, load) }.sorted { first, second in first.0 < second.0 } let response = ForecastResponse(version: version, forecast: forecast) completion(Result(success: response)) } } } internal func fetchJSON(url: URL, completion: @escaping (Result<JSON>) -> Void) { URLSession.shared.dataTask(with: url) { data, resp, err in guard err == nil else { completion(Result(failure: err!)); return } guard let status = (resp as? HTTPURLResponse)?.statusCode else { completion(Result(failure: ParkError.request(nil))); return } switch status / 100 { case 4: completion(Result(failure: ParkError.notFound)) return case 5: completion(Result(failure: ParkError.server(statusCode: status))) return default: break } guard let data = data else { completion(Result(failure: ParkError.unknown)); return } guard let rawJson = try? JSONSerialization.jsonObject(with: data), let json = rawJson as? JSON else { completion(Result(failure: ParkError.decoding)) return } completion(Result(success: json)) }.resume() } }
mit
18f65aaa736cd6ee069196e055bd3cae
43.086957
218
0.573636
4.708978
false
false
false
false
petrmanek/revolver
Examples/ExampleCar/ExampleCar/NSBezierPath+hermiteInterpolation.swift
1
6503
import AppKit // Hermite Interpolation // Courtesy of http://stackoverflow.com/questions/34579957/drawing-class-drawing-straight-lines-instead-of-curved-lines extension NSBezierPath { /// Create smooth NSBezierPath using Hermite Spline /// /// This requires at least two points. /// /// Adapted from https://github.com/jnfisher/ios-curve-interpolation /// See http://spin.atomicobject.com/2014/05/28/ios-interpolating-points/ /// /// - parameter hermiteInterpolatedPoints: The array of CGPoint values. /// - parameter closed: Whether the path should be closed or not /// /// - returns: An initialized `NSBezierPath`, or `nil` if an object could not be created for some reason (e.g. not enough points). convenience init?(hermiteInterpolatedPoints points:[CGPoint], closed: Bool) { self.init() guard points.count > 1 else { return nil } let numberOfCurves = closed ? points.count : points.count - 1 var previousPoint: CGPoint? = closed ? points.last : nil var currentPoint: CGPoint = points[0] var nextPoint: CGPoint? = points[1] moveToPoint(currentPoint) for index in 0 ..< numberOfCurves { let endPt = nextPoint! var mx: CGFloat var my: CGFloat if previousPoint != nil { mx = (nextPoint!.x - currentPoint.x) * 0.5 + (currentPoint.x - previousPoint!.x)*0.5 my = (nextPoint!.y - currentPoint.y) * 0.5 + (currentPoint.y - previousPoint!.y)*0.5 } else { mx = (nextPoint!.x - currentPoint.x) * 0.5 my = (nextPoint!.y - currentPoint.y) * 0.5 } let ctrlPt1 = CGPoint(x: currentPoint.x + mx / 3.0, y: currentPoint.y + my / 3.0) previousPoint = currentPoint currentPoint = nextPoint! let nextIndex = index + 2 if closed { nextPoint = points[nextIndex % points.count] } else { nextPoint = nextIndex < points.count ? points[nextIndex % points.count] : nil } if nextPoint != nil { mx = (nextPoint!.x - currentPoint.x) * 0.5 + (currentPoint.x - previousPoint!.x) * 0.5 my = (nextPoint!.y - currentPoint.y) * 0.5 + (currentPoint.y - previousPoint!.y) * 0.5 } else { mx = (currentPoint.x - previousPoint!.x) * 0.5 my = (currentPoint.y - previousPoint!.y) * 0.5 } let ctrlPt2 = CGPoint(x: currentPoint.x - mx / 3.0, y: currentPoint.y - my / 3.0) curveToPoint(endPt, controlPoint1: ctrlPt1, controlPoint2: ctrlPt2) } if closed { closePath() } } /// Create smooth NSBezierPath using Catmull-Rom Splines /// /// This requires at least four points. /// /// Adapted from https://github.com/jnfisher/ios-curve-interpolation /// See http://spin.atomicobject.com/2014/05/28/ios-interpolating-points/ /// /// - parameter catmullRomInterpolatedPoints: The array of CGPoint values. /// - parameter closed: Whether the path should be closed or not /// - parameter alpha: The alpha factor to be applied to Catmull-Rom spline. /// /// - returns: An initialized `NSBezierPath`, or `nil` if an object could not be created for some reason (e.g. not enough points). convenience init?(catmullRomInterpolatedPoints points:[CGPoint], closed: Bool, alpha: Float) { self.init() guard points.count > 3 else { return nil } assert(alpha >= 0 && alpha <= 1.0, "Alpha must be between 0 and 1") let endIndex = closed ? points.count : points.count - 2 let startIndex = closed ? 0 : 1 let kEPSILON: Float = 1.0e-5 moveToPoint(points[startIndex]) for index in startIndex ..< endIndex { let nextIndex = (index + 1) % points.count let nextNextIndex = (nextIndex + 1) % points.count let previousIndex = index < 1 ? points.count - 1 : index - 1 let point0 = points[previousIndex] let point1 = points[index] let point2 = points[nextIndex] let point3 = points[nextNextIndex] let d1 = hypot(Float(point1.x - point0.x), Float(point1.y - point0.y)) let d2 = hypot(Float(point2.x - point1.x), Float(point2.y - point1.y)) let d3 = hypot(Float(point3.x - point2.x), Float(point3.y - point2.y)) let d1a2 = powf(d1, alpha * 2) let d1a = powf(d1, alpha) let d2a2 = powf(d2, alpha * 2) let d2a = powf(d2, alpha) let d3a2 = powf(d3, alpha * 2) let d3a = powf(d3, alpha) var controlPoint1: CGPoint, controlPoint2: CGPoint if fabs(d1) < kEPSILON { controlPoint1 = point2 } else { controlPoint1 = (point2 * d1a2 - point0 * d2a2 + point1 * (2 * d1a2 + 3 * d1a * d2a + d2a2)) / (3 * d1a * (d1a + d2a)) } if fabs(d3) < kEPSILON { controlPoint2 = point2 } else { controlPoint2 = (point1 * d3a2 - point3 * d2a2 + point2 * (2 * d3a2 + 3 * d3a * d2a + d2a2)) / (3 * d3a * (d3a + d2a)) } curveToPoint(point2, controlPoint1: controlPoint1, controlPoint2: controlPoint2) } if closed { closePath() } } } // Some functions to make the Catmull-Rom splice code a little more readable. // These multiply/divide a `CGPoint` by a scalar and add/subtract one `CGPoint` // from another. private func * (lhs: CGPoint, rhs: Float) -> CGPoint { return CGPoint(x: lhs.x * CGFloat(rhs), y: lhs.y * CGFloat(rhs)) } private func / (lhs: CGPoint, rhs: Float) -> CGPoint { return CGPoint(x: lhs.x / CGFloat(rhs), y: lhs.y / CGFloat(rhs)) } private func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } private func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) }
mit
a3a85da36cb7ee3288991f9c43c9e07c
38.652439
135
0.546363
3.984681
false
false
false
false
Sojjocola/EladeDroneControl
EladeDroneControl/AppDelegate.swift
1
2928
// // AppDelegate.swift // EladeDroneControl // // Created by François Chevalier on 20/09/2015. // Copyright © 2015 François Chevalier. All rights reserved. // import UIKit import Starscream import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var locationManager:CLLocationManager? var port:String? var host:String? var socket:WebSocket? var droneStartBehaviour:DroneStartBehaviour? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. port = "8888" host = "192.168.1.123" locationManager = CLLocationManager() locationManager?.requestWhenInUseAuthorization() locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation 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:. } } extension UINavigationController { public override func preferredStatusBarStyle() -> UIStatusBarStyle { if let rootViewController = self.viewControllers.first { return rootViewController.preferredStatusBarStyle() } return self.preferredStatusBarStyle() } }
mit
885d9577e72688f5d33c0157de4f2556
42.029412
285
0.742906
5.746562
false
false
false
false
937447974/YJCocoa
YJCocoa/Classes/AppFrameworks/UIKit/CollectionView/YJUICollectionView.swift
1
1660
// // YJUICollectionView.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/5/23. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import UIKit @objcMembers open class YJUICollectionView: UICollectionView { /// 管理器 public lazy var manager: YJUICollectionViewManager! = { return YJUICollectionViewManager(collectionView: self) }() /// header 数据源 public var dataSourceHeader: Array<YJUICollectionCellObject> { get {return self.manager.dataSourceHeader} set {self.manager.dataSourceHeader = newValue} } /// footer 数据源 public var dataSourceFooter: Array<YJUICollectionCellObject> { get {return self.manager.dataSourceFooter} set {self.manager.dataSourceFooter = newValue} } /// cell 数据源 public var dataSourceCell: Array<Array<YJUICollectionCellObject>> { get {return self.manager.dataSourceCell} set {self.manager.dataSourceCell = newValue} } /// cell 第一组数据源 public var dataSourceCellFirst: Array<YJUICollectionCellObject> { get {return self.manager.dataSourceCellFirst} set {self.manager.dataSourceCellFirst = newValue} } public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.delegate = self.manager self.dataSource = self.manager } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
82c7fb7ecf6b5d0eb33f91b29a7b1d66
29.865385
94
0.685358
4.612069
false
false
false
false
Pradeepkn/Mysore_App
MysoreApp/Network/TTNetwork/TTNetworkConstants/TTNetworkContants.swift
1
407
// // TTNetworkContants.swift // TTNetwork // // Created by Pradeep on 5/11/16. // import Foundation /// MARK : Database struct Database { struct Entities { static let APICache = "APICache" } struct APICacheFields { static let Key = "key" static let Value = "value" static let CreatedAt = "createdAt" static let ExpiresAt = "expiresAt" } }
mit
3a52c4a05429f329cadad2ce9f3f1dfc
16.695652
42
0.597052
3.666667
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Tag/TagView/JSTagItem.swift
1
4370
// // JSTagItem.swift // BeeFun // // Created by WengHengcong on 14/05/2017. // Copyright © 2017 JungleSong. All rights reserved. // import UIKit protocol JSTagItemTouchProtocol: class { func touchTag(sender: JSTagItem, index: Int) } class JSTagItem: UIView { /// itme title var title: String? { didSet { setTitleAllState(title: title!) } } weak var delegate: JSTagItemTouchProtocol? var font: UIFont? = UIFont.bfSystemFont(ofSize: 15.0) { didSet { titleBtn.titleLabel?.font = font } } var align: NSTextAlignment? = .center { didSet { titleBtn.titleLabel?.textAlignment = align! } } var foreColor: UIColor? = .black { didSet { titleBtn.setTitleColor(foreColor, for: .normal) } } var backColor: UIColor? = .white { didSet { titleBtn.backgroundColor = backColor } } var attributeTitle: NSAttributedString? { didSet { titleBtn.titleLabel?.attributedText = attributeTitle } } var isSelected: Bool? = false { didSet { didSelectedTagButtion() } } var contentWidth: CGFloat { if self.title != nil { let width = self.title!.width(with: self.height, font: self.font!) return width+30 } return 0 } private lazy var titleBtn = UIButton() override init(frame: CGRect) { super.init(frame: frame) } convenience init(title: String?) { assert(title != nil, "JSTagItem title can't nil") self.init(title: title, frame: CGRect.zero) } convenience init(title: String?, frame: CGRect) { assert(title != nil, "JSTagItem title can't nil") self.init(frame: frame) //初始化View commonInitView() //设置标题 self.title = title setTitleAllState(title: title!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func commonInitView() { setTitleColor(.black, for: .normal) setTitleColor(.bfRedColor, for: .highlighted) setTitleColor(.bfRedColor, for: .selected) titleBtn.addTarget(self, action: #selector(touchItem(sengder:)), for: .touchUpInside) // titleBtn.backgroundColor = UIColor.green self.addSubview(titleBtn) } override func layoutSubviews() { super.layoutSubviews() titleBtn.frame = CGRect(x: 0, y: 0, w: self.contentWidth, h: self.height) self.frame = CGRect(x: self.x, y: self.y, w: self.contentWidth, h: self.height) } func didSelectedTagButtion() { if isSelected != nil { touchItem(sengder: titleBtn) } } func setTitle(_ title: String?, for state: UIControlState) { titleBtn.setTitle(title, for: state) } func setTitleColor(_ color: UIColor?, for state: UIControlState) { titleBtn.setTitleColor(color, for: state) } func setImage(_ image: UIImage?, for state: UIControlState) { titleBtn.setImage(image, for: state) } func setBackgroundImage(_ image: UIImage?, for state: UIControlState) { titleBtn.setBackgroundImage(image, for: state) } func setAttributedTitle(_ title: NSAttributedString?, for state: UIControlState) { titleBtn.setAttributedTitle(title, for: state) } func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents) { titleBtn.addTarget(target, action: action, for: controlEvents) } func setTitleAllState(title: String) { titleBtn.setTitle(title, for: .normal) titleBtn.setTitle(title, for: .highlighted) titleBtn.setTitle(title, for: .selected) } @objc func touchItem(sengder: UIButton) { if sengder.isKind(of: UIButton.self) { if sengder.isSelected { return } else { //选中 sengder.isSelected = true self.delegate?.touchTag(sender: self, index: self.tag) } } } func setTagUnselected() { titleBtn.isSelected = false } }
mit
940d5445ea0f632df1287f2c96c254f7
25.858025
93
0.580326
4.485567
false
false
false
false
naebada-dev/swift
language-guide/Tests/language-guideTests/methods/TypeMethodTests.swift
1
2149
import XCTest class TypeMethodTests : XCTestCase { override func setUp() { super.setUp(); print("############################"); } override func tearDown() { print("############################"); super.tearDown(); } /* 클래스, 구조체, 열거형은 타입 메소드를 가질 수 있다. 타입 메소드는 static 키워드를 사용한다. 클래스의 경우 서브클래스에서 오버라이딩을 허용하기 위해서 class 키워드를 사용할 수 있다. */ func testMethodType() { var player = Player(name: "Argyrios") player.complete(level: 1) print("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)") player = Player(name: "Beto") if player.tracker.advance(to: 6) { print("player is now on level 6") } else { print("level 6 has not yet been unlocked") } } private struct LevelTracker { // type property static var highestUnlockedLevel = 1 var currentLevel = 1 // type method static func unlock(_ level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } static func isUnlocked(_ level: Int) -> Bool { return level <= highestUnlockedLevel } // 값을 반환하는 function/method를 반환값을 사용하지 ㅇ낳고 호출할 때 // compiler warning을 숨기기 위해 사용 @discardableResult mutating func advance(to level: Int) -> Bool { if LevelTracker.isUnlocked(level) { currentLevel = level return true } else { return false } } } private class Player { var tracker = LevelTracker() let playerName: String init(name: String) { playerName = name } func complete(level: Int) { LevelTracker.unlock(level + 1) tracker.advance(to: level + 1) } } }
apache-2.0
45842080f8b87377499f46ac9b284ab6
23.037037
83
0.508988
4.375281
false
false
false
false
SinnerSchraderMobileMirrors/Alamofire
Tests/DownloadTests.swift
13
4682
// DownloadTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Alamofire import XCTest class AlamofireDownloadResponseTestCase: XCTestCase { let searchPathDirectory: NSSearchPathDirectory = .DocumentDirectory let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask // MARK: - func testDownloadRequest() { let numberOfLines = 100 let URL = "http://httpbin.org/stream/\(numberOfLines)" let expectation = expectationWithDescription(URL) let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain) Alamofire.download(.GET, URL, destination) .response { request, response, _, error in XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNil(error, "error should be nil") let fileManager = NSFileManager.defaultManager() let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL var fileManagerError: NSError? let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: &fileManagerError)! XCTAssertNil(fileManagerError, "fileManagerError should be nil") #if os(iOS) let suggestedFilename = "\(numberOfLines)" #elseif os(OSX) let suggestedFilename = "\(numberOfLines).json" #endif let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'") let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate) XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents") let file = filteredContents.first as! NSURL XCTAssertEqual(file.lastPathComponent!, "\(suggestedFilename)", "filename should be \(suggestedFilename)") if let data = NSData(contentsOfURL: file) { XCTAssertGreaterThan(data.length, 0, "data length should be non-zero") } else { XCTFail("data should exist for contents of URL") } fileManager.removeItemAtURL(file, error: nil) expectation.fulfill() } waitForExpectationsWithTimeout(10) { error in XCTAssertNil(error, "\(error)") } } func testDownloadRequestWithProgress() { let numberOfLines = 100 let URL = "http://httpbin.org/stream/\(numberOfLines)" let expectation = expectationWithDescription(URL) let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain) let download = Alamofire.download(.GET, URL, destination) download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in XCTAssert(bytesRead > 0, "bytesRead should be > 0") XCTAssert(totalBytesRead > 0, "totalBytesRead should be > 0") XCTAssert(totalBytesExpectedToRead == -1, "totalBytesExpectedToRead should be -1") download.cancel() expectation.fulfill() } waitForExpectationsWithTimeout(10) { error in XCTAssertNil(error, "\(error)") } } }
mit
359996fc35da1663e91f4ffd8e70e14f
42.738318
195
0.676709
5.672727
false
true
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/WPStyleGuide+Blog.swift
2
1770
import Foundation import WordPressShared extension WPStyleGuide { @objc public class func configureTableViewBlogCell(_ cell: UITableViewCell) { cell.textLabel?.font = tableviewTextFont() cell.textLabel?.sizeToFit() cell.textLabel?.textColor = .text cell.detailTextLabel?.font = self.subtitleFont() cell.detailTextLabel?.sizeToFit() cell.detailTextLabel?.textColor = .textSubtle cell.imageView?.layer.borderColor = UIColor.divider.cgColor cell.imageView?.layer.borderWidth = .hairlineBorderWidth cell.imageView?.tintColor = .listIcon cell.backgroundColor = UIColor.listForeground } @objc public class func configureCellForLogin(_ cell: WPBlogTableViewCell) { cell.textLabel?.textColor = .text cell.detailTextLabel?.textColor = .textSubtle let fontSize = UIFont.preferredFont(forTextStyle: .subheadline).pointSize cell.textLabel?.font = UIFont.systemFont(ofSize: fontSize, weight: .medium) cell.detailTextLabel?.font = UIFont.systemFont(ofSize: fontSize, weight: .regular) cell.imageView?.tintColor = .listIcon cell.selectionStyle = .none cell.backgroundColor = .basicBackground } } extension LoginEpilogueBlogCell { // Per Apple's documentation (https://developer.apple.com/documentation/xcode/supporting_dark_mode_in_your_interface), // `cgColor` objects do not adapt to appearance changes (i.e. toggling light/dark mode). // `tintColorDidChange` is called when the appearance changes, so re-set the border color when this occurs. override func tintColorDidChange() { super.tintColorDidChange() imageView?.layer.borderColor = UIColor.neutral(.shade10).cgColor } }
gpl-2.0
a1601611ab730aa78e1890246435d675
38.333333
122
0.711299
4.957983
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/ProjectPamphletCreatorHeaderCellViewModel.swift
1
3320
import Foundation import KsApi import ReactiveSwift import UIKit public protocol ProjectPamphletCreatorHeaderCellViewModelInputs { func configure(with project: Project) func viewProgressButtonTapped() } public protocol ProjectPamphletCreatorHeaderCellViewModelOutputs { var buttonTitle: Signal<String, Never> { get } var launchDateLabelAttributedText: Signal<NSAttributedString, Never> { get } var notifyDelegateViewProgressButtonTapped: Signal<Project, Never> { get } } public protocol ProjectPamphletCreatorHeaderCellViewModelType { var inputs: ProjectPamphletCreatorHeaderCellViewModelInputs { get } var outputs: ProjectPamphletCreatorHeaderCellViewModelOutputs { get } } public final class ProjectPamphletCreatorHeaderCellViewModel: ProjectPamphletCreatorHeaderCellViewModelType, ProjectPamphletCreatorHeaderCellViewModelInputs, ProjectPamphletCreatorHeaderCellViewModelOutputs { public init() { self.buttonTitle = self.projectSignal .map(title(for:)) self.launchDateLabelAttributedText = self.projectSignal .map(attributedLaunchDateString(with:)) .skipNil() self.notifyDelegateViewProgressButtonTapped = self.projectSignal .takeWhen(self.viewProgressButtonTappedSignal.ignoreValues()) } private let (projectSignal, projectObserver) = Signal<Project, Never>.pipe() public func configure(with project: Project) { self.projectObserver.send(value: project) } private let (viewProgressButtonTappedSignal, viewProgressButtonTappedObserver) = Signal<Void, Never>.pipe() public func viewProgressButtonTapped() { self.viewProgressButtonTappedObserver.send(value: ()) } public let buttonTitle: Signal<String, Never> public let launchDateLabelAttributedText: Signal<NSAttributedString, Never> public let notifyDelegateViewProgressButtonTapped: Signal<Project, Never> public var inputs: ProjectPamphletCreatorHeaderCellViewModelInputs { return self } public var outputs: ProjectPamphletCreatorHeaderCellViewModelOutputs { return self } } private func title(for project: Project) -> String { return project.state == .live ? Strings.View_progress() : Strings.View_dashboard() } private func attributedLaunchDateString(with project: Project) -> NSAttributedString? { let date = Format.date( secondsInUTC: project.dates.launchedAt, dateStyle: .long, timeStyle: .none, timeZone: UTCTimeZone ) let fullString = Strings.You_launched_this_project_on_launch_date(launch_date: date) let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: fullString) let fullRange = (fullString as NSString).localizedStandardRange(of: fullString) let rangeDate: NSRange = (fullString as NSString).localizedStandardRange(of: date) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .left let regularFontAttribute = [ NSAttributedString.Key.paragraphStyle: paragraphStyle, NSAttributedString.Key.font: UIFont.ksr_subhead(), NSAttributedString.Key.foregroundColor: UIColor.ksr_support_700 ] let boldFontAttribute = [NSAttributedString.Key.font: UIFont.ksr_subhead().bolded] attributedString.addAttributes(regularFontAttribute, range: fullRange) attributedString.addAttributes(boldFontAttribute, range: rangeDate) return attributedString }
apache-2.0
9e4ba6f06d3b64cd3836bc69599620fd
37.604651
108
0.798494
5.286624
false
false
false
false
kickstarter/ios-oss
Library/UIDeviceType.swift
1
1392
import UIKit /** * A type that behaves like a UIDevice. */ public protocol UIDeviceType { var identifierForVendor: UUID? { get } var modelCode: String { get } var orientation: UIDeviceOrientation { get } var systemVersion: String { get } var userInterfaceIdiom: UIUserInterfaceIdiom { get } } extension UIDevice: UIDeviceType { public var modelCode: String { var size: Int = 0 sysctlbyname("hw.machine", nil, &size, nil, 0) var machine = [CChar](repeating: 0, count: Int(size)) sysctlbyname("hw.machine", &machine, &size, nil, 0) return String(cString: machine) } } internal struct MockDevice: UIDeviceType { internal var identifierForVendor = UUID(uuidString: "DEADBEEF-DEAD-BEEF-DEAD-DEADBEEFBEEF") internal var modelCode = "MockmodelCode" internal var orientation: UIDeviceOrientation internal var systemVersion: String = "MockSystemVersion" internal var userInterfaceIdiom: UIUserInterfaceIdiom internal init( userInterfaceIdiom: UIUserInterfaceIdiom = .phone, orientation: UIDeviceOrientation = .portrait ) { self.userInterfaceIdiom = userInterfaceIdiom self.orientation = orientation } } extension UIDeviceType { var deviceType: String { switch self.userInterfaceIdiom { case .phone: return "phone" case .pad: return "tablet" case .tv: return "tv" default: return "unspecified" } } }
apache-2.0
d633b046821da376b9ce01f4891b8ce0
27.408163
93
0.719828
4.419048
false
false
false
false
apple/swift-experimental-string-processing
Sources/_StringProcessing/Utility/Protocols.swift
1
1579
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 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 // //===----------------------------------------------------------------------===// // These currently only drive tracing/formatting, but could drive // more protocol InstructionProtocol { var operandPC: InstructionAddress? { get } } protocol ProcessorProtocol { associatedtype Input: Collection associatedtype Instruction: InstructionProtocol associatedtype SavePoint = () associatedtype Registers = () var cycleCount: Int { get } var input: Input { get } var currentPosition: Input.Index { get } var currentPC: InstructionAddress { get } var instructions: InstructionList<Instruction> { get } var isAcceptState: Bool { get } var isFailState: Bool { get } // Provide to get call stack formatting, default empty var callStack: Array<InstructionAddress> { get } // Provide to get save point formatting, default empty var savePoints: Array<SavePoint> { get } // Provide to get register formatting, default empty var registers: Registers { get } } extension ProcessorProtocol { func fetch() -> Instruction { instructions[currentPC] } var callStack: Array<InstructionAddress> { [] } // var savePoints: Array<SavePoint> { [] } var registers: Array<Registers> { [] } }
apache-2.0
2e5d01ade9c201475540f6a80c7a6355
27.196429
80
0.650412
4.727545
false
false
false
false
tutao/tutanota
app-ios/tutanota/Sources/Keychain/KeychainManager.swift
1
10651
import Foundation import LocalAuthentication #if !targetEnvironment(simulator) import CryptoTokenKit #endif private let TAG = "de.tutao.tutanota.notificationkey." private let KEY_PERMANENTLY_INVALIDATED_ERROR_DOMAIN = "de.tutao.tutanota.KeyPermanentlyInvalidatedError" private let CREDENTIAL_AUTHENTICATION_ERROR_DOMAIN = "de.tutao.tutanota.CredentialAuthenticationError" class KeyPermanentlyInvalidatedError : TutanotaError { init(underlyingError: Error) { super.init(message: underlyingError.localizedDescription, underlyingError: underlyingError) } override var name: String { get { return KEY_PERMANENTLY_INVALIDATED_ERROR_DOMAIN } } } class CredentialAuthenticationError : TutanotaError { init(underlyingError: Error) { super.init(message: underlyingError.localizedDescription, underlyingError: underlyingError) } override var name: String { get { return CREDENTIAL_AUTHENTICATION_ERROR_DOMAIN } } } class KeychainManager : NSObject { private static let DEVICE_LOCK_DATA_KEY_ALIAS = "DeviceLockDataKey" private static let SYSTEM_PASSWORD_DATA_KEY_ALIAS = "SystemPasswordDataKey" private static let BIOMETRICS_DATA_KEY_ALIAS = "BiometricsDataKey" private static let DATA_ALGORITHM = SecKeyAlgorithm.eciesEncryptionCofactorVariableIVX963SHA256AESGCM private let keyGenerator: KeyGenerator init(keyGenerator: KeyGenerator) { self.keyGenerator = keyGenerator } func storeKey(_ key: Data, withId keyId: String) throws { let keyTag = self.keyTagFromKeyId(keyId: keyId) let existingKey = try? self.getKey(keyId: keyId) let status: OSStatus if let key = existingKey { let updateQuery: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: keyTag ] let updateFields: [String: Any] = [ kSecValueData as String: key, kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly ] status = SecItemUpdate(updateQuery as CFDictionary, updateFields as CFDictionary) } else { let addQuery: [String: Any] = [ kSecValueData as String: key, kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: keyTag, kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly ] status = SecItemAdd(addQuery as CFDictionary, nil) } if status != errSecSuccess { throw TUTErrorFactory.createError("Could not store the key, status: \(status)") } } func getKey(keyId: String) throws -> Data? { let keyTag = self.keyTagFromKeyId(keyId: keyId) let getQuery: [String : Any] = [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: keyTag, kSecReturnData as String: true ] var item: CFTypeRef? let status = SecItemCopyMatching(getQuery as CFDictionary, &item) if status != errSecSuccess { throw TUTErrorFactory.createError("Failed to get key \(keyId). status: \(status)") as NSError } else if let item = item { return (item as! Data) } else { return nil } } func removePushIdentifierKeys() throws { // TODO: Don't delete all of teh keyz when fingerprints let deleteQuery: [String: Any] = [ kSecClass as String: kSecClassKey ] let status = SecItemDelete(deleteQuery as CFDictionary) if status != errSecSuccess { throw TUTErrorFactory.createError("Could not delete the keys, status: \(status)") } } private func deleteKey(tag: String) throws { let deleteQuery: [String : Any] = [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: tag ] let status = SecItemDelete(deleteQuery as CFDictionary) if status != errSecSuccess { throw TUTErrorFactory.createError("Failed to delete key: \(status)") } } func encryptData(encryptionMode: CredentialEncryptionMode, data: Data) throws -> Data { let privateKey = try self.getDataKey(mode: encryptionMode) guard let publicKey = SecKeyCopyPublicKey(privateKey) else { throw TUTErrorFactory.createError("Cannot get public key from private key for mode \(encryptionMode)") } var error: Unmanaged<CFError>? let encryptedData = SecKeyCreateEncryptedData(publicKey, Self.DATA_ALGORITHM, data as CFData, &error) as Data? guard let encryptedData = encryptedData else { switch try self.handleKeychainError(error!, mode: encryptionMode) { case .unrecoverable(let error): throw error case .recoverable(let error): TUTSLog("Trying to recover from error \(error)") return try self.encryptData(encryptionMode: encryptionMode, data: data) } } return encryptedData } func decryptData(encryptionMode: CredentialEncryptionMode, encryptedData: Data) throws -> Data { let key = try self.getDataKey(mode: encryptionMode) var error: Unmanaged<CFError>? let decryptedData = SecKeyCreateDecryptedData(key, Self.DATA_ALGORITHM, encryptedData as CFData, &error) as Data? guard let decryptedData = decryptedData else { switch try self.handleKeychainError(error!, mode: encryptionMode) { case .unrecoverable(let error): throw error case .recoverable(let error): TUTSLog("Trying to recover from error \(error)") return try self.decryptData(encryptionMode: encryptionMode, encryptedData: encryptedData) } } return decryptedData } private func getDataKey(mode: CredentialEncryptionMode) throws -> SecKey { let tag = self.keyAlias(for: mode) return try self.fetchDataKey(tag: tag) ?? self.generateDataKey(tag: tag, mode: mode) } private func keyAlias(for encryptionMode: CredentialEncryptionMode) -> String { switch encryptionMode { case .deviceLock: return Self.DEVICE_LOCK_DATA_KEY_ALIAS case .systemPassword: return Self.SYSTEM_PASSWORD_DATA_KEY_ALIAS case .biometrics: return Self.BIOMETRICS_DATA_KEY_ALIAS } } private func fetchDataKey(tag: String) throws -> SecKey? { let getQuery: [String : Any] = [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: tag, kSecReturnRef as String: true, kSecUseOperationPrompt as String: translate("TutaoUnlockCredentialsAction", default: "Unlock credentials") ] var item: CFTypeRef? let status = SecItemCopyMatching(getQuery as CFDictionary, &item) switch status { case errSecItemNotFound: return nil case errSecSuccess: return item as! SecKey? default: throw TUTErrorFactory.createError("Failed to get key \(tag). Status: \(status)") } } private func accessControl(for encryptionMethod: CredentialEncryptionMode) -> SecAccessControl { let flags: SecAccessControlCreateFlags switch encryptionMethod { case .deviceLock: flags = .privateKeyUsage case .systemPassword: flags = [.privateKeyUsage, .userPresence] case .biometrics: flags = [.privateKeyUsage, .biometryCurrentSet] } var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, flags, &error ) if let accessControl = accessControl { return accessControl } else { let error = error!.takeRetainedValue() as Error as NSError fatalError(error.debugDescription) } } private func generateDataKey(tag: String, mode: CredentialEncryptionMode) throws -> SecKey { let access = self.accessControl(for: mode) return try self.keyGenerator.generateKey(tag: tag, accessControl: access) } private func keyTagFromKeyId(keyId: String) -> Data { let keyTag = TAG + keyId return keyTag.data(using: .utf8)! } private func handleKeychainError(_ error: Unmanaged<CFError>, mode: CredentialEncryptionMode) throws -> HandledKeychainError { let parsedError = self.parseKeychainError(error) switch parsedError { case .authFailure(let error): return .unrecoverable(error: CredentialAuthenticationError(underlyingError: error)) case .lockout(error: let error): let (result, promptError) = blockOn { cb in self.showPasswordPrompt(reason: error.localizedDescription, cb) } if let error = promptError { return .unrecoverable(error: CredentialAuthenticationError(underlyingError: error)) } else if result == .some(false) { return .unrecoverable(error: CredentialAuthenticationError(underlyingError: error)) } else { return .recoverable(error: CredentialAuthenticationError(underlyingError: error)) } case .keyPermanentlyInvalidated(let error): let tag = self.keyAlias(for: mode) try self.deleteKey(tag: tag) return .unrecoverable(error: KeyPermanentlyInvalidatedError(underlyingError: error)) case .unknown(let error): let message = "Keychain operation failed with mode \(mode)" return .unrecoverable(error: TUTErrorFactory.wrapNativeError(withDomain: TUT_ERROR_DOMAIN, message: message, error: error)) } } private func showPasswordPrompt(reason: String, _ completion: @escaping (Bool?, Error?) -> Void) { DispatchQueue.main.async { LAContext() .evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason, reply: completion ) } } private func parseKeychainError(_ error: Unmanaged<CFError>) -> KeychainError { let e = error.takeRetainedValue() as Error as NSError #if !targetEnvironment(simulator) if e.domain == TKError.errorDomain && e.code == TKError.Code.corruptedData.rawValue { return .keyPermanentlyInvalidated(error: e) } #endif if e.domain == LAError.errorDomain && e.code == LAError.Code.biometryLockout.rawValue { return .lockout(error: e) } if e.domain == LAError.errorDomain { return .authFailure(error: e) } // This sometimes happens to some users for unknown reasons if e.domain == NSOSStatusErrorDomain && e.code == Security.errSecParam { return .keyPermanentlyInvalidated(error: e) } return .unknown(error: e) } } fileprivate enum HandledKeychainError { case recoverable(error: Error) case unrecoverable(error: Error) } private enum KeychainError { case authFailure(error: NSError) /// Too many attempts to use biometrics, user must authenticate with password before trying again case lockout(error: NSError) case keyPermanentlyInvalidated(error: NSError) case unknown(error: NSError) }
gpl-3.0
d75a28bf4a28f8b4b8323ffc46055d97
34.036184
129
0.707727
4.679701
false
false
false
false
piars777/TheMovieDatabaseSwiftWrapper
Sources/Models/CreditsMDB.swift
1
3442
// // CreditsMDB.swift // MDBSwiftWrapper // // Created by George on 2016-03-07. // Copyright © 2016 GeorgeKye. All rights reserved. // import Foundation public struct Credits_Episodes{ public var air_date: String! public var episode_number: Int! public var overview: String! public var season_number: Int! public var still_path: String? init(episodes: JSON){ air_date = episodes["air_date"].string episode_number = episodes["episode_number"].int overview = episodes["overview"].string season_number = episodes["season_number"].int still_path = episodes["still_path"].string } } public struct Credits_Seasons{ public var air_date: String! public var poster_path: String! public var season_number: Int! init(seasons: JSON){ air_date = seasons["air_date"].string poster_path = seasons["poster_path"].string season_number = seasons["season_number"].int } } public struct Credits_Media{ public var id: Int! public var name: String! public var original_name: String! public var character: String! public var episodes = [Credits_Episodes]() public var seasons = [Credits_Seasons]() init(media: JSON){ id = media["id"].int name = media["name"].string original_name = media["original_name"].string character = media["character"].string if(media["episodes"].count > 0){ for episode in media["episodes"]{ episodes.append(Credits_Episodes.init(episodes: episode.1)) } } if(media["seasons"].count > 0){ for i in 0...media["seasons"].count { seasons.append(Credits_Seasons.init(seasons: media["seasons"][i])) } } } } public struct CreditsMDB{ public var credit_type: String! public var department: String! public var job: String! public var media: Credits_Media! public var media_Type: String! public var id: String! public var person: (name: String!, id: Int!) init(credits: JSON){ credit_type = credits["credit_type"].string department = credits["department"].string job = credits["job"].string media = Credits_Media.init(media: credits["media"]) media_Type = credits["media_type"].string id = credits["id"].string person = (name: credits["person"]["name"].string, id: credits["person"]["id"].int) } ///Get the detailed information about a particular credit record. This is currently only supported with the new credit model found in TV. These ids can be found from any TV credit response as well as the tv_credits and combined_credits methods for people. The episodes object returns a list of episodes and are generally going to be guest stars. The season array will return a list of season numbers. public static func credits(apiKey: String, creditID: String, language: String, completion: (clientReturn: ClientReturn, data: CreditsMDB?) -> ()) -> (){ Client.Credits(apiKey, creditID: creditID, language: language){ apiReturn in if(apiReturn.error == nil){ completion(clientReturn: apiReturn, data: CreditsMDB.init(credits: apiReturn.json!)) }else{ completion(clientReturn: apiReturn, data: nil) } } } }
mit
5d270cd5787e1c098ac46c66cf785f8b
34.484536
404
0.627434
4.389031
false
false
false
false
EstefaniaGilVaquero/OrienteeringQuizIOS
OrienteeringQuiz/OrienteeringQuiz/SYBLoginViewController.swift
1
3446
// // SYBLoginViewController.swift // OrienteeringQuiz // // Created by CICE on 4/10/16. // Copyright © 2016 Symbel. All rights reserved. // import UIKit import Parse class SYBLoginViewController: UIViewController { //MARK: - VARIABLES LOCALES GLOBALES //MARK: - IBOUTLET @IBOutlet weak var myUsernameTF: UITextField! @IBOutlet weak var myPasswordTF: UITextField! @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var myAccederBTN: UIButton! @IBOutlet weak var myRegistroBTN: UIButton! //MARK: - IBACTION @IBAction func realizaLoginInParse(_ sender: Any) { if myUsernameTF.text == "" || myPasswordTF.text == ""{ showAlertVCFinal("¡Atención!", "No has rellenado todos los campos.") }else{ myActivityIndicator.isHidden = false myActivityIndicator.startAnimating() UIApplication.shared.beginIgnoringInteractionEvents() PFUser.logInWithUsername(inBackground: myUsernameTF.text!, password:myPasswordTF.text!) { (user: PFUser?, error: Error?) -> Void in self.myActivityIndicator.isHidden = true self.myActivityIndicator.stopAnimating() UIApplication.shared.endIgnoringInteractionEvents() if let error = error { if let errorString = (error as NSError).userInfo["error"] as? String { NSLog(errorString); self.showAlertVCFinal("ATENCION", errorString as String) }else{ self.showAlertVCFinal("ATENCION", "Existe un error en el login") } } else { // Hooray! Let them use the app now. NSLog("Logged in!"); self.performSegue(withIdentifier: "saltarTabBarControllerFromLogin", sender: self) } } } } override func viewDidLoad() { super.viewDidLoad() myRegistroBTN.layer.cornerRadius = 20 myAccederBTN.layer.cornerRadius = 20 myActivityIndicator.isHidden = true //let menuColo1 = UIColor(red: 0.965, green: 0.467, blue: 0.161, alpha: 1) //Naranja oscuro let menuColo1 = UIColor(red: 0.925, green: 0.517, blue: 0.0, alpha: 1) myAccederBTN.backgroundColor = menuColo1 myActivityIndicator.color = menuColo1 myRegistroBTN.backgroundColor = menuColo1 } //Si el usuario ya esta registrado pasamos al menu override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if PFUser.current() != nil{ self.performSegue(withIdentifier: "saltarTabBarControllerFromLogin", sender: self) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - ALERTVC func showAlertVCFinal(_ tituloData : String, _ mensajeData : String ){ let alertVC = UIAlertController(title: tituloData, message: mensajeData, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) present(alertVC, animated: true, completion: nil) } }
apache-2.0
a3d9dfeeca3f3f5e1b02e3b2adc03030
33.777778
104
0.598315
4.918571
false
false
false
false
taironas/gonawin-engine-ios
GonawinEngine/MatchDay.swift
1
776
// // MatchDay.swift // GonawinEngine // // Created by Remy JOURDE on 16/03/2016. // Copyright © 2016 Remy Jourde. All rights reserved. // import SwiftyJSON final public class MatchDay: JSONAble { public let day: String public let matches: [Match] public init(day: String, matches: [Match]) { self.day = day self.matches = matches } static func fromJSON(_ json: JSONDictionary) -> MatchDay { let json = JSON(json) return fromJSON(json) } static func fromJSON(_ json: JSON) -> MatchDay { let date = json["Date"].stringValue let matches = json["Matches"].arrayValue.map{ Match.fromJSON($0) } return MatchDay(day: date, matches: matches) } }
mit
dafea709ef70941a0314cb681150142a
22.484848
74
0.594839
4.057592
false
false
false
false
notohiro/NowCastMapView
NowCastMapView/Tile.swift
1
6820
// // Tile.swift // NowCastMapView // // Created by Hiroshi Noto on 9/26/15. // Copyright © 2015 Hiroshi Noto. All rights reserved. // import Foundation import MapKit /** A `Tile` structure represents a single tile file of High-resolution Precipitation Nowcasts. (http://www.jma.go.jp/en/highresorad/) For performance, you should initialize `Tile` instance by using `TileModel`. The `Tile` instances are cached by `TileModel`, and it handles duplicated requests. */ public struct Tile { // MARK: - Public Properties public let baseTime: BaseTime public let index: Int public let modifiers: Tile.Modifiers public let url: URL public var image: UIImage? public let deltas: Tile.Deltas public let coordinates: Coordinates public let mapRect: MKMapRect // MARK: - Internal Properties // MARK: - Functions internal init(image: UIImage?, baseTime: BaseTime, index: Int, modifiers: Tile.Modifiers, url: URL) { self.image = image self.baseTime = baseTime self.index = index self.modifiers = modifiers self.coordinates = Coordinates(modifiers: modifiers) self.url = url self.deltas = Tile.Deltas(zoomLevel: modifiers.zoomLevel) self.mapRect = MKMapRect(modifiers: modifiers) } /** Returns a Boolean value indicating whether the tile contains the given coordinate. Right(East) edge and Bottom(South) one of the `Tile` are not contained, because these edges are contained by next tiles, except if the `Tile` is on East or South service bound. - Parameter coordinate: The coordinate to test for containment within this tile. - Returns: Whether the tile contains the given coordinate */ internal func contains(_ coordinate: CLLocationCoordinate2D) -> Bool { let origin = coordinates.origin let terminal = coordinates.terminal let north = origin.latitude >= coordinate.latitude let west = origin.longitude <= coordinate.longitude var south: Bool var east: Bool if modifiers.isOnServiceBound().south { south = coordinate.latitude >= terminal.latitude } else { south = coordinate.latitude > terminal.latitude } if modifiers.isOnServiceBound().east { east = coordinate.longitude <= terminal.longitude } else { east = coordinate.longitude < terminal.longitude } if north && west && south && east { return true } else { return false } } /** Returns a `RGBA255` value at the given coordinate. It could be nil if the coordinate don't be contained by the `Tile`. - Parameter coordinate: The coordinate of the tile you want. - Returns: A `RGBA255` value at the given coordinate. */ public func rgba255(at coordinate: CLLocationCoordinate2D) -> RGBA255? { if contains(coordinate) == false { return nil } guard let point = point(at: coordinate) else { return nil } return image?.rgba255(at: point) } /** Returns a `CGPoint` value at the given coordinate. It could be nil if the coordinate don't be contained by the `Tile`. - Parameter coordinate: The coordinate of the tile you want. - Returns: A `CGPoint` value at the given coordinate. */ internal func point(at coordinate: CLLocationCoordinate2D) -> CGPoint? { if contains(coordinate) == false { return nil } guard let image = self.image, let position = position(at: coordinate) else { return nil } let x = floor(image.size.width * CGFloat(position.longitudePosition)) // swiftlint:disable:this identifier_name let y = floor(image.size.height * CGFloat(position.latitudePosition)) // swiftlint:disable:this identifier_name return CGPoint(x: x, y: y) } /** Returns a normalized position at the given coordinate. It could be nil if the coordinate don't be contained by the `Tile`. The return value contains two dimensional position, and are between from 0.0 to 1.0. (0,0) describes top left, (1,1) is bottom right. (1,1) will never happen because bottom right edge don't be contained by the `Tile`. - Parameter coordinate: The coordinate of the tile you want. - Returns: A normalized position at the given coordinate. */ internal func position(at coordinate: CLLocationCoordinate2D) -> (latitudePosition: Double, longitudePosition: Double)? { if contains(coordinate) == false { return nil } let latitudeNumberAsDouble = (coordinate.latitude - Constants.originLatitude) / -deltas.latitude let longitudeNumberAsDouble = (coordinate.longitude - Constants.originLongitude) / deltas.longitude let latitudePosition = latitudeNumberAsDouble - Double(modifiers.latitude) let longitudePosition = longitudeNumberAsDouble - Double(modifiers.longitude) return (latitudePosition, longitudePosition) } /** Returns a `CLLocationCoordinate2D` value at the given point. It could be nil if the point is outside of the image of `Tile`. - Parameter coordinate: The point of the tile you want. - Returns: A `CLLocationCoordinate2D` value at the given point. */ internal func coordinate(at point: CGPoint) -> CLLocationCoordinate2D? { guard let image = self.image else { return nil } if point.x < 0 || point.y < 0 || point.x >= image.size.width || point.y >= image.size.height { return nil } let latitudePosition = Double(point.y / image.size.height) let longitudePosition = Double(point.x / image.size.width) let latitudeDeltaPerPixel = deltas.latitude / Double(image.size.height) let longitudeDeltaPerPixel = deltas.longitude / Double(image.size.width) let latitude = Double(coordinates.origin.latitude) - Double(deltas.latitude * latitudePosition) - (latitudeDeltaPerPixel / 2) let longitude = Double(coordinates.origin.longitude) + Double(deltas.longitude * longitudePosition) + (longitudeDeltaPerPixel / 2) return CLLocationCoordinate2DMake(latitude, longitude) } } // MARK: - Hashable extension Tile: Hashable { public var hashValue: Int { return url.hashValue } } // MARK: - Equatable extension Tile: Equatable { public static func == (lhs: Tile, rhs: Tile) -> Bool { return lhs.hashValue == rhs.hashValue } } // MARK: - CustomStringConvertible extension Tile: CustomStringConvertible { public var description: String { return url.absoluteString } } // MARK: - CustomDebugStringConvertible extension Tile: CustomDebugStringConvertible { public var debugDescription: String { var output: [String] = [] output.append("[url]: \(url)") output.append(image != nil ? "[image]: not nil" : "[image]: nil") return output.joined(separator: "\n") } }
mit
d01a5c96c0709cf3b92f05e849a48e60
31.165094
135
0.688811
4.416451
false
false
false
false
mindbody/Conduit
Tests/ConduitTests/Auth/OAuth2RequestPipelineMiddlewareTests.swift
1
16426
// // OAuth2RequestPipelineMiddlewareTests.swift // Conduit // // Created by John Hammerlund on 7/7/17. // Copyright © 2017 MINDBODY. All rights reserved. // import XCTest @testable import Conduit class CustomRefreshTokenGrantStrategy: OAuth2TokenGrantStrategy { enum Error: Swift.Error { case didExecute } func issueToken(completion: @escaping (Result<BearerToken>) -> Void) { completion(.error(CustomRefreshTokenGrantStrategy.Error.didExecute)) } func issueToken() throws -> BearerToken { return BearerToken(accessToken: "", expiration: Date()) } } struct CustomRefreshTokenGrantStrategyFactory: OAuth2RefreshStrategyFactory { func make(refreshToken: String, clientConfiguration: OAuth2ClientConfiguration) -> OAuth2TokenGrantStrategy { return CustomRefreshTokenGrantStrategy() } } // swiftlint:disable type_body_length class OAuth2RequestPipelineMiddlewareTests: XCTestCase { let validClientID = "test_client" let validClientSecret = "test_secret" let guestUsername = "test_user" let guestPassword = "hunter2" let randomTokenAccessToken = "abc123!!" private func makeMockClientConfiguration() throws -> OAuth2ClientConfiguration { let mockServerEnvironment = OAuth2ServerEnvironment(scope: "urn:everything", tokenGrantURL: try URL(absoluteString: "https://httpbin.org/get")) let mockClientConfiguration = OAuth2ClientConfiguration(clientIdentifier: "herp", clientSecret: "derp", environment: mockServerEnvironment, guestUsername: "clientuser", guestPassword: "abc123") return mockClientConfiguration } private func makeValidClientConfiguration() throws -> OAuth2ClientConfiguration { let validServerEnvironment = OAuth2ServerEnvironment(scope: "all the things", tokenGrantURL: try URL(absoluteString: "http://localhost:5000/oauth2/issue/token")) let validClientConfiguration = OAuth2ClientConfiguration(clientIdentifier: validClientID, clientSecret: validClientSecret, environment: validServerEnvironment) return validClientConfiguration } private func makeDummyRequest() throws -> URLRequest { let requestBuilder = HTTPRequestBuilder(url: try URL(absoluteString: "https://httpbin.org/post")) requestBuilder.bodyParameters = ["key": "value"] requestBuilder.method = .POST requestBuilder.serializer = JSONRequestSerializer() return try requestBuilder.build() } func testAppliesBearerHeaderIfValidTokenExists() throws { let randomToken = BearerToken(accessToken: randomTokenAccessToken, refreshToken: "notused", expiration: Date().addingTimeInterval(1_000_000)) let authorization = OAuth2Authorization(type: .bearer, level: .user) let validClientConfiguration = try makeValidClientConfiguration() let tokenStorage = OAuth2TokenMemoryStore() tokenStorage.store(token: randomToken, for: validClientConfiguration, with: authorization) let request = try makeDummyRequest() let sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: tokenStorage) let decorateRequestExpectation = expectation(description: "request immediately decorated") sut.prepareForTransport(request: request) { result in guard case .value(let request) = result else { XCTFail("No value") return } XCTAssert(request.allHTTPHeaderFields?["Authorization"] == randomToken.authorizationHeaderValue) decorateRequestExpectation.fulfill() } waitForExpectations(timeout: 0.1) } func DISABLED_testRefreshesBearerTokenIfExpired() throws { let authorization = OAuth2Authorization(type: .bearer, level: .user) let validClientConfiguration = try makeValidClientConfiguration() let request = try makeDummyRequest() let tokenStorage = OAuth2TokenMemoryStore() let sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: tokenStorage) let refreshTokenExpectation = expectation(description: "token refreshed") let clientCredentialsStrategy = OAuth2ClientCredentialsTokenGrantStrategy(clientConfiguration: validClientConfiguration) clientCredentialsStrategy.issueToken { result in guard let token = result.value else { XCTFail("No token") return } let expiredToken = BearerToken(accessToken: token.accessToken, refreshToken: token.refreshToken, expiration: Date()) tokenStorage.store(token: expiredToken, for: validClientConfiguration, with: authorization) sut.prepareForTransport(request: request) { result in guard let request = result.value else { XCTFail("No value") return } let authorizationHeader = request.allHTTPHeaderFields?["Authorization"] XCTAssertTrue(authorizationHeader?.contains("Bearer") == true) XCTAssert(authorizationHeader?.contains(expiredToken.accessToken) == false) refreshTokenExpectation.fulfill() } } waitForExpectations(timeout: 2) } func DISABLED_testAllowsCustomTokenRefreshGrants() throws { let authorization = OAuth2Authorization(type: .bearer, level: .user) let validClientConfiguration = try makeValidClientConfiguration() let request = try makeDummyRequest() let tokenStorage = OAuth2TokenMemoryStore() var sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: tokenStorage) sut.refreshStrategyFactory = CustomRefreshTokenGrantStrategyFactory() let refreshTokenExpectation = expectation(description: "token refreshed") let clientCredentialsStrategy = OAuth2ClientCredentialsTokenGrantStrategy(clientConfiguration: validClientConfiguration) clientCredentialsStrategy.issueToken { result in guard let token = result.value else { XCTFail("No token") return } let expiredToken = BearerToken(accessToken: token.accessToken, refreshToken: token.refreshToken, expiration: Date()) tokenStorage.store(token: expiredToken, for: validClientConfiguration, with: authorization) sut.prepareForTransport(request: request) { result in guard result.error is CustomRefreshTokenGrantStrategy.Error else { XCTFail("Custom strategy ignored") return } refreshTokenExpectation.fulfill() } } waitForExpectations(timeout: 2) } func DISABLED_testEmptyTokenRefreshStrategyPreventsRefreshes() throws { let authorization = OAuth2Authorization(type: .bearer, level: .user) let validClientConfiguration = try makeValidClientConfiguration() let request = try makeDummyRequest() let tokenStorage = OAuth2TokenMemoryStore() var sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: tokenStorage) sut.refreshStrategyFactory = nil let tokenInvalidatedExpectation = expectation(description: "token refresh ignored & token invalidated") let clientCredentialsStrategy = OAuth2ClientCredentialsTokenGrantStrategy(clientConfiguration: validClientConfiguration) clientCredentialsStrategy.issueToken { result in guard let token = result.value else { XCTFail("No token") return } let expiredToken = BearerToken(accessToken: token.accessToken, refreshToken: token.refreshToken, expiration: Date()) tokenStorage.store(token: expiredToken, for: validClientConfiguration, with: authorization) sut.prepareForTransport(request: request) { result in guard let error = result.error, case OAuth2Error.clientFailure(_, _) = error else { XCTFail("Custom strategy ignored") return } tokenInvalidatedExpectation.fulfill() } } waitForExpectations(timeout: 2) } func DISABLED_testAttemptsPasswordGrantWithGuestCredentialsIfTheyExist() throws { let authorization = OAuth2Authorization(type: .bearer, level: .client) var validClientConfiguration = try makeValidClientConfiguration() let request = try makeDummyRequest() validClientConfiguration.guestUsername = "test_user" validClientConfiguration.guestPassword = "hunter2" var sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: OAuth2TokenMemoryStore()) let tokenFetchedExpectation = expectation(description: "token fetched") sut.prepareForTransport(request: request) { result in guard case .value(let request) = result else { XCTFail("No value") return } XCTAssert(request.allHTTPHeaderFields?["Authorization"]?.contains("Bearer") == true) tokenFetchedExpectation.fulfill() } /// Update guest user creds to prove code flow validClientConfiguration.guestUsername = "invalid_user" validClientConfiguration.guestPassword = "invalid_pass" sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: OAuth2TokenMemoryStore()) let tokenFetchAttemptedExpectation = expectation(description: "token fetch failed") sut.prepareForTransport(request: request) { result in XCTAssertNotNil(result.error) tokenFetchAttemptedExpectation.fulfill() } waitForExpectations(timeout: 2) } func DISABLED_testAttemptsClientCredentialsGrantIfGuestCredentialsDontExist() throws { let authorization = OAuth2Authorization(type: .bearer, level: .client) var validClientConfiguration = try makeValidClientConfiguration() let request = try makeDummyRequest() var sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: OAuth2TokenMemoryStore()) let tokenFetchedExpectation = expectation(description: "token fetched") sut.prepareForTransport(request: request) { result in guard case .value(let request) = result else { XCTFail("No value") return } XCTAssert(request.allHTTPHeaderFields?["Authorization"]?.contains("Bearer") == true) tokenFetchedExpectation.fulfill() } /// Update client creds to prove code flow validClientConfiguration.clientIdentifier = "invalid_client" validClientConfiguration.clientSecret = "invalid_secret" sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: OAuth2TokenMemoryStore()) let tokenFetchAttemptedExpectation = expectation(description: "token fetch failed") sut.prepareForTransport(request: request) { result in XCTAssertNotNil(result.error) tokenFetchAttemptedExpectation.fulfill() } waitForExpectations(timeout: 2) } func testFailsForBearerUserAuthIfNoTokenExists() throws { let authorization = OAuth2Authorization(type: .bearer, level: .user) let validClientConfiguration = try makeValidClientConfiguration() let request = try makeDummyRequest() let sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: OAuth2TokenMemoryStore()) let decorationFailedExpectation = expectation(description: "decoration failed") sut.prepareForTransport(request: request) { result in XCTAssertNotNil(result.error) decorationFailedExpectation.fulfill() } waitForExpectations(timeout: 0.1) } func testNotifiesMigratorPreAndPostFetchTokenHooksForRefreshes() throws { let randomToken = BearerToken(accessToken: randomTokenAccessToken, refreshToken: "notused", expiration: Date()) let authorization = OAuth2Authorization(type: .bearer, level: .user) let mockClientConfiguration = try makeMockClientConfiguration() let tokenStorage = OAuth2TokenMemoryStore() tokenStorage.store(token: randomToken, for: mockClientConfiguration, with: authorization) let request = try makeDummyRequest() let sut = OAuth2RequestPipelineMiddleware(clientConfiguration: mockClientConfiguration, authorization: authorization, tokenStorage: tokenStorage) let calledPreFetchHookExpectation = expectation(description: "called pre-fetch hook") let calledPostFetchHookExpectation = expectation(description: "called pre-fetch hook") calledPreFetchHookExpectation.assertForOverFulfill = false calledPostFetchHookExpectation.assertForOverFulfill = false Auth.Migrator.registerPreFetchHook { _, _, _ in calledPreFetchHookExpectation.fulfill() } Auth.Migrator.registerPostFetchHook { _, _, _ in calledPostFetchHookExpectation.fulfill() } sut.prepareForTransport(request: request) { _ in // Pass } waitForExpectations(timeout: 1) } func DISABLED_testCoordinatesRefreshesBetweenMultipleSessions() throws { /// Simulates multiple sessions (different processes) triggering token refreshes at once let authorization = OAuth2Authorization(type: .bearer, level: .user) let validClientConfiguration = try makeValidClientConfiguration() let request = try makeDummyRequest() let tokenStorage = OAuth2TokenMemoryStore() let sut = OAuth2RequestPipelineMiddleware(clientConfiguration: validClientConfiguration, authorization: authorization, tokenStorage: tokenStorage) let refreshTokenExpectation = expectation(description: "token refreshed") let numSessions = 15 refreshTokenExpectation.expectedFulfillmentCount = numSessions var authorizationHeaders: [String] = [] let arrayQueue = DispatchQueue(label: #function) let clientCredentialsStrategy = OAuth2ClientCredentialsTokenGrantStrategy(clientConfiguration: validClientConfiguration) let issuedToken = try clientCredentialsStrategy.issueToken() let expiredToken = BearerToken(accessToken: issuedToken.accessToken, refreshToken: issuedToken.refreshToken, expiration: Date()) tokenStorage.store(token: expiredToken, for: validClientConfiguration, with: authorization) for _ in 0..<numSessions { sut.prepareForTransport(request: request) { result in guard let request = result.value, let authorizationHeader = request.allHTTPHeaderFields?["Authorization"] else { XCTFail("No value") return } arrayQueue.sync { authorizationHeaders.append(authorizationHeader) refreshTokenExpectation.fulfill() } } } waitForExpectations(timeout: 5) let firstHeader = authorizationHeaders[0] XCTAssertFalse(firstHeader.contains(expiredToken.accessToken)) for header in authorizationHeaders { XCTAssertEqual(firstHeader, header) } } } // swiftlint:enable type_body_length
apache-2.0
cd0a9861b7cd51ec7c6acce9883f5ed7
45.008403
154
0.683957
6.271478
false
true
false
false
samodom/TestableUIKit
TestableUIKit/UIResponder/UIView/UITableView/UITableViewEndUpdatesSpy.swift
1
1695
// // UITableViewEndUpdatesSpy.swift // TestableUIKit // // Created by Sam Odom on 2/22/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import FoundationSwagger import TestSwagger public extension UITableView { private static let endUpdatesCalledString = UUIDKeyString() private static let endUpdatesCalledKey = ObjectAssociationKey(endUpdatesCalledString) private static let endUpdatesCalledReference = SpyEvidenceReference(key: endUpdatesCalledKey) /// Spy controller for ensuring a table view has had `endUpdates` called on it. public enum EndUpdatesSpyController: SpyController { public static let rootSpyableClass: AnyClass = UITableView.self public static let vector = SpyVector.direct public static let coselectors = [ SpyCoselectors( methodType: .instance, original: #selector(UITableView.endUpdates), spy: #selector(UITableView.spy_endUpdates) ) ] as Set public static let evidence = [endUpdatesCalledReference] as Set public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of `endUpdates` public func spy_endUpdates() { endUpdatesCalled = true spy_endUpdates() } /// Indicates whether the `endUpdates` method has been called on this object. public final var endUpdatesCalled: Bool { get { return loadEvidence(with: UITableView.endUpdatesCalledReference) as? Bool ?? false } set { saveEvidence(true, with: UITableView.endUpdatesCalledReference) } } }
mit
63ea76bcaab8e3f71f7aa7205b8518b0
29.8
94
0.672963
5.482201
false
false
false
false
Longhanks/qlift
Sources/Qlift/Qt.swift
1
5525
public struct Qt { public struct Alignment: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public static let AlignLeft = Alignment(rawValue: 1) public static let AlignRight = Alignment(rawValue: 2) public static let AlignHCenter = Alignment(rawValue: 4) public static let AlignJustify = Alignment(rawValue: 8) public static let AlignAbsolute = Alignment(rawValue: 16) public static let AlignTop = Alignment(rawValue: 32) public static let AlignBottom = Alignment(rawValue: 64) public static let AlignVCenter = Alignment(rawValue: 128) public static let AlignBaseline = Alignment(rawValue: 256) public static let AlignCenter: Alignment = [.AlignVCenter, .AlignHCenter] public static let AlignHorizontal_Mask: Alignment = [.AlignLeft, .AlignRight, .AlignHCenter, .AlignJustify, .AlignAbsolute] public static let AlignVertical_Mask: Alignment = [.AlignTop, .AlignBottom, .AlignVCenter, .AlignBaseline] } public struct Orientation: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public static let Horizontal = Orientation(rawValue: 1) public static let Vertical = Orientation(rawValue: 2) } public struct WindowFlags: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public static let Widget: WindowFlags = [] public static let Window = WindowFlags(rawValue: 1) public static let Dialog = WindowFlags(rawValue: 3) public static let Sheet = WindowFlags(rawValue: 5) public static let Drawer = WindowFlags(rawValue: 7) public static let Popup = WindowFlags(rawValue: 9) public static let Tool = WindowFlags(rawValue: 11) public static let ToolTip = WindowFlags(rawValue: 13) public static let SplashScreen = WindowFlags(rawValue: 15) public static let Desktop = WindowFlags(rawValue: 17) public static let SubWindow = WindowFlags(rawValue: 18) public static let ForeignWindow = WindowFlags(rawValue: 33) public static let CoverWindow = WindowFlags(rawValue: 65) public static let WindowType_Mask = WindowFlags(rawValue: 255) public static let MSWindowsFixedSizeDialogHint = WindowFlags(rawValue: 256) public static let MSWindowsOwnDC = WindowFlags(rawValue: 512) public static let BypassWindowManagerHint = WindowFlags(rawValue: 1024) public static let X11BypassWindowManagerHint = WindowFlags(rawValue: 1024) public static let FramelessWindowHint = WindowFlags(rawValue: 2048) public static let WindowTitleHint = WindowFlags(rawValue: 4096) public static let WindowSystemMenuHint = WindowFlags(rawValue: 8192) public static let WindowMinimizeButtonHint = WindowFlags(rawValue: 16384) public static let WindowMaximizeButtonHint = WindowFlags(rawValue: 32768) public static let WindowMinMaxButtonsHint = WindowFlags(rawValue: 49152) public static let WindowContextHelpButtonHint = WindowFlags(rawValue: 65536) public static let WindowShadeButtonHint = WindowFlags(rawValue: 131072) public static let WindowStaysOnTopHint = WindowFlags(rawValue: 262144) public static let WindowTransparentForInput = WindowFlags(rawValue: 524288) public static let WindowOverridesSystemGestures = WindowFlags(rawValue: 1048576) public static let WindowDoesNotAcceptFocus = WindowFlags(rawValue: 2097152) public static let MaximizeUsingFullscreenGeometryHint = WindowFlags(rawValue: 4194304) public static let CustomizeWindowHint = WindowFlags(rawValue: 33554432) public static let WindowStaysOnBottomHint = WindowFlags(rawValue: 67108864) public static let WindowCloseButtonHint = WindowFlags(rawValue: 134217728) public static let MacWindowToolBarButtonHint = WindowFlags(rawValue: 268435456) public static let BypassGraphicsProxyWidget = WindowFlags(rawValue: 536870912) public static let NoDropShadowWindowHint = WindowFlags(rawValue: 1073741824) public static let WindowFullscreenButtonHint = WindowFlags(rawValue: -2147483648) } public struct TimerType: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public static let PreciseTimer: TimerType = [] public static let CoarseTimer = TimerType(rawValue: 1) public static let VeryCoarseTimer = TimerType(rawValue: 2) } public struct MouseButton: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public static let NoButton: MouseButton = [] public static let LeftButton = MouseButton(rawValue: 1) public static let RightButton = MouseButton(rawValue: 2) // Incomplete! } public struct WindowModality: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public static let NonModal: WindowModality = [] public static let WindowModal = WindowModality(rawValue: 1) public static let ApplicationModal = WindowModality(rawValue: 2) } }
mit
12282c32e8b9eeec3229983cff39d19b
45.428571
132
0.6981
4.968525
false
false
false
false
mohamede1945/quran-ios
Quran/SQLiteActiveTranslationsPersistence.swift
2
5761
// // SQLiteActiveTranslationsPersistence.swift // Quran // // Created by Ahmed El-Helw on 2/13/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import Foundation import SQLite import SQLitePersistence struct SQLiteActiveTranslationsPersistence: ActiveTranslationsPersistence, SQLitePersistence { let version: UInt = 1 var filePath: String { return Files.databasesPath.stringByAppendingPath("translations.db") } private struct Translations { static let table = Table("translations") static let id = Expression<Int>("_ID") static let name = Expression<String>("name") static let translator = Expression<String?>("translator") static let translatorForeign = Expression<String?>("translator_foreign") static let fileURL = Expression<String>("fileURL") static let fileName = Expression<String>("filename") static let languageCode = Expression<String>("languageCode") static let version = Expression<Int>("version") static let installedVersion = Expression<Int?>("installedVersion") } func onCreate(connection: Connection) throws { // translations table try connection.run(Translations.table.create(ifNotExists: true) { builder in builder.column(Translations.id, primaryKey: true) builder.column(Translations.name) builder.column(Translations.translator) builder.column(Translations.translatorForeign) builder.column(Translations.fileURL) builder.column(Translations.fileName) builder.column(Translations.languageCode) builder.column(Translations.version) builder.column(Translations.installedVersion) }) } func retrieveAll() throws -> [Translation] { return try run { connection in let query = Translations.table.order(Translations.name.asc) let rows = try connection.prepare(query) let bookmarks = convert(rowsToTranslations: rows) return bookmarks } } func insert(_ translation: Translation) throws { return try run { connection in let insert = Translations.table.insert( Translations.id <- translation.id, Translations.name <- translation.displayName, Translations.translator <- translation.translator, Translations.translatorForeign <- translation.translatorForeign, Translations.fileURL <- translation.fileURL.absoluteString, Translations.fileName <- translation.fileName, Translations.languageCode <- translation.languageCode, Translations.version <- translation.version, Translations.installedVersion <- translation.installedVersion) try connection.run(insert) } } func update(_ translation: Translation) throws { return try run { connection in let update = Translations.table .where(Translations.id == translation.id) .update( Translations.name <- translation.displayName, Translations.translator <- translation.translator, Translations.translatorForeign <- translation.translatorForeign, Translations.fileURL <- translation.fileURL.absoluteString, Translations.fileName <- translation.fileName, Translations.languageCode <- translation.languageCode, Translations.version <- translation.version, Translations.installedVersion <- translation.installedVersion) try connection.run(update) } } func remove(_ translation: Translation) throws { return try run { connection in let filter = Translations.table.filter(Translations.id == translation.id) try connection.run(filter.delete()) } } private func convert(rowsToTranslations rows: AnySequence<Row>) -> [Translation] { var translations: [Translation] = [] for row in rows { let id = row[Translations.id] let name = row[Translations.name] let translator = row[Translations.translator] let translatorForeign = row[Translations.translatorForeign] let fileURL = row[Translations.fileURL] let fileName = row[Translations.fileName] let languageCode = row[Translations.languageCode] let version = row[Translations.version] let installedVersion = row[Translations.installedVersion] let translation = Translation(id: id, displayName: name, translator: translator, translatorForeign: translatorForeign, fileURL: cast(URL(string: fileURL)), fileName: fileName, languageCode: languageCode, version: version, installedVersion: installedVersion) translations.append(translation) } return translations } }
gpl-3.0
98e20fcbefc14db81f40f754caa385f2
43.315385
98
0.639299
5.582364
false
false
false
false
zhiquan911/CHKLineChart
CHKLineChart/CHKLineChart/Classes/CHKLineChartStyle.swift
1
9497
// // CHKLineChartStyle.swift // CHKLineChart // // Created by 麦志泉 on 16/9/19. // Copyright © 2016年 Chance. All rights reserved. // import Foundation import UIKit /// 最大最小值显示风格 /// /// - none: 不显示 /// - arrow: 箭头风格 /// - circle: 空心圆风格 /// - tag: 标签风格 public enum CHUltimateValueStyle { case none case arrow(UIColor) case circle(UIColor, Bool) case tag(UIColor) } // MARK: - 图表样式配置类 open class CHKLineChartStyle { /// 分区样式配置 open var sections: [CHSection] = [CHSection]() /// 要处理的算法 open var algorithms: [CHChartAlgorithmProtocol] = [CHChartAlgorithmProtocol]() /// 背景颜色 open var backgroundColor: UIColor = UIColor.white /// 显示边线上左下有 open var ch_borderWidth: (top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) = (0.5, 0.5, 0.5, 0.5) /** 边距 - returns: */ open var padding: UIEdgeInsets! //字体大小 open var labelFont: UIFont! //线条颜色 open var lineColor: UIColor = UIColor.clear //文字颜色 open var textColor: UIColor = UIColor.clear //选中点的显示的框背景颜色 open var selectedBGColor: UIColor = UIColor.clear //选中点的显示的文字颜色 open var selectedTextColor: UIColor = UIColor.clear //显示y的位置,默认右边 open var showYAxisLabel = CHYAxisShowPosition.right /// 是否把y坐标内嵌到图表仲 open var isInnerYAxis: Bool = false //是否可缩放 open var enablePinch: Bool = true //是否可滑动 open var enablePan: Bool = true //是否可点选 open var enableTap: Bool = true /// 是否显示选中的内容 open var showSelection: Bool = true /// 把X坐标内容显示到哪个索引分区上,默认为-1,表示最后一个,如果用户设置溢出的数值,也以最后一个 open var showXAxisOnSection: Int = -1 /// 是否显示X轴标签 open var showXAxisLabel: Bool = true /// 是否显示所有内容 open var isShowAll: Bool = false /// 买方深度图层颜色 open var bidColor: (stroke: UIColor, fill: UIColor, lineWidth: CGFloat) = (.white, .white, 1) /// 卖方深度图层颜色 open var askColor: (stroke: UIColor, fill: UIColor, lineWidth: CGFloat) = (.white, .white, 1) /// 买单居右 open var bidChartOnDirection:CHKDepthChartOnDirection = .right public init() { } } // MARK: - 扩展样式 public extension CHKLineChartStyle { //实现一个最基本的样式,开发者可以自由扩展配置样式 public static var base: CHKLineChartStyle { let style = CHKLineChartStyle() style.labelFont = UIFont.systemFont(ofSize: 10) style.lineColor = UIColor(white: 0.2, alpha: 1) style.textColor = UIColor(white: 0.8, alpha: 1) style.selectedBGColor = UIColor(white: 0.4, alpha: 1) style.selectedTextColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) style.padding = UIEdgeInsets(top: 32, left: 8, bottom: 4, right: 0) style.backgroundColor = UIColor.ch_hex(0x1D1C1C) style.showYAxisLabel = .right //配置图表处理算法 style.algorithms = [ CHChartAlgorithm.timeline, CHChartAlgorithm.sar(4, 0.02, 0.2), //默认周期4,最小加速0.02,最大加速0.2 CHChartAlgorithm.ma(5), CHChartAlgorithm.ma(10), CHChartAlgorithm.ma(20), //计算BOLL,必须先计算到同周期的MA CHChartAlgorithm.ma(30), CHChartAlgorithm.ema(5), CHChartAlgorithm.ema(10), CHChartAlgorithm.ema(12), //计算MACD,必须先计算到同周期的EMA CHChartAlgorithm.ema(26), //计算MACD,必须先计算到同周期的EMA CHChartAlgorithm.ema(30), CHChartAlgorithm.boll(20, 2), CHChartAlgorithm.macd(12, 26, 9), CHChartAlgorithm.kdj(9, 3, 3), ] //分区点线样式 let upcolor = (UIColor.ch_hex(0xF80D1F), true) let downcolor = (UIColor.ch_hex(0x1E932B), true) let priceSection = CHSection() priceSection.backgroundColor = style.backgroundColor priceSection.titleShowOutSide = true priceSection.valueType = .master priceSection.key = "master" priceSection.hidden = false priceSection.ratios = 3 priceSection.padding = UIEdgeInsets(top: 16, left: 0, bottom: 16, right: 0) /// 时分线 let timelineSeries = CHSeries.getTimelinePrice( color: UIColor.ch_hex(0xAE475C), section: priceSection, showGuide: true, ultimateValueStyle: .circle(UIColor.ch_hex(0xAE475C), true), lineWidth: 2) timelineSeries.hidden = true /// 蜡烛线 let priceSeries = CHSeries.getCandlePrice( upStyle: upcolor, downStyle: downcolor, titleColor: UIColor(white: 0.8, alpha: 1), section: priceSection, showGuide: true, ultimateValueStyle: .arrow(UIColor(white: 0.8, alpha: 1))) priceSeries.showTitle = true priceSeries.chartModels.first?.ultimateValueStyle = .arrow(UIColor(white: 0.8, alpha: 1)) let priceMASeries = CHSeries.getPriceMA( isEMA: false, num: [5,10,30], colors: [ UIColor.ch_hex(0xDDDDDD), UIColor.ch_hex(0xF9EE30), UIColor.ch_hex(0xF600FF), ], section: priceSection) priceMASeries.hidden = false let priceEMASeries = CHSeries.getPriceMA( isEMA: true, num: [5,10,30], colors: [ UIColor.ch_hex(0xDDDDDD), UIColor.ch_hex(0xF9EE30), UIColor.ch_hex(0xF600FF), ], section: priceSection) priceEMASeries.hidden = true let priceBOLLSeries = CHSeries.getBOLL( UIColor.ch_hex(0xDDDDDD), ubc: UIColor.ch_hex(0xF9EE30), lbc: UIColor.ch_hex(0xF600FF), section: priceSection) priceBOLLSeries.hidden = true let priceSARSeries = CHSeries.getSAR( upStyle: upcolor, downStyle: downcolor, titleColor: UIColor.ch_hex(0xDDDDDD), section: priceSection) priceSARSeries.hidden = true priceSection.series = [ timelineSeries, priceSeries, priceMASeries, priceEMASeries, priceBOLLSeries, priceSARSeries ] let volumeSection = CHSection() volumeSection.backgroundColor = style.backgroundColor volumeSection.valueType = .assistant volumeSection.key = "volume" volumeSection.hidden = false volumeSection.ratios = 1 volumeSection.yAxis.tickInterval = 4 volumeSection.padding = UIEdgeInsets(top: 16, left: 0, bottom: 8, right: 0) let volumeSeries = CHSeries.getDefaultVolume(upStyle: upcolor, downStyle: downcolor, section: volumeSection) let volumeMASeries = CHSeries.getVolumeMA( isEMA: false, num: [5,10,30], colors: [ UIColor.ch_hex(0xDDDDDD), UIColor.ch_hex(0xF9EE30), UIColor.ch_hex(0xF600FF), ], section: volumeSection) let volumeEMASeries = CHSeries.getVolumeMA( isEMA: true, num: [5,10,30], colors: [ UIColor.ch_hex(0xDDDDDD), UIColor.ch_hex(0xF9EE30), UIColor.ch_hex(0xF600FF), ], section: volumeSection) volumeEMASeries.hidden = true volumeSection.series = [volumeSeries, volumeMASeries, volumeEMASeries] let trendSection = CHSection() trendSection.backgroundColor = style.backgroundColor trendSection.valueType = .assistant trendSection.key = "analysis" trendSection.hidden = false trendSection.ratios = 1 trendSection.paging = true trendSection.yAxis.tickInterval = 4 trendSection.padding = UIEdgeInsets(top: 16, left: 0, bottom: 8, right: 0) let kdjSeries = CHSeries.getKDJ( UIColor.ch_hex(0xDDDDDD), dc: UIColor.ch_hex(0xF9EE30), jc: UIColor.ch_hex(0xF600FF), section: trendSection) kdjSeries.title = "KDJ(9,3,3)" let macdSeries = CHSeries.getMACD( UIColor.ch_hex(0xDDDDDD), deac: UIColor.ch_hex(0xF9EE30), barc: UIColor.ch_hex(0xF600FF), upStyle: upcolor, downStyle: downcolor, section: trendSection) macdSeries.title = "MACD(12,26,9)" macdSeries.symmetrical = true trendSection.series = [ kdjSeries, macdSeries] style.sections = [priceSection, volumeSection, trendSection] return style } }
mit
abc3b5595a50b8a03f3c04293d016d82
29.836237
116
0.572429
4.093432
false
false
false
false
alexito4/SwiftSandbox
TheStringsProblem.playground/Sources/SafeURL.swift
1
659
import Foundation public struct URLString: Language { let url: String public init(fragment: String) { url = fragment } public init(plainText: String) { url = plainText.urlEncoded } public func toString() -> String { return url } public let name = "URL" } extension String { var urlEncoded: String { return CFURLCreateStringByAddingPercentEscapes(nil, self, nil, "!*'();:@&=+$,/?%#[]\"", CFStringBuiltInEncodings.UTF8.rawValue) as String } } public typealias URL = SafeString<URLString> public func url(text: String) -> URL { return URL(fragment: text) }
mit
021a25372dd685fe6e4356171babc876
19.59375
145
0.614568
4.640845
false
false
false
false
corderoi/Microblast
Microblast/GameScene.swift
1
14251
// // GameScene.swift // Microblast // // Created by Ian Cordero on 11/12/14. // Copyright (c) 2014 Ian Cordero. All rights reserved. // import SpriteKit import Foundation class GameScene : SKScene, SKPhysicsContactDelegate { let wCellNode = SKSpriteNode(imageNamed: "wcell") var tick: (() -> ())? var frameTick: (() -> ())? var collisionHappened: (() -> ())? var startMusic: (() -> ())? var stopMusic: (() -> ())? var lastTick: NSDate? var tickLengthMillis: NSTimeInterval! var previewNode: SKSpriteNode? var pauseOverlay: SKSpriteNode! var virusNodes: [SKSpriteNode]! var antibodyNodes: [SKSpriteNode]! var antigenNodes: [SKSpriteNode]! var energyNodes: [SKSpriteNode]! var chargeNode: SKSpriteNode? var lNode: SKSpriteNode! var spacedTicksEnabled: Bool = false var virusMoveDuration: NSTimeInterval! required init(coder aDecoder: NSCoder) { fatalError("NSCoder not supported") } func playSound(sound:String) { runAction(SKAction.playSoundFileNamed(sound, waitForCompletion: false)) } override init(size: CGSize) { super.init(size: size) virusNodes = [SKSpriteNode]() antibodyNodes = [SKSpriteNode]() antigenNodes = [SKSpriteNode]() energyNodes = [SKSpriteNode]() lNode = SKSpriteNode() chargeNode = nil lastTick = nil pauseOverlay = SKSpriteNode() virusMoveDuration = SpeedConfig[0].moveDuration tickLengthMillis = SpeedConfig[0].tickLength } override func didMoveToView(view: SKView) { // Initialize field physicsWorld.gravity = CGVectorMake(0, 0) physicsWorld.contactDelegate = self } func setUpCampaign() { backgroundColor = SKColor.redColor() let bgNode = SKSpriteNode(imageNamed: "bg.jpg") bgNode.size = size bgNode.position = CGPoint(x: size.width / 2, y: size.height / 2) bgNode.zPosition = -999 addChild(bgNode) } func endCampaign() { self.removeAllChildren() } override func update(currentTime: CFTimeInterval) { if (lastTick == nil) { return } // Frame-by-frame frameTick?() if spacedTicksEnabled { var timePassed = lastTick!.timeIntervalSinceNow * -1000.0 if timePassed > tickLengthMillis { lastTick = NSDate() tick?() } } } func startTicking() { lastTick = NSDate() } func stopTicking() { lastTick = nil } func pauseScene() { pauseOverlay = SKSpriteNode(color: SKColor.blackColor(), size: size) pauseOverlay.alpha = 0.5 pauseOverlay.position = CGPoint(x: size.width / 2, y: size.height / 2) pauseOverlay.zPosition = 899 addChild(pauseOverlay) paused = true } func unpauseScene() { pauseOverlay.removeFromParent() paused = false } func startSpacedTicks() { spacedTicksEnabled = true } func stopSpacedTicks() { spacedTicksEnabled = false } func dissolvePreview(game: Game) { if let myPreviewNode = previewNode { myPreviewNode.runAction(SKAction.sequence([SKAction.fadeOutWithDuration(0.5) , SKAction.removeFromParent()])) } } func addPlayer(game: Game, player: WhiteBloodCell) { let renderCoords = renderCoordinates(player.positionX, player.positionY, deviceWidth: Int(size.width), deviceHeight: Int(size.height)) wCellNode.position = CGPoint(x: renderCoords.0, y: renderCoords.1) wCellNode.size = PlayerSize wCellNode.zRotation = 0.0 initializePhysicsProperties(wCellNode, radius: PlayerSize.width / 2, category: PhysicsCategory.WCell, contact: PhysicsCategory.Antigen | PhysicsCategory.Virus) wCellNode.zPosition = 100 addChild(wCellNode) } func redrawPlayer(game: Game, player: WhiteBloodCell) { let playerNode = wCellNode let renderCoords = renderCoordinates(player.positionX, player.positionY, deviceWidth: Int(size.width), deviceHeight: Int(size.height)) playerNode.position = CGPoint(x: renderCoords.0, y: renderCoords.1) let angle = Double(atan(player.angle.y / player.angle.x)) + M_PI_2 let correctedAngle = player.angle.x >= 0 ? angle + M_PI : angle playerNode.zRotation = CGFloat(correctedAngle) } func removePlayer(callback: (() -> ())) { let rumbleNode = SKSpriteNode(imageNamed: "rumble-1") rumbleNode.position = wCellNode.position wCellNode.removeFromParent() addChild(rumbleNode) playSound("rumble.wav") var textures = [SKTexture]() for i in 1 ... 3 { textures.append(SKTexture(imageNamed: "rumble-\(i)")) } rumbleNode.runAction(SKAction.sequence([SKAction.animateWithTextures(textures, timePerFrame: SpeedConfig[0].virusAnimationSpeed), SKAction.fadeOutWithDuration(0), SKAction.waitForDuration(LevelPauseDuration), SKAction.removeFromParent()]), callback) } func addAntibody(antibody: Antibody) { let antibodyNode = SKSpriteNode(imageNamed: "antibody") antibodyNode.position = wCellNode.position let angle = Double(atan(antibody.direction.y / antibody.direction.x)) + M_PI_2 let correctedAngle = antibody.direction.x >= 0 ? angle + M_PI : angle antibodyNode.zRotation = CGFloat(correctedAngle) initializePhysicsProperties(antibodyNode, radius: antibodyNode.size.width / 2, category: PhysicsCategory.Antibody, contact: PhysicsCategory.Virus | PhysicsCategory.Antigen | PhysicsCategory.OuterBound, precise: true) addChild(antibodyNode) antibodyNodes.append(antibodyNode) } func redrawAntibodies(game: Game) { if let player = game.field.player { for i in 0 ..< player.antibodies.count { if let antibody = game.field.player?.antibodies[i] { let gameCoords = (antibody.positionX, antibody.positionY) let renderCoords = renderCoordinates(gameCoords.0, gameCoords.1, deviceWidth: Int(size.width), deviceHeight: Int(size.height)) let destination = CGPoint(x: renderCoords.0, y: renderCoords.1) antibodyNodes[i].position = destination } } } } func removeAntibody(whichAntibody: Int) { antibodyNodes[whichAntibody].removeFromParent() antibodyNodes.removeAtIndex(whichAntibody) } func initializePhysicsProperties(body: SKSpriteNode, radius: CGFloat, category: UInt32, contact: UInt32, precise: Bool = false) { body.physicsBody = SKPhysicsBody(circleOfRadius: radius) if let myPhysicsBody = body.physicsBody { myPhysicsBody.dynamic = true myPhysicsBody.categoryBitMask = category myPhysicsBody.contactTestBitMask = contact myPhysicsBody.collisionBitMask = PhysicsCategory.None if precise { myPhysicsBody.usesPreciseCollisionDetection = true } } else { println("Error initializing physics body!") } } func addVirus(game: Game, virus: Virus, completion: (() -> ())) { let virusNode = SKSpriteNode(imageNamed: virus.name) virusNode.size = CGSize(width: 1, height: 1) let startXY = CGPoint(x: size.width / 2, y: size.height / 2) let renderCoords = renderCoordinates(virus.positionX, virus.positionY, deviceWidth: Int(size.width), deviceHeight: Int(size.height)) let renderXY = CGPoint(x: renderCoords.0, y: renderCoords.1) virusNode.position = startXY initializePhysicsProperties(virusNode, radius: VirusSize.width / 2, category: PhysicsCategory.Virus, contact: PhysicsCategory.Antibody | PhysicsCategory.WCell) if virus.animationScheme != [1] { configureAnimationLoop(virusNode, virus.animationScheme, virus.name, game.field.virusAnimationSpeed) } let zoomAction = SKAction.group([SKAction.scaleTo(VirusSize.width, duration: 0.59), SKAction.moveTo(renderXY , duration: 0.59)]) virusNode.runAction(SKAction.sequence([zoomAction, SKAction.runBlock(completion)])) addChild(virusNode) virusNodes.append(virusNode) } func redrawViruses(game: Game, descended: Bool = false) { for i in 0 ..< virusNodes.count { if let virus = game.field.viruses[i] { let gameCoords = (virus.positionX, virus.positionY) let renderCoords = renderCoordinates(gameCoords.0, gameCoords.1, deviceWidth: Int(size.width), deviceHeight: Int(size.height)) let destination = CGPoint(x: renderCoords.0, y: renderCoords.1) virusNodes[i].position = destination } } } func removeVirus(game: Game, whichVirus: Int) { let explosionNode = SKSpriteNode(imageNamed: "explosion-1") explosionNode.position = virusNodes[whichVirus].position virusNodes[whichVirus].removeFromParent() addChild(explosionNode) var textures = [SKTexture]() for i in 1 ... 3 { textures.append(SKTexture(imageNamed: "explosion-\(i)")) } explosionNode.runAction(SKAction.sequence([SKAction.animateWithTextures(textures, timePerFrame: SpeedConfig[0].virusAnimationSpeed), SKAction.removeFromParent()])) playSound("explosion.wav") virusNodes.removeAtIndex(whichVirus) } func addAntigen(virus: Virus, antigen: Antigen) { let antigenNode = SKSpriteNode(imageNamed: antigen.name) let renderPosition = renderCoordinates(virus.positionX, virus.positionY, deviceWidth: Int(size.width), deviceHeight: Int(size.height)) antigenNode.position = CGPoint(x: renderPosition.0, y: renderPosition.1) initializePhysicsProperties(antigenNode, radius: CGFloat(antigenDimensions.0 / 2), category: PhysicsCategory.Antigen, contact: PhysicsCategory.WCell & PhysicsCategory.Antibody | PhysicsCategory.Shield | PhysicsCategory.Ground | PhysicsCategory.OuterBound, precise: true) if antigen.animationSequence != [1] { configureAnimationLoop(antigenNode, antigen.animationSequence, antigen.name, 0.05) } addChild(antigenNode) antigenNodes.append(antigenNode) } func redrawAntigens(game: Game) { for i in 0 ..< game.field.antigens.count { if let antigen = game.field.antigens[i] { let gameCoords = (antigen.positionX, antigen.positionY) let renderCoords = renderCoordinates(gameCoords.0, gameCoords.1, deviceWidth: Int(size.width), deviceHeight: Int(size.height)) let destination = CGPoint(x: renderCoords.0, y: renderCoords.1) antigenNodes[i].position = destination } } } func removeAntigens(whichVirus: Int, whichAntigen: Int) { antigenNodes[whichAntigen].removeFromParent() antigenNodes.removeAtIndex(whichAntigen) } func createLevelScene() { } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { } func antibodyDidCollideWithVirus(antibody: SKSpriteNode, virus: SKSpriteNode) { } func endOfLevel(game: Game) { stopMusic?() } func levelTransition(game: Game, transition: (() -> ())) { // Wait for antigens to disappear func restart() { startMusic?() transition() } runAction(SKAction.sequence([SKAction.waitForDuration(NSTimeInterval(LevelPauseDuration))]), completion: restart) } func didBeginContact(contact: SKPhysicsContact) { } func redrawEnergy(game: Game) { var offset = 0 for i in 0 ..< energyNodes.count { energyNodes[i - offset].removeFromParent() energyNodes.removeAtIndex(i - offset) offset++ } for i in 0 ..< game.energy.count { var spriteName: String! switch game.energy[i] { case .BlueEnergy: spriteName = "blue" case .GreenEnergy: spriteName = "green" case .GoldEnergy: spriteName = "gold" default: spriteName = "red" } var newEnergyNode = SKSpriteNode(imageNamed: "power\(spriteName)") newEnergyNode.position = CGPoint(x: CGFloat(21 + 43 * i), y: size.height - 46) newEnergyNode.size = CGSize(width: 38.0, height: 12.0) newEnergyNode.runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.fadeAlphaTo(0.5, duration: 1), SKAction.fadeAlphaTo(1.0, duration: 1)]))) energyNodes.append(newEnergyNode) addChild(newEnergyNode) } if (energyNodes.count == 4) { for energyNode in energyNodes { energyNode.removeAllActions() energyNode.runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.fadeAlphaTo(0.5, duration: 0.25), SKAction.fadeAlphaTo(1.0, duration: 0.25)]))) } } } func redrawCharge(game: Game) { } }
mit
7d0d78af0424737ec3d4ea243c011814
31.244344
278
0.599186
4.907369
false
false
false
false
paynerc/video-quickstart-swift
VideoQuickStart/ViewController.swift
1
13936
// // ViewController.swift // VideoQuickStart // // Copyright © 2016-2017 Twilio, Inc. All rights reserved. // import UIKit import TwilioVideo class ViewController: UIViewController { // MARK: View Controller Members // Configure access token manually for testing, if desired! Create one manually in the console // at https://www.twilio.com/user/account/video/dev-tools/testing-tools var accessToken = "TWILIO_ACCESS_TOKEN" // Configure remote URL to fetch token from var tokenUrl = "http://localhost:8000/token.php" // Video SDK components var room: TVIRoom? var camera: TVICameraCapturer? var localVideoTrack: TVILocalVideoTrack? var localAudioTrack: TVILocalAudioTrack? var participant: TVIParticipant? var remoteView: TVIVideoView? // MARK: UI Element Outlets and handles // `TVIVideoView` created from a storyboard @IBOutlet weak var previewView: TVIVideoView! @IBOutlet weak var connectButton: UIButton! @IBOutlet weak var disconnectButton: UIButton! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var roomTextField: UITextField! @IBOutlet weak var roomLine: UIView! @IBOutlet weak var roomLabel: UILabel! @IBOutlet weak var micButton: UIButton! // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() if PlatformUtils.isSimulator { self.previewView.removeFromSuperview() } else { // Preview our local camera track in the local video preview view. self.startPreview() } // Disconnect and mic button will be displayed when the Client is connected to a Room. self.disconnectButton.isHidden = true self.micButton.isHidden = true self.roomTextField.autocapitalizationType = .none self.roomTextField.delegate = self let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) self.view.addGestureRecognizer(tap) } func setupRemoteVideoView() { // Creating `TVIVideoView` programmatically self.remoteView = TVIVideoView.init(frame: CGRect.zero, delegate:self) self.view.insertSubview(self.remoteView!, at: 0) // `TVIVideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit // scaleAspectFit is the default mode when you create `TVIVideoView` programmatically. self.remoteView!.contentMode = .scaleAspectFit; let centerX = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0); self.view.addConstraint(centerX) let centerY = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0); self.view.addConstraint(centerY) let width = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0); self.view.addConstraint(width) let height = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 0); self.view.addConstraint(height) } // MARK: IBActions @IBAction func connect(sender: AnyObject) { // Configure access token either from server or manually. // If the default wasn't changed, try fetching from server. if (accessToken == "TWILIO_ACCESS_TOKEN") { do { accessToken = try TokenUtils.fetchToken(url: tokenUrl) } catch { let message = "Failed to fetch access token" logMessage(messageText: message) return } } // Prepare local media which we will share with Room Participants. self.prepareLocalMedia() // Preparing the connect options with the access token that we fetched (or hardcoded). let connectOptions = TVIConnectOptions.init(token: accessToken) { (builder) in // Use the local media that we prepared earlier. builder.audioTracks = self.localAudioTrack != nil ? [self.localAudioTrack!] : [TVILocalAudioTrack]() builder.videoTracks = self.localVideoTrack != nil ? [self.localVideoTrack!] : [TVILocalVideoTrack]() // The name of the Room where the Client will attempt to connect to. Please note that if you pass an empty // Room `name`, the Client will create one for you. You can get the name or sid from any connected Room. builder.roomName = self.roomTextField.text } // Connect to the Room using the options we provided. room = TwilioVideo.connect(with: connectOptions, delegate: self) logMessage(messageText: "Attempting to connect to room \(String(describing: self.roomTextField.text))") self.showRoomUI(inRoom: true) self.dismissKeyboard() } @IBAction func disconnect(sender: AnyObject) { self.room!.disconnect() logMessage(messageText: "Attempting to disconnect from room \(room!.name)") } @IBAction func toggleMic(sender: AnyObject) { if (self.localAudioTrack != nil) { self.localAudioTrack?.isEnabled = !(self.localAudioTrack?.isEnabled)! // Update the button title if (self.localAudioTrack?.isEnabled == true) { self.micButton.setTitle("Mute", for: .normal) } else { self.micButton.setTitle("Unmute", for: .normal) } } } // MARK: Private func startPreview() { if PlatformUtils.isSimulator { return } // Preview our local camera track in the local video preview view. camera = TVICameraCapturer(source: .frontCamera, delegate: self) localVideoTrack = TVILocalVideoTrack.init(capturer: camera!) if (localVideoTrack == nil) { logMessage(messageText: "Failed to create video track") } else { // Add renderer to video track for local preview localVideoTrack!.addRenderer(self.previewView) logMessage(messageText: "Video track created") // We will flip camera on tap. let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.flipCamera)) self.previewView.addGestureRecognizer(tap) } } func flipCamera() { if (self.camera?.source == .frontCamera) { self.camera?.selectSource(.backCameraWide) } else { self.camera?.selectSource(.frontCamera) } } func prepareLocalMedia() { // We will share local audio and video when we connect to the Room. // Create an audio track. if (localAudioTrack == nil) { localAudioTrack = TVILocalAudioTrack.init() if (localAudioTrack == nil) { logMessage(messageText: "Failed to create audio track") } } // Create a video track which captures from the camera. if (localVideoTrack == nil) { self.startPreview() } } // Update our UI based upon if we are in a Room or not func showRoomUI(inRoom: Bool) { self.connectButton.isHidden = inRoom self.roomTextField.isHidden = inRoom self.roomLine.isHidden = inRoom self.roomLabel.isHidden = inRoom self.micButton.isHidden = !inRoom self.disconnectButton.isHidden = !inRoom UIApplication.shared.isIdleTimerDisabled = inRoom } func dismissKeyboard() { if (self.roomTextField.isFirstResponder) { self.roomTextField.resignFirstResponder() } } func cleanupRemoteParticipant() { if ((self.participant) != nil) { if ((self.participant?.videoTracks.count)! > 0) { self.participant?.videoTracks[0].removeRenderer(self.remoteView!) self.remoteView?.removeFromSuperview() self.remoteView = nil } } self.participant = nil } func logMessage(messageText: String) { messageLabel.text = messageText } } // MARK: UITextFieldDelegate extension ViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.connect(sender: textField) return true } } // MARK: TVIRoomDelegate extension ViewController : TVIRoomDelegate { func didConnect(to room: TVIRoom) { // At the moment, this example only supports rendering one Participant at a time. logMessage(messageText: "Connected to room \(room.name) as \(String(describing: room.localParticipant?.identity))") if (room.participants.count > 0) { self.participant = room.participants[0] self.participant?.delegate = self } } func room(_ room: TVIRoom, didDisconnectWithError error: Error?) { logMessage(messageText: "Disconncted from room \(room.name), error = \(String(describing: error))") self.cleanupRemoteParticipant() self.room = nil self.showRoomUI(inRoom: false) } func room(_ room: TVIRoom, didFailToConnectWithError error: Error) { logMessage(messageText: "Failed to connect to room with error") self.room = nil self.showRoomUI(inRoom: false) } func room(_ room: TVIRoom, participantDidConnect participant: TVIParticipant) { if (self.participant == nil) { self.participant = participant self.participant?.delegate = self } logMessage(messageText: "Room \(room.name), Participant \(participant.identity) connected") } func room(_ room: TVIRoom, participantDidDisconnect participant: TVIParticipant) { if (self.participant == participant) { cleanupRemoteParticipant() } logMessage(messageText: "Room \(room.name), Participant \(participant.identity) disconnected") } } // MARK: TVIParticipantDelegate extension ViewController : TVIParticipantDelegate { func participant(_ participant: TVIParticipant, addedVideoTrack videoTrack: TVIVideoTrack) { logMessage(messageText: "Participant \(participant.identity) added video track") if (self.participant == participant) { setupRemoteVideoView() videoTrack.addRenderer(self.remoteView!) } } func participant(_ participant: TVIParticipant, removedVideoTrack videoTrack: TVIVideoTrack) { logMessage(messageText: "Participant \(participant.identity) removed video track") if (self.participant == participant) { videoTrack.removeRenderer(self.remoteView!) self.remoteView?.removeFromSuperview() self.remoteView = nil } } func participant(_ participant: TVIParticipant, addedAudioTrack audioTrack: TVIAudioTrack) { logMessage(messageText: "Participant \(participant.identity) added audio track") } func participant(_ participant: TVIParticipant, removedAudioTrack audioTrack: TVIAudioTrack) { logMessage(messageText: "Participant \(participant.identity) removed audio track") } func participant(_ participant: TVIParticipant, enabledTrack track: TVITrack) { var type = "" if (track is TVIVideoTrack) { type = "video" } else { type = "audio" } logMessage(messageText: "Participant \(participant.identity) enabled \(type) track") } func participant(_ participant: TVIParticipant, disabledTrack track: TVITrack) { var type = "" if (track is TVIVideoTrack) { type = "video" } else { type = "audio" } logMessage(messageText: "Participant \(participant.identity) disabled \(type) track") } } // MARK: TVIVideoViewDelegate extension ViewController : TVIVideoViewDelegate { func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) { self.view.setNeedsLayout() } } // MARK: TVICameraCapturerDelegate extension ViewController : TVICameraCapturerDelegate { func cameraCapturer(_ capturer: TVICameraCapturer, didStartWith source: TVICameraCaptureSource) { self.previewView.shouldMirror = (source == .frontCamera) } }
mit
d9c882779f7aea2a03d8f60b2c33ace5
37.07377
123
0.602081
5.494874
false
false
false
false
jovito-royeca/Decktracker
ios/Pods/Eureka/Source/Rows/ImageRow.swift
6
7463
// // ImageRow.swift // Eureka // // Created by Martin Barreto on 2/23/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation public struct ImageRowSourceTypes : OptionSetType { public let rawValue: Int public var imagePickerControllerSourceTypeRawValue: Int { return self.rawValue >> 1 } public init(rawValue: Int) { self.rawValue = rawValue } private init(_ sourceType: UIImagePickerControllerSourceType) { self.init(rawValue: 1 << sourceType.rawValue) } public static let PhotoLibrary = ImageRowSourceTypes(.PhotoLibrary) public static let Camera = ImageRowSourceTypes(.Camera) public static let SavedPhotosAlbum = ImageRowSourceTypes(.SavedPhotosAlbum) public static let All: ImageRowSourceTypes = [Camera, PhotoLibrary, SavedPhotosAlbum] } extension ImageRowSourceTypes { // MARK: Helpers private var localizedString: String { switch self { case ImageRowSourceTypes.Camera: return "Take photo" case ImageRowSourceTypes.PhotoLibrary: return "Photo Library" case ImageRowSourceTypes.SavedPhotosAlbum: return "Saved Photos" default: return "" } } } public enum ImageClearAction { case No case Yes(style: UIAlertActionStyle) } //MARK: Row public class _ImageRow<Cell: CellType where Cell: BaseCell, Cell: TypedCellType, Cell.Value == UIImage>: SelectorRow<UIImage, Cell, ImagePickerController> { public var sourceTypes: ImageRowSourceTypes public internal(set) var imageURL: NSURL? public var clearAction = ImageClearAction.Yes(style: .Destructive) private var _sourceType: UIImagePickerControllerSourceType = .Camera public required init(tag: String?) { sourceTypes = .All super.init(tag: tag) presentationMode = .PresentModally(controllerProvider: ControllerProvider.Callback { return ImagePickerController() }, completionCallback: { [weak self] vc in self?.select() vc.dismissViewControllerAnimated(true, completion: nil) }) self.displayValueFor = nil } // copy over the existing logic from the SelectorRow private func displayImagePickerController(sourceType: UIImagePickerControllerSourceType) { if let presentationMode = presentationMode where !isDisabled { if let controller = presentationMode.createController(){ controller.row = self controller.sourceType = sourceType onPresentCallback?(cell.formViewController()!, controller) presentationMode.presentViewController(controller, row: self, presentingViewController: cell.formViewController()!) } else{ _sourceType = sourceType presentationMode.presentViewController(nil, row: self, presentingViewController: cell.formViewController()!) } } } public override func customDidSelect() { guard !isDisabled else { super.customDidSelect() return } deselect() var availableSources: ImageRowSourceTypes = [] if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) { availableSources.insert(.PhotoLibrary) } if UIImagePickerController.isSourceTypeAvailable(.Camera) { availableSources.insert(.Camera) } if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) { availableSources.insert(.SavedPhotosAlbum) } sourceTypes.intersectInPlace(availableSources) if sourceTypes.isEmpty { super.customDidSelect() return } // now that we know the number of actions aren't empty let sourceActionSheet = UIAlertController(title: nil, message: selectorTitle, preferredStyle: .ActionSheet) guard let tableView = cell.formViewController()?.tableView else { fatalError() } if let popView = sourceActionSheet.popoverPresentationController { popView.sourceView = tableView popView.sourceRect = tableView.convertRect(cell.accessoryView?.frame ?? cell.contentView.frame, fromView: cell) } createOptionsForAlertController(sourceActionSheet) if case .Yes(let style) = clearAction where value != nil { let clearPhotoOption = UIAlertAction(title: NSLocalizedString("Clear Photo", comment: ""), style: style, handler: { [weak self] _ in self?.value = nil self?.updateCell() }) sourceActionSheet.addAction(clearPhotoOption) } // check if we have only one source type given if sourceActionSheet.actions.count == 1 { if let imagePickerSourceType = UIImagePickerControllerSourceType(rawValue: sourceTypes.imagePickerControllerSourceTypeRawValue) { displayImagePickerController(imagePickerSourceType) } } else { let cancelOption = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel, handler:nil) sourceActionSheet.addAction(cancelOption) if let presentingViewController = cell.formViewController() { presentingViewController.presentViewController(sourceActionSheet, animated: true, completion:nil) } } } public override func prepareForSegue(segue: UIStoryboardSegue) { super.prepareForSegue(segue) guard let rowVC = segue.destinationViewController as? ImagePickerController else { return } rowVC.sourceType = _sourceType } public override func customUpdateCell() { super.customUpdateCell() cell.accessoryType = .None if let image = self.value { let imageView = UIImageView(frame: CGRectMake(0, 0, 44, 44)) imageView.contentMode = .ScaleAspectFill imageView.image = image imageView.clipsToBounds = true cell.accessoryView = imageView } else{ cell.accessoryView = nil } } } extension _ImageRow { //MARK: Helpers private func createOptionForAlertController(alertController: UIAlertController, sourceType: ImageRowSourceTypes) { guard let pickerSourceType = UIImagePickerControllerSourceType(rawValue: sourceType.imagePickerControllerSourceTypeRawValue) where sourceTypes.contains(sourceType) else { return } let option = UIAlertAction(title: NSLocalizedString(sourceType.localizedString, comment: ""), style: .Default, handler: { [weak self] _ in self?.displayImagePickerController(pickerSourceType) }) alertController.addAction(option) } private func createOptionsForAlertController(alertController: UIAlertController) { createOptionForAlertController(alertController, sourceType: .Camera) createOptionForAlertController(alertController, sourceType: .PhotoLibrary) createOptionForAlertController(alertController, sourceType: .SavedPhotosAlbum) } } /// A selector row where the user can pick an image public final class ImageRow : _ImageRow<PushSelectorCell<UIImage>>, RowType { public required init(tag: String?) { super.init(tag: tag) } }
apache-2.0
88907830898d53bf0b0c4bda97e5ac22
37.663212
187
0.666979
5.908155
false
false
false
false
linkedin/LayoutKit
LayoutKitSampleApp/Benchmarks/TableViewController.swift
1
3253
// Copyright 2016 LinkedIn Corp. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import UIKit /// Each view type of collection view should be a non-generic subclass from TableViewController /// If each view type uses the generic TableViewController, it will cause the crash. /// Please see `CollectionViewController.swift` for details @available(iOS 9, *) class TableViewControllerFeedItemUIStackView: TableViewController<FeedItemUIStackView> {} class TableViewControllerFeedItemAutoLayoutView: TableViewController<FeedItemAutoLayoutView> {} class TableViewControllerFeedItemLayoutKitView: TableViewController<FeedItemLayoutKitView> {} class TableViewControllerFeedItemManualView: TableViewController<FeedItemManualView> {} /// A TableViewController controller where each cell's content view is a DataBinder. class TableViewController<ContentViewType: UIView>: UITableViewController where ContentViewType: DataBinder { typealias CellType = TableCell<ContentViewType> let reuseIdentifier = "cell" let data: [CellType.DataType] init(data: [CellType.DataType]) { self.data = data super.init(style: UITableView.Style.grouped) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 100 tableView.register(CellType.self, forCellReuseIdentifier: reuseIdentifier) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: CellType = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! CellType cell.setData(data[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } /// A UITableViewCell cell that adds a DataBinder to its content view. class TableCell<ContentView: UIView>: UITableViewCell, DataBinder where ContentView: DataBinder { lazy var wrappedContentView: ContentView = { let v = ContentView() v.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(v) let views = ["v": v] self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[v]-0-|", options: [], metrics: nil, views: views)) self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[v]-0-|", options: [], metrics: nil, views: views)) return v }() func setData(_ data: ContentView.DataType) { wrappedContentView.setData(data) } }
apache-2.0
b92e337a892d6e290303b2b17a3321e0
42.373333
147
0.74024
5.11478
false
false
false
false
JerrySir/YCOA
YCOA/Main/Metting/View/MettingListTableViewCell.swift
1
1423
// // MettingListTableViewCell.swift // YCOA // // Created by Jerry on 2016/12/16. // Copyright © 2016年 com.baochunsteel. All rights reserved. // import UIKit class MettingListTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var roomLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var participantLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configure(title: String?, time: String?, room: String?, status: String?, participant: String?) { self.titleLabel.text = title self.timeLabel.text = time self.roomLabel.text = room self.participantLabel.text = participant //HTML文本 guard status != nil else {return} let attrStr = try? NSAttributedString(data: status!.data(using: String.Encoding.unicode)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) guard attrStr != nil else {return} self.statusLabel.attributedText = attrStr self.statusLabel.font = UIFont.systemFont(ofSize: 16) } }
mit
93155b4426ed28380ae27467b1291b04
31.930233
191
0.680085
4.704319
false
false
false
false
dbart01/Spyder
Spyder/JWT.Token.swift
1
3827
// // JWT.Token.swift // Spyder // // Copyright (c) 2016 Dima Bart // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // import Foundation extension JWT { struct Token { var header: Header var payload: Payload // ---------------------------------- // MARK: - Init - // init(header: Header = .init(), payload: Payload = .init()) { self.header = header self.payload = payload } // ---------------------------------- // MARK: - Base64 - // private func headerBase64() throws -> String { return try JSONSerialization.data(withJSONObject: self.header.values, options: []).base64URL } private func payloadBase64() throws -> String { return try JSONSerialization.data(withJSONObject: self.payload.values, options: []).base64URL } private func contents() throws -> String { let header = try self.headerBase64() let payload = try self.payloadBase64() return "\(header).\(payload)" } // ---------------------------------- // MARK: - Signature - // func sign(using cryptor: CryptorType) throws -> String { let contents = try self.contents() let signature = cryptor.sign(message: contents) guard let encodedSignature = signature?.base64URL else { throw Error.signingFailed } return "\(contents).\(encodedSignature)" } // func sign(using key: PrivateKey) throws -> String { // let header = try self.headerBase64() // let payload = try self.payloadBase64() // // let message = "\(header).\(payload)" //// let digest = SHA256.hash(message) // let signature = key.sign(algorithm: .ecdsaSignatureMessageX962SHA256, message: message)?.base64URL // // guard let encodedSignature = signature else { // throw Error.signingFailed // } // // return "\(message).\(encodedSignature)" // } } } extension JWT.Token { enum Error: Swift.Error { case signingFailed } }
bsd-2-clause
f2224e5a746c86a3ab3bc129f8dcd7b7
36.891089
112
0.608309
4.78375
false
false
false
false
EMart002/EMCommon
EMCommon/Classes/UILabel+EMKit.swift
1
1844
// // UILabel+EMKit.swift // common-extentions // // Created by Martin Eberl on 02.07.16. // Copyright © 2016 Martin Eberl. All rights reserved. // import UIKit public extension UILabel { public func optimizeForOneLine() { adjustSize(CGFloat.max, heightConstraint: CGFloat.max) } public func adjustHeight() { adjustHeight(self.frame.width) } public func adjustHeight(widthConstraint:CGFloat) { guard self.text != nil && self.font != nil else { self.numberOfLines = 0 self.height = 0 return } self.adjustHeight(widthConstraint, heightConstraint: CGFloat.max) } public func adjustHeight(widthConstraint:CGFloat, heightConstraint:CGFloat) { let constraintSize = CGSize(width: widthConstraint, height: heightConstraint) self.numberOfLines = self.text!.numberOfLines(self.font!, contraintSize: constraintSize) self.height = self.text!.size(self.font!, contraintSize: constraintSize).height } public func adjustWidth(widthConstraint:CGFloat, heightConstraint:CGFloat) { let constraintSize = CGSize(width: widthConstraint, height: heightConstraint) self.numberOfLines = self.text!.numberOfLines(self.font!, contraintSize: constraintSize) self.width = self.text!.size(self.font!, contraintSize: constraintSize).width } public func adjustSize(widthConstraint:CGFloat, heightConstraint:CGFloat) { let constraintSize = CGSize(width: widthConstraint, height: heightConstraint) self.numberOfLines = self.text!.numberOfLines(self.font!, contraintSize: constraintSize) self.size = self.text!.size(self.font!, contraintSize: constraintSize) } }
mit
79e59a048e78aad809626796457bb0b1
33.12963
96
0.659251
5.008152
false
false
false
false
yonadev/yona-app-ios
Yona/Yona/RootRequestHelper.swift
1
827
// // RootRequestHelper.swift // Yona // // Created by Angel Vasa on 14/03/17. // Copyright © 2017 Yona. All rights reserved. // import Foundation class RootRequestHelper { func handleMobileconfigRootRequest (_ request :RouteRequest, response :RouteResponse ) { let url = Bundle.main.url(forResource: "style", withExtension:"css") guard let urlValue = url else { return } var cssFile = "" do { cssFile = try String(contentsOf: urlValue) } catch let error { return // Nothing for now :) } let htmString = NSLocalizedString("yona-certificate", comment: "base64 image") let final = htmString.replacingOccurrences(of: "{cssFile}", with: cssFile) response.respond(with: final) } }
mpl-2.0
83f557ac30b99ae75434512700f6f5f5
27.482759
93
0.602906
4.37037
false
false
false
false
zaneswafford/ProjectEulerSwift
ProjectEuler/Problem4.swift
1
514
// // Problem4.swift // ProjectEuler // // Created by Zane Swafford on 6/16/15. // Copyright (c) 2015 Zane Swafford. All rights reserved. // import Foundation func problem4() -> Int { var maxProduct = 0 for var x = 999; x > 99; x-- { for var y = 999; y > 99; y-- { var product = x * y if product > maxProduct && String(product) == String(reverse(String(product))) { maxProduct = product } } } return maxProduct }
bsd-2-clause
09ed0efe1cb03fb55b25d80890653626
20.458333
93
0.529183
3.697842
false
false
false
false
cfdrake/lobsters-reader
Source/Services/Helpers/Tag+Unboxable.swift
1
664
// // Tag+Unboxable.swift // LobstersReader // // Created by Colin Drake on 6/25/17. // Copyright © 2017 Colin Drake. All rights reserved. // import Foundation import Unbox /// Adds Unboxable adherence for Tag type. extension Tag: Unboxable { init(unboxer: Unboxer) throws { id = try unboxer.unbox(key: "id") tag = try unboxer.unbox(key: "tag") description = try unboxer.unbox(key: "description") privileged = try unboxer.unbox(key: "privileged") isMedia = try unboxer.unbox(key: "is_media") inactive = try unboxer.unbox(key: "inactive") hotnessMod = try unboxer.unbox(key: "hotness_mod") } }
mit
5bf78b443c84fcc596eba7caf525b41c
27.826087
59
0.647059
3.583784
false
false
false
false
ishkawa/APIKit
Tests/APIKitTests/TestComponents/TestRequest.swift
2
1141
import Foundation import APIKit struct TestRequest: Request { var absoluteURL: URL? { let urlRequest = try? buildURLRequest() return urlRequest?.url } // MARK: Request typealias Response = Any init(baseURL: String = "https://example.com", path: String = "/", method: HTTPMethod = .get, parameters: Any? = [:], headerFields: [String: String] = [:], interceptURLRequest: @escaping (URLRequest) throws -> URLRequest = { $0 }) { self.baseURL = URL(string: baseURL)! self.path = path self.method = method self.parameters = parameters self.headerFields = headerFields self.interceptURLRequest = interceptURLRequest } let baseURL: URL let method: HTTPMethod let path: String let parameters: Any? let headerFields: [String: String] let interceptURLRequest: (URLRequest) throws -> URLRequest func intercept(urlRequest: URLRequest) throws -> URLRequest { return try interceptURLRequest(urlRequest) } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { return object } }
mit
82e61477da82c9cfd420370612e1c6b6
30.694444
235
0.658195
4.918103
false
false
false
false
Hejki/SwiftExtLib
iOSPlayground.playground/Contents.swift
1
404
//: Playground - noun: a place where people can play import UIKit import CoreGraphics var col = UIColor.white var col2 = UIColor(red: 0, green: 0, blue: 0, alpha: 1.0) let hex = 0x000000 let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green = CGFloat((hex & 0xFF00) >> 8) / 255.0 let blue = CGFloat(hex & 0xFF) / 255.0 col = UIColor(red: red, green: green, blue: blue, alpha: 1.0) col == col2
mit
196a326239dca5ca722c7398b6531639
24.25
61
0.660891
2.825175
false
false
false
false
klone1127/yuan
yuan/YPopularUserListViewController.swift
1
1868
// // YPopularUserListViewController.swift // yuan // // Created by CF on 2017/6/26. // Copyright © 2017年 klone. All rights reserved. // import UIKit let kPopularUserListID: String = "PopularUserList" class YPopularUserListViewController: YBaseViewController, FetchPopularUsers, UITableViewDelegate, UITableViewDataSource { let net = YNetWork() var popularUserTableView: UITableView! var dataSource: NSMutableArray! override func viewDidLoad() { super.viewDidLoad() self.dataSource = NSMutableArray(capacity: 0) self.loadTableView() self.fetchData() // Do any additional setup after loading the view. } fileprivate func loadTableView() { let frame = CGRect(x: 0.0, y: 0.0, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 49.0) self.popularUserTableView = UITableView(frame: frame, style: .plain) self.view.addSubview(self.popularUserTableView) self.popularUserTableView.delegate = self self.popularUserTableView.dataSource = self self.popularUserTableView.register(UITableViewCell.self, forCellReuseIdentifier: kPopularUserListID) } fileprivate func fetchData() { net.fetchPopularUsers("") net.fetchPopularUsersDelegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
bd6775438e872314ae46b22453f9285f
31.155172
123
0.685791
4.745547
false
false
false
false
sfsam/Snk
Snk/SnkScoreLabel.swift
1
3218
// Created by Sanjay Madan on June 16, 2015 // Copyright (c) 2015 mowglii.com import Cocoa // SnkScoreLabel draws a score with foreground and // background colors. The background forms a border // (stroke) around the digits. See digitsfg.png and // digitsbg.png to see what the digits look like. // // Example: 21 // X: digitFg, -: digitBg, .: viewBg // // ------------. // -XXXXX--XXX-. // -----X---XX-. // -XXXXX-.-XX-. // -X-----.-XX-. // -XXXXX-.-XX-. // -------.----. // // When drawn on screen, digits are scaled up 2x. final class SnkScoreLabel: MoView { // Only draw foreground digits when false. var drawsDigitsBackground = true // Validate score, set view size, and draw it. @objc var score: Int = 0 { didSet { self.score = max(0, self.score) // enforce score >= 0 self.invalidateIntrinsicContentSize() self.needsDisplay = true } } // View size changes to fit digits in score. override var intrinsicContentSize: CGSize { let numberOfDigits = CGFloat(String(score).count) // Each digit is 12x14 points + 1 on each side for margin let width = numberOfDigits * (12 * kScale) + (2 * kScale) return CGSize(width: width, height: 14 * kScale) } let digitsFg: NSImage! let digitsBg: NSImage! // Create a score label with a digit background. init(fgColor: NSColor, bgColor: NSColor) { self.digitsFg = NSImage(named: "digitsfg")?.tint(color: fgColor) self.digitsBg = NSImage(named: "digitsbg")?.tint(color: bgColor) super.init(frame: NSZeroRect) self.drawBlock = { (context, bounds) in if self.score == 0 { return } // No anti-aliasing so pixels are sharp when scaled. context.interpolationQuality = .none // Convert the score to a string so we can enumerate its // digits. First draw the digit background and then draw // the digit foreground on top of it. let scoreString = String(self.score) for (index, digitCharacter) in scoreString.enumerated() { let digit = Int( String(digitCharacter) )! let toOffset = 12 * kScale * CGFloat(index) let toWidth = 14 * kScale let fromOffset = 7 * digit let toRect = NSRect(x: toOffset, y: 0, width: toWidth, height: toWidth) let fromRect = NSRect(x: fromOffset, y: 0, width: 7, height: 7) if self.drawsDigitsBackground { self.digitsBg.draw(in: toRect, from: fromRect, operation: .sourceOver, fraction: 1) } self.digitsFg.draw(in: toRect, from: fromRect, operation: .sourceOver, fraction: 1) } } } // Create a score label without a digit background. convenience init(fgColor: NSColor) { self.init(fgColor: fgColor, bgColor: fgColor) self.drawsDigitsBackground = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
6c68e155df6e8e24a7e16bcd294c410f
31.836735
103
0.576134
4.290667
false
false
false
false
nodekit-io/nodekit-windows
src/nodekit/NKElectro/common/NKEProtocol/NKE_ProtocolFileDecode.swift
1
4134
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation class NKE_ProtocolFileDecode: NSObject { var resourcePath: NSString? // The path to the bundle resource var urlPath: NSString // The relative path from root var fileName: NSString // The filename, with extension var fileBase: NSString // The filename, without the extension var fileExtension: NSString // The file extension var mimeType: NSString? // The mime type var textEncoding: NSString? // The text encoding init(url: NSURL) { resourcePath = nil let _mainBundle: NSBundle = NSBundle.mainBundle() let _nodeKitBundle: NSBundle = NSBundle(forClass: NKNodeKit.self) let _appPath: NSString = (_mainBundle.bundlePath as NSString).stringByDeletingLastPathComponent let _fileManager: NSFileManager = NSFileManager.defaultManager() var _fileTypes: [NSString: NSString] = ["html": "text/html" , "js" : "application/javascript" , "css": "text/css" ] urlPath = (url.path! as NSString).stringByDeletingLastPathComponent fileExtension = url.pathExtension!.lowercaseString fileName = url.lastPathComponent! if (fileExtension.length == 0) { fileBase = fileName } else { fileBase = fileName.substringToIndex(fileName.length - fileExtension.length - 1) } mimeType = nil textEncoding = nil super.init() if (fileName.length > 0) { resourcePath = _appPath.stringByAppendingPathComponent(urlPath.stringByAppendingPathComponent(fileName as String)) if (!_fileManager.fileExistsAtPath(resourcePath! as String)) { resourcePath = nil } if ((resourcePath == nil) && (fileExtension.length > 0)) { resourcePath = _mainBundle.pathForResource(fileBase as String, ofType:fileExtension as String, inDirectory: ("app" as NSString).stringByAppendingPathComponent(urlPath as String)) } if ((resourcePath == nil) && (fileExtension.length > 0)) { resourcePath = _mainBundle.pathForResource(fileBase as String, ofType:fileExtension as String, inDirectory: urlPath as String) } if ((resourcePath == nil) && (fileExtension.length == 0)) { resourcePath = _mainBundle.pathForResource(fileBase as String, ofType:"html", inDirectory: ("app" as NSString).stringByAppendingPathComponent(urlPath as String)) } if ((resourcePath == nil) && (fileExtension.length == 0)) { resourcePath = _mainBundle.pathForResource("index", ofType:"html", inDirectory: ("app" as NSString).stringByAppendingPathComponent(urlPath as String)) } if ((resourcePath == nil) && (fileExtension.length > 0)) { resourcePath = _nodeKitBundle.pathForResource(fileBase as String, ofType:fileExtension as String, inDirectory: urlPath as String) } if ((resourcePath == nil) && (fileExtension.length == 0)) { resourcePath = _nodeKitBundle.pathForResource(fileBase as String, ofType:"html", inDirectory: urlPath as String) } mimeType = _fileTypes[fileExtension] if (mimeType != nil) { if mimeType!.hasPrefix("text") { textEncoding = "utf-8" } } } } func exists() -> Bool { return (resourcePath != nil) } }
apache-2.0
f442765f8fd73456f70edf82b25fb9de
37.635514
194
0.638849
5.035323
false
false
false
false
B-Lach/BLShareController
Example/BLShareController/ViewController.swift
1
1263
// // ViewController.swift // BLShareController // // Created by Benny Lach on 22.12.14. // Copyright (c) 2014 Benny Lach. All rights reserved. // import UIKit class ViewController: UIViewController { var shareController = BLShareController() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.customLightGray() let button = UIButton(frame: CGRectMake(0, 0, 200, 40)) button.addTarget(self, action: Selector("showShareController"), forControlEvents: UIControlEvents.TouchUpInside) button.setTitleColor(UIColor.customDarkGray(), forState: UIControlState.Normal) button.setTitle("share", forState: UIControlState.Normal) button.titleLabel?.textAlignment = NSTextAlignment.Center button.titleLabel?.textColor = UIColor.customDarkGray() button.titleLabel?.numberOfLines = 1 button.center = self.view.center self.view.addSubview(button) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showShareController() { self.view.addSubview(self.shareController.view) } }
mit
9c6809bc0f50cc3de8eb26bc7b1945bf
29.804878
120
0.680127
5.011905
false
false
false
false
danielpi/NSOutlineViewInSwift
NSOutlineViewInSwift/NSOutlineViewInSwift/FileSystemItem.swift
1
5009
// // FileSystemItem.swift // NSOutlineViewInSwift // // Created by Daniel Pink on 2/12/2014. // Copyright (c) 2014 Electronic Innovations. All rights reserved. // import Cocoa public class FileSystemItem: NSObject { var relativePath: String var parent: FileSystemItem? lazy var children: [FileSystemItem]? = { let fileManager = NSFileManager.defaultManager() let fullPath = self.fullPath() var isDir = ObjCBool(false) let valid = fileManager.fileExistsAtPath(fullPath as String, isDirectory: &isDir) var newChildren: [FileSystemItem] = [] if (valid && isDir.boolValue) { let array: [AnyObject]? do { array = try fileManager.contentsOfDirectoryAtPath(fullPath as String) } catch _ { array = nil } if let ar = array as? [String] { for contents in ar { let newChild = FileSystemItem(path: contents, parent: self) newChildren.append(newChild) } } return newChildren } else { return nil } }() public override var description: String { return "FileSystemItem:\(relativePath)" } init(path: NSString, parent: FileSystemItem?) { self.relativePath = path.lastPathComponent.copy() as! String self.parent = parent } class var rootItem: FileSystemItem { get { return FileSystemItem(path:"/", parent: nil) } } public func numberOfChildren() -> Int { guard let children = self.children else { return 0 } return children.count } public func childAtIndex(n: Int) -> FileSystemItem? { guard let children = self.children else { return nil } return children[n] } public func fullPath() -> NSString { guard let parent = self.parent else { return relativePath } return parent.fullPath().stringByAppendingPathComponent(relativePath as String) } } /* @interface FileSystemItem : NSObject { NSString *relativePath; FileSystemItem *parent; NSMutableArray *children; } + (FileSystemItem *)rootItem; - (NSInteger)numberOfChildren;// Returns -1 for leaf nodes - (FileSystemItem *)childAtIndex:(NSUInteger)n; // Invalid to call on leaf nodes - (NSString *)fullPath; - (NSString *)relativePath; @end @implementation FileSystemItem static FileSystemItem *rootItem = nil; static NSMutableArray *leafNode = nil; + (void)initialize { if (self == [FileSystemItem class]) { leafNode = [[NSMutableArray alloc] init]; } } - (id)initWithPath:(NSString *)path parent:(FileSystemItem *)parentItem { self = [super init]; if (self) { relativePath = [[path lastPathComponent] copy]; parent = parentItem; } return self; } + (FileSystemItem *)rootItem { if (rootItem == nil) { rootItem = [[FileSystemItem alloc] initWithPath:@"/" parent:nil]; } return rootItem; } // Creates, caches, and returns the array of children // Loads children incrementally - (NSArray *)children { if (children == nil) { NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *fullPath = [self fullPath]; BOOL isDir, valid; valid = [fileManager fileExistsAtPath:fullPath isDirectory:&isDir]; if (valid && isDir) { NSArray *array = [fileManager contentsOfDirectoryAtPath:fullPath error:NULL]; NSUInteger numChildren, i; numChildren = [array count]; children = [[NSMutableArray alloc] initWithCapacity:numChildren]; for (i = 0; i < numChildren; i++) { FileSystemItem *newChild = [[FileSystemItem alloc] initWithPath:[array objectAtIndex:i] parent:self]; [children addObject:newChild]; [newChild release]; } } else { children = leafNode; } } return children; } - (NSString *)relativePath { return relativePath; } - (NSString *)fullPath { // If no parent, return our own relative path if (parent == nil) { return relativePath; } // recurse up the hierarchy, prepending each parent’s path return [[parent fullPath] stringByAppendingPathComponent:relativePath]; } - (FileSystemItem *)childAtIndex:(NSUInteger)n { return [[self children] objectAtIndex:n]; } - (NSInteger)numberOfChildren { NSArray *tmp = [self children]; return (tmp == leafNode) ? (-1) : [tmp count]; } - (void)dealloc { if (children != leafNode) { [children release]; } [relativePath release]; [super dealloc]; } @end */
mit
1151d6eddfffc14c3e22b958d03bbb07
25.083333
89
0.582385
4.947628
false
false
false
false
heyjessi/SafeWays
SafeWayController/InputViewController.swift
1
4196
// // InputViewController.swift // SafeWay // // Created by Hansen Qian on 7/11/15. // Copyright (c) 2015 HQ. All rights reserved. // import AFNetworking import ReactiveCocoa import SnapKit import SwiftyJSON import UIKit class InputViewController: UIViewController { let insets = UIEdgeInsetsMake(10, 10, 10, 10) let originTextField: UITextField let destinationTextField: UITextField let submitButton: UIButton // let tableViewController: TableViewController let buttonPressedSignal: Signal<(String, String), NoError> let buttonPressedObserver: Signal<(String, String), NoError>.Observer var mvc: MapViewController? var tbc: UITabBarController? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.originTextField = UITextField() self.destinationTextField = UITextField() self.submitButton = UIButton() // self.tableViewController = TableViewController() (self.buttonPressedSignal, self.buttonPressedObserver) = Signal<(String, String), NoError>.pipe() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.originTextField.placeholder = "Enter Origin" self.originTextField.text = "116 New Montgomery St., San Francisco, CA" self.destinationTextField.text = "549 Connecticut St., San Francisco, CA" self.destinationTextField.placeholder = "Enter Destination" self.submitButton.setTitle("Search!", forState: .Normal) self.submitButton.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.3) self.submitButton.tintColor = UIColor.blueColor() self.submitButton.addTarget(self, action: NSSelectorFromString("buttonPressed"), forControlEvents: .TouchUpInside) self.view.addSubview(self.originTextField) self.view.addSubview(self.destinationTextField) self.view.addSubview(self.submitButton) // Customize tableView // self.view.addSubview(self.tableViewController) self.originTextField.snp_makeConstraints { [unowned self] make in make.top.equalTo(self.view).insets(UIEdgeInsetsMake(50, 0, 0, 0)) make.left.right.equalTo(self.view).insets(UIEdgeInsetsMake(0, 20, 0, 20)) } self.destinationTextField.snp_makeConstraints { [unowned self] make in make.left.right.equalTo(self.view).insets(UIEdgeInsetsMake(0, 20, 0, 20)) make.top.equalTo(self.originTextField).insets(UIEdgeInsetsMake(40, 0, 0, 0)) } self.submitButton.snp_makeConstraints { [unowned self] make in make.top.equalTo(self.destinationTextField).insets(UIEdgeInsetsMake(40, 0, 0, 0)) make.left.right.equalTo(self.view).insets(UIEdgeInsetsMake(0, 20, 0, 20)) } } func buttonPressed() { println("Button Pressed!") if self.originTextField.text != "" && self.destinationTextField != "" { // sendNext(self.buttonPressedObserver, (self.originTextField.text, self.destinationTextField.text)) let originText = self.originTextField.text! let destinationText = self.destinationTextField.text! let url = "http://chime.notifsta.com/directions" let parameters = [ "start_address": originText, "end_address": destinationText, ] println("Requesting from url \(url)") AFHTTPRequestOperationManager().GET(url, parameters: parameters, success: { [unowned self] (operation, responseObj) -> Void in self.mvc?.displayRoutes(JSON(responseObj)) self.tbc?.selectedIndex = 1 }, failure: { (operation, error) -> Void in println("Error: \(error)") }) } } func displayResults(responseObj: JSON) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
1d95c8f21e7d650fc2d1049bf34308bc
37.851852
138
0.666826
4.811927
false
false
false
false
Metex/swiftCommon
Classes/UIEnumPickerView.swift
1
1876
// // UIEnumPickerView.swift // EDUGrader // // Created by Elliot Grafil on 3/15/16. // Copyright © 2016 Elliot Grafil. All rights reserved. // import UIKit //https://www.raywenderlich.com/76433/how-to-make-a-custom-control-swift //https://gist.github.com/LoganWright/5785b62fd30cd6c96e45 class UIEnumPickerView< T: protocol<EnumProtocols> >: UIControl, UIPickerViewDataSource, UIPickerViewDelegate { var value: T var text: String { return value.description } let pickerView:UIPickerView = UIPickerView() // MARK: - UIPickerViewDataSource convenience init() { self.init(frame: CGRectZero) } override init(frame: CGRect) { value = T(rawValue: 0)! super.init(frame: frame) pickerView.dataSource = self pickerView.delegate = self self.addSubview(pickerView) } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return T.allValues.count } // MARK: - UIPickerViewDelegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return T(rawValue: row)!.description } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { value = T(rawValue: row)! } // several optional methods: // func pickerView(pickerView: UIPickerView!, widthForComponent component: Int) -> CGFloat // func pickerView(pickerView: UIPickerView!, rowHeightForComponent component: Int) -> CGFloat // func pickerView(pickerView: UIPickerView!, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString! // func pickerView(pickerView: UIPickerView!, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView! }
mit
dfa530de227eb647a136a0b8524e5476
28.296875
133
0.721067
4.340278
false
false
false
false
envoy/Ambassador
AmbassadorTests/JSONResponseTests.swift
1
1654
// // JSONResponseTests.swift // Ambassador // // Created by Fang-Pen Lin on 6/10/16. // Copyright © 2016 Fang-Pen Lin. All rights reserved. // import XCTest import Embassy import Ambassador class JSONResponseTests: XCTestCase { func testJSONResponse() { let dataResponse = JSONResponse() { (environ) -> Any in return ["foo", "bar"] } var receivedStatus: String? var receivedHeaders: [(String, String)]? let startResponse = { (status: String, headers: [(String, String)]) in receivedStatus = status receivedHeaders = headers } var receivedData: [Data] = [] let sendBody = { (data: Data) in receivedData.append(data) } let environ: [String: Any] = [ "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "PATH_INFO": "/", ] dataResponse.app( environ, startResponse: startResponse, sendBody: sendBody ) XCTAssertEqual(receivedStatus, "200 OK") let headersDict = MultiDictionary<String, String, LowercaseKeyTransform>( items: receivedHeaders ?? [] ) XCTAssertEqual(headersDict["Content-Type"], "application/json") XCTAssertEqual(receivedData.count, 2) XCTAssertEqual(receivedData.last?.count, 0) let bytes = receivedData.first ?? Data() let parsedJSON: [String] = try! JSONSerialization.jsonObject( with: bytes, options: .allowFragments ) as? [String] ?? [] XCTAssertEqual(parsedJSON, ["foo", "bar"]) } }
mit
545f78f58eb451cfc97d0f73ea81ff94
27.016949
81
0.571688
4.604457
false
true
false
false
wangzheng0822/algo
swift/14_sorts/CountingSort.swift
1
737
// // CountingSort.swift // algo // // Created by Wenru Dong on 2018/10/18. // Copyright © 2018年 Wenru Dong. All rights reserved. // import Foundation // 假设数组中储存的都是非负整数 public func countingSort(_ a: inout [Int]) { if a.count <= 1 { return } var counts = Array(repeating: 0, count: a.max()! + 1) for num in a { counts[num] += 1 } for i in 1..<counts.count { counts[i] = counts[i-1] + counts[i] } var aSorted = Array(repeating: 0, count: a.count) for num in a.reversed() { let index = counts[num] - 1 aSorted[index] = num counts[num] -= 1 } for (i, num) in aSorted.enumerated() { a[i] = num } }
apache-2.0
67d4adc62b090dab2b1090a16aade6eb
20.393939
57
0.545326
3.082969
false
false
false
false
kaltura/playkit-ios
Classes/PKStateMachine.swift
1
2636
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import Foundation public protocol IntRawRepresentable: RawRepresentable { var rawValue: Int { get } } public protocol StateProtocol: IntRawRepresentable, Hashable {} extension StateProtocol { var hashValue: Int { return rawValue } } public class BasicStateMachine<T: StateProtocol> { /// the current state. private var state: T /// the queue to make changes and fetches on. let dispatchQueue: DispatchQueue /// the initial state of the state machine. let initialState: T /// indicates whether it is allowed to change the state to the initial one. var allowTransitionToInitialState: Bool /// a block to perform on every state changing (performed on the main queue). var onStateChange: ((T) -> Void)? public init(initialState: T, allowTransitionToInitialState: Bool = true) { self.state = initialState self.initialState = initialState self.allowTransitionToInitialState = allowTransitionToInitialState self.dispatchQueue = DispatchQueue(label: "com.kaltura.playkit.dispatch-queue.\(String(describing: type(of: self)))") } /// gets the current state. public func getState() -> T { return self.dispatchQueue.sync { return self.state } } /// sets the state to a new value. public func set(state: T) { self.dispatchQueue.sync { if state == self.initialState && !self.allowTransitionToInitialState { PKLog.error("\(String(describing: type(of: self))) was set to initial state, this is not allowed") return } // only set state when changed if self.state != state { self.state = state DispatchQueue.main.async { self.onStateChange?(state) } } } } /// sets the state machine to the initial value. public func reset() { dispatchQueue.sync { self.state = self.initialState DispatchQueue.main.async { self.onStateChange?(self.state) } } } }
agpl-3.0
9c6bef8649a9e73a83c3bf47a9233cc2
33.233766
125
0.575493
5.118447
false
false
false
false
edx/edx-app-ios
Source/ValuePropDetailViewController.swift
1
6790
// // ValuePropDetailViewController.swift // edX // // Created by Salman on 19/11/2020. // Copyright © 2020 edX. All rights reserved. // import UIKit enum ValuePropModalType { case courseEnrollment case courseUnit } class ValuePropDetailViewController: UIViewController, InterfaceOrientationOverriding { typealias Environment = OEXAnalyticsProvider & OEXStylesProvider & ReachabilityProvider & NetworkManagerProvider & OEXConfigProvider & OEXInterfaceProvider private lazy var valuePropTableView: ValuePropMessagesView = { let tableView = ValuePropMessagesView() tableView.accessibilityIdentifier = "ValuePropDetailViewController:table-view" return tableView }() private lazy var titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.attributedText = titleStyle.attributedString(withText: Strings.ValueProp.upgrade(courseName: course.name ?? "")).setLineSpacing(4) label.accessibilityIdentifier = "ValuePropDetailViewController:title-label" return label }() private lazy var upgradeButton: CourseUpgradeButtonView = { let upgradeButton = CourseUpgradeButtonView() upgradeButton.tapAction = { [weak self] in self?.upgradeCourse() } upgradeButton.accessibilityIdentifier = "ValuePropDetailViewController:upgrade-button" return upgradeButton }() private var titleStyle: OEXMutableTextStyle = { let style = OEXMutableTextStyle(weight: .bold, size: .xxLarge, color: OEXStyles.shared().primaryDarkColor()) style.alignment = .left return style }() private let crossButtonSize: CGFloat = 20 private var type: ValuePropModalType private let course: OEXCourse private let environment: Environment init(type: ValuePropModalType, course: OEXCourse, environment: Environment) { self.type = type self.course = course self.environment = environment super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = environment.styles.neutralWhiteT() navigationController?.navigationBar.apply(barTintColor: environment.styles.neutralWhiteT(), tintColor: environment.styles.primaryBaseColor(), clearShadow: true) configureView() guard let courseSku = UpgradeSKUManager.shared.courseSku(for: course) else { return } PaymentManager.shared.productPrice(courseSku) { [weak self] price in if let price = price { self?.upgradeButton.setPrice(price) } } } private func configureView() { addSubviews() setConstraints() } private func addSubviews() { view.addSubview(titleLabel) view.addSubview(valuePropTableView) view.addSubview(upgradeButton) addCloseButton() } private func addCloseButton() { let closeButton = UIBarButtonItem(image: Icon.Close.imageWithFontSize(size: crossButtonSize), style: .plain, target: nil, action: nil) closeButton.accessibilityLabel = Strings.Accessibility.closeLabel closeButton.accessibilityHint = Strings.Accessibility.closeHint closeButton.accessibilityIdentifier = "ValuePropDetailView:close-button" navigationItem.rightBarButtonItem = closeButton closeButton.oex_setAction { [weak self] in self?.dismiss(animated: true, completion: nil) } } private func setConstraints() { titleLabel.snp.makeConstraints { make in make.leading.equalTo(view).offset(StandardHorizontalMargin) make.trailing.equalTo(view).inset(StandardHorizontalMargin) make.top.equalTo(view).offset(StandardVerticalMargin * 5) } valuePropTableView.snp.makeConstraints { make in make.leading.equalTo(titleLabel).inset(-StandardHorizontalMargin / 2) make.trailing.equalTo(titleLabel) make.top.equalTo(titleLabel.snp.bottom).offset(StandardVerticalMargin) make.bottom.equalTo(upgradeButton.snp.top).offset(-StandardVerticalMargin) } upgradeButton.snp.makeConstraints { make in make.leading.equalTo(view).offset(StandardHorizontalMargin) make.trailing.equalTo(view).inset(StandardHorizontalMargin) make.bottom.equalTo(safeBottom).inset(StandardVerticalMargin) make.height.equalTo(CourseUpgradeButtonView.height) } } private func upgradeCourse() { guard let courseSku = UpgradeSKUManager.shared.courseSku(for: course) else { return } disableAppTouchs() let pacing = course.isSelfPaced ? "self" : "instructor" environment.analytics.trackUpgradeNow(with: course.course_id ?? "", blockID: courseSku, pacing: pacing) CourseUpgradeHandler.shared.upgradeCourse(course, environment: environment) { [weak self] status in switch status { case .payment: self?.upgradeButton.stopAnimating() break case .complete: self?.enableAppTouches() self?.upgradeButton.isHidden = true self?.dismiss(animated: true) { CourseUpgradeCompletion.shared.handleCompletion(state: .success(self?.course.course_id ?? "", nil)) } break case .error: self?.enableAppTouches() self?.upgradeButton.stopAnimating() self?.dismiss(animated: true) { CourseUpgradeCompletion.shared.handleCompletion(state: .error) } break default: break } } } private func disableAppTouchs() { DispatchQueue.main.async { if !UIApplication.shared.isIgnoringInteractionEvents { UIApplication.shared.beginIgnoringInteractionEvents() } } } private func enableAppTouches() { DispatchQueue.main.async { if UIApplication.shared.isIgnoringInteractionEvents { UIApplication.shared.endIgnoringInteractionEvents() } } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .allButUpsideDown } }
apache-2.0
b3e22edf09269220d1d751619e5cb66b
35.304813
168
0.638828
5.606111
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/CHIPageControl/CHIPageControl/CHIPageControlPuya.swift
1
5422
// // CHIPageControlPuya.swift // CHIPageControl ( https://github.com/ChiliLabs/CHIPageControl ) // // Copyright (c) 2017 Chili ( http://chi.lv ) // // // 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 CHIPageControlPuya: CHIBasePageControl { fileprivate var diameter: CGFloat { return radius * 2 } fileprivate var elements = [CHILayer]() fileprivate var frames = [CGRect]() fileprivate var min: CGRect? fileprivate var max: CGRect? required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(frame: CGRect) { super.init(frame: frame) } override func updateNumberOfPages(_ count: Int) { elements.forEach { $0.removeFromSuperlayer() } elements = [CHILayer]() elements = (0..<count).map {_ in let layer = CHILayer() self.layer.addSublayer(layer) return layer } setNeedsLayout() self.invalidateIntrinsicContentSize() } override open func layoutSubviews() { super.layoutSubviews() let floatCount = CGFloat(elements.count) let x = (self.bounds.size.width - self.diameter*floatCount - self.padding*(floatCount-1))*0.5 let y = (self.bounds.size.height - self.diameter)*0.5 var frame = CGRect(x: x, y: y, width: self.diameter, height: self.diameter) elements.enumerated().forEach() { index, layer in layer.backgroundColor = self.tintColor(position: index).withAlphaComponent(self.inactiveTransparency).cgColor if self.borderWidth > 0 { layer.borderWidth = self.borderWidth layer.borderColor = self.tintColor(position: index).cgColor } layer.cornerRadius = self.radius layer.frame = frame frame.origin.x += self.diameter + self.padding } if let active = elements.first { active.backgroundColor = (self.currentPageTintColor ?? self.tintColor)?.cgColor active.borderWidth = 0 } min = elements.first?.frame max = elements.last?.frame self.frames = elements.map { $0.frame } update(for: progress) } override func update(for progress: Double) { guard let min = self.min, let max = self.max, progress >= 0 && progress <= Double(numberOfPages - 1), numberOfPages > 1 else { return } let total = Double(numberOfPages - 1) let dist = max.origin.x - min.origin.x let percent = CGFloat(progress / total) let page = Int(progress) for (index, _) in self.frames.enumerated() { if page > index { self.elements[index+1].frame = self.frames[index] } else if page < index { self.elements[index].frame = self.frames[index] } } let offset = dist * percent guard let active = elements.first else { return } active.frame.origin.x = min.origin.x + offset active.borderWidth = 0 let index = page + 1 guard elements.indices.contains(index) else { return } let element = elements[index] guard frames.indices.contains(page), frames.indices.contains(page + 1) else { return } let prev = frames[page] let prevColor = tintColor(position: page) let current = frames[page + 1] let currentColor = tintColor(position: page + 1) let elementTotal: CGFloat = current.origin.x - prev.origin.x let elementProgress: CGFloat = current.origin.x - active.frame.origin.x let elementPercent = (elementTotal - elementProgress) / elementTotal element.backgroundColor = blend(color1: currentColor, color2: prevColor, progress: elementPercent).withAlphaComponent(self.inactiveTransparency).cgColor element.frame = prev element.frame.origin.x += elementProgress } override open var intrinsicContentSize: CGSize { return sizeThatFits(CGSize.zero) } override open func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize(width: CGFloat(elements.count) * self.diameter + CGFloat(elements.count - 1) * self.padding, height: self.diameter) } }
mit
98677ed41e6b7735311d4e187ec5554f
36.393103
160
0.638694
4.567818
false
false
false
false
edx/edx-app-ios
Test/MicrosoftConfigTests.swift
1
1142
// // MicrosoftConfigTests.swift // edXTests // // Created by Salman on 30/10/2019. // Copyright © 2019 edX. All rights reserved. // import XCTest @testable import edX let microsoftAppID = "3000c01b-0c11-0111-1111-e0ae10101de0" class MicrosoftConfigTests: XCTestCase { func testNoMicrosoftConfig() { let config = OEXConfig(dictionary:[:]) XCTAssertFalse(config.microsoftConfig.enabled) XCTAssertNil(config.microsoftConfig.appID) } func testEmptyMicrosoftConfig() { let config = OEXConfig(dictionary:["MICROSOFT":[:]]) XCTAssertFalse(config.microsoftConfig.enabled) XCTAssertNil(config.microsoftConfig.appID) } func testMicrosoftConfig() { let configDictionary = [ "MICROSOFT" : [ "ENABLED": true, "APP_ID" : microsoftAppID ] ] let config = OEXConfig(dictionary: configDictionary) XCTAssertTrue(config.microsoftConfig.enabled) XCTAssertEqual(config.microsoftConfig.appID, microsoftAppID) XCTAssertNotNil(config.microsoftConfig.appID) } }
apache-2.0
39505cf94cf6edd46f7afdfba6d3b784
26.166667
68
0.651183
4.638211
false
true
false
false
lorentey/swift
test/IRGen/closure.swift
10
4544
// RUN: %target-swift-frontend -primary-file %s -emit-ir | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -emit-ir | %FileCheck %s --check-prefix=CAPTURE // RUN: %target-swift-frontend -primary-file %s -O -emit-ir | %FileCheck %s --check-prefix=OPT // REQUIRES: CPU=x86_64 // CHECK-DAG: [[FILENAME:@[0-9]+]] = {{.*}} c"{{.*}}closure.swift\00" // OPT: [[FILENAME:@[0-9]+]] = {{.*}} [1 x i8] zeroinitializer // -- partial_apply context metadata // CHECK-DAG: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* @objectdestroy, i8** null, %swift.type { i64 1024 }, i32 16, i8* bitcast ({ i32, i32, i32, i32 }* @"\01l__swift5_reflection_descriptor" to i8*) } func a(i i: Int) -> (Int) -> Int { return { x in i } } // -- Closure entry point // CHECK: define internal swiftcc i64 @"$s7closure1a1iS2icSi_tFS2icfU_"(i64, i64) protocol Ordinable { func ord() -> Int } func b<T : Ordinable>(seq seq: T) -> (Int) -> Int { return { i in i + seq.ord() } } // -- partial_apply stub // CHECK: define internal swiftcc i64 @"$s7closure1a1iS2icSi_tFS2icfU_TA"(i64, %swift.refcounted* swiftself) // CHECK: } // -- Closure entry point // CHECK: define internal swiftcc i64 @"$s7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_"(i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} { // -- partial_apply stub // CHECK: define internal swiftcc i64 @"$s7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_TA"(i64, %swift.refcounted* swiftself) {{.*}} { // CHECK: entry: // CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* // CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1 // CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]] // CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8 // CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1 // CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]] // CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8 // CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2 // CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8 // CHECK: [[RES:%.*]] = tail call swiftcc i64 @"$s7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_"(i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]]) // CHECK: ret i64 [[RES]] // CHECK: } // -- <rdar://problem/14443343> Boxing of tuples with generic elements // CHECK: define hidden swiftcc { i8*, %swift.refcounted* } @"$s7closure14captures_tuple1xx_q_tycx_q_t_tr0_lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U) func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) { // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_getTupleTypeMetadata2(i64 0, %swift.type* %T, %swift.type* %U, i8* null, i8** null) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NOT: @swift_getTupleTypeMetadata2 // CHECK: [[BOX:%.*]] = call swiftcc { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]]) // CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1 // CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>* return {x} } class C {} func useClosure(_ cl : () -> ()) {} // CAPTURE-NOT: reflection_descriptor{{.*}} = private constant { i32, i32, i32, i32, i32, i32, i32, i32 } { i32 5, i32 0, i32 0 func no_capture_descriptor(_ c: C, _ d: C, _ e: C, _ f: C, _ g: C) { useClosure( { _ = c ; _ = d ; _ = e ; _ = f ; _ = g }) } // CHECK-LABEL: define hidden swiftcc { i8*, %swift.refcounted* } @"$s7closure9letEscape1fyycyyXE_tF"(i8*, %swift.opaque*) // CHECK: call i1 @swift_isEscapingClosureAtFileLocation(%swift.refcounted* {{.*}}, i8* getelementptr inbounds ({{.*}} [[FILENAME]] // OPT-LABEL: define hidden swiftcc { i8*, %swift.refcounted* } @"$s7closure9letEscape1fyycyyXE_tF"(i8*, %swift.opaque*) // OPT: call i1 @swift_isEscapingClosureAtFileLocation(%swift.refcounted* {{.*}}, i8* getelementptr inbounds ({{.*}} [[FILENAME]] func letEscape(f: () -> ()) -> () -> () { return withoutActuallyEscaping(f) { return $0 } }
apache-2.0
ea9aa54887389cf48f264389cdb8a0e8
56.518987
248
0.630942
3.112329
false
false
false
false
skutnii/4swivl
TestApp/TestApp/Observable.swift
1
1738
// // Observable.swift // TestApp // // Created by Serge Kutny on 9/17/15. // Copyright © 2015 skutnii. All rights reserved. // import Foundation class Callback<T, O : AnyObject> { typealias Call = (T?, T?, AnyObject) -> () typealias Owner = Observable<T, O> private let _call : Call private let _observable : Owner private init(call: Call, owner: Owner) { _call = call _observable = owner } func unlink() { let index = _observable._callbacks.indexOf({ (value) in value === self}) if nil != index { _observable._callbacks.removeAtIndex(index!) } } } class Observable<T, O : AnyObject> : GenericWrapper<T> { private unowned let _owner : O private var _callbacks = [Callback<T, O>]() private func _didChange(from oldValue: T?, to newValue:T?) { for callback in _callbacks { callback._call(oldValue, newValue, _owner) } } override subscript () -> T? { get { return super[] } set (value) { let oldValue = super[] super[] = value _didChange(from: oldValue, to: value) } } func addObserver(call: Callback<T, O>.Call) -> Callback<T, O> { let callback = Callback<T, O>(call: call, owner: self) _callbacks.append(callback) return callback } func removeObserver(observer: Callback<T, O>?) { guard let index = _callbacks.indexOf({ (value) in value === observer}) else { return } _callbacks.removeAtIndex(index) } init(owner: O, value: T?) { _owner = owner super.init(value: value) } }
mit
e8385514e130cc0d209a2b2037d597e2
24.173913
86
0.545769
4.030162
false
false
false
false
inderdhir/DatWeatherDoe
DatWeatherDoe/UI/Decorator/Text/Humidity/HumidityTextBuilder.swift
1
1383
// // HumidityTextBuilder.swift // DatWeatherDoe // // Created by Inder Dhir on 1/15/22. // Copyright © 2022 Inder Dhir. All rights reserved. // import Foundation final class HumidityTextBuilder { private let initial: String private let humidity: Int private let logger: DatWeatherDoeLoggerType private let percentString = "\u{0025}" private let humidityFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .none formatter.maximumFractionDigits = 0 return formatter }() init( initial: String, humidity: Int, logger: DatWeatherDoeLoggerType ) { self.initial = initial self.humidity = humidity self.logger = logger } func build() -> String { guard let humidityString = buildHumidity() else { logger.error("Unable to construct humidity string") return initial } return "\(initial) | \(humidityString)" } private func buildHumidity() -> String? { guard let formattedString = buildFormattedString() else { return nil } return "\(formattedString)\(percentString)" } private func buildFormattedString() -> String? { humidityFormatter.string(from: NSNumber(value: humidity)) } }
apache-2.0
a65cf65cb2f0c923450a95fd0480ec1f
24.592593
78
0.613603
5.062271
false
false
false
false
codeslubber/onboarding
onboarding/RootViewController.swift
1
4882
// // RootViewController.swift // onboarding // // Created by Rob Williams on 12/9/15. // Copyright © 2015 ontometrics. All rights reserved. // import UIKit class RootViewController: UIViewController, UIPageViewControllerDelegate { var pageViewController: UIPageViewController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Configure the page view controller and add it as a child view controller. self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil) self.pageViewController!.delegate = self let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)! let viewControllers = [startingViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in }) self.pageViewController!.dataSource = self.modelController self.addChildViewController(self.pageViewController!) self.view.addSubview(self.pageViewController!.view) // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. var pageViewRect = self.view.bounds if UIDevice.currentDevice().userInterfaceIdiom == .Pad { pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0) } self.pageViewController!.view.frame = pageViewRect self.pageViewController!.didMoveToParentViewController(self) // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var modelController: ModelController { // Return the model controller object, creating it if necessary. // In more complex implementations, the model controller may be passed to the view controller. if _modelController == nil { _modelController = ModelController() } return _modelController! } var _modelController: ModelController? = nil // MARK: - UIPageViewController delegate methods func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation { if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) { // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here. let currentViewController = self.pageViewController!.viewControllers![0] let viewControllers = [currentViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) self.pageViewController!.doubleSided = false return .Min } // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers. let currentViewController = self.pageViewController!.viewControllers![0] as! DataViewController var viewControllers: [UIViewController] let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController) if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) { let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfterViewController: currentViewController) viewControllers = [currentViewController, nextViewController!] } else { let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBeforeViewController: currentViewController) viewControllers = [previousViewController!, currentViewController] } self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) return .Mid } }
mit
94c34135b3dc27241fab152777a8c763
51.483871
333
0.733661
5.916364
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/Create/Cells/ConversationCreateErrorCell.swift
1
1822
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireCommonComponents class ConversationCreateErrorCell: UICollectionViewCell { let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init?(coder aDecoder: NSCoder) is not implemented") } fileprivate func setup() { label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.font = FontSpec(.small, .semibold).font! label.textColor = UIColor.from(scheme: .errorIndicator, variant: .light) contentView.addSubview(label) NSLayoutConstraint.activate([ label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0), label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0) ]) } }
gpl-3.0
c2a44e2bc48b5f87bc150dc1c51b9e81
34.72549
96
0.708013
4.720207
false
false
false
false
seandavidmcgee/HumanKontactBeta
src/keyboardTest/MMPlayStandPageViewController.swift
1
25315
// // MMPlayStandPageViewController.swift // MMGooglePlayNewsStand // // Created by mukesh mandora on 25/08/15. // Copyright (c) 2015 madapps. All rights reserved. // import UIKit // MARK: - Protocols - /** Page Delegate: This delegate performs basic operations such as dismissing the pagecontroller or call whatever action on page change. Probably the container is presented by this delegate. **/ @objc protocol MMPlayPageControllerDelegate{ @objc optional func containerCloseButtonPressed() // If the skipRequest(sender:) action is connected to a button, this function is called when that button is pressed. @objc optional func containerNextButtonPressed() // @objc optional func containerPrevButtonPressed() // @objc optional func containerPageDidChange(pageNumber:Int) // Called when current page changes } /** Scroll Page: The page represents any page added to the container. At the moment it's only used to perform custom animations on didScroll. **/ @objc protocol MMPlayPageScroll{ // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. @objc func walkthroughDidScroll(position:CGFloat, offset:CGFloat) // Called when the main Scrollview...scrolls } @objc class MMPlayStandPageViewController: UIViewController,UIScrollViewDelegate,scrolldelegateForYAxis,UIGestureRecognizerDelegate { // MARK: - Public properties - weak var delegate:MMPlayPageControllerDelegate? var check:NSString! var menuBut:UIButton! var searchBut:UIButton! var navTitle : UILabel! var horiScroll:UIScrollView! var currentColor:UIColor! var showStatus = false as Bool //ScrollView State var lastOffset:CGFloat! var currentPage:Int{ // The index of the current page (readonly) get{ let page = Int((scrollview.contentOffset.x / view.bounds.size.width)) return page } } // MARK: - Private properties - private let scrollview:UIScrollView! private let bannerImage:JBKenBurnsView! private let bannerAlpha:UIView! private let bannerThin:UIView! private let navBar:UIView! private let indicatorcolor:UIView! private var controllers:[UIViewController]! private var labels:[UILabel]! private var titles:[NSString]! private var colors:[UIColor]! private var lastViewConstraint:NSArray? private var images :[UIImage]! required init?(coder aDecoder: NSCoder) { // Setup the scrollview scrollview = UIScrollView() scrollview.showsHorizontalScrollIndicator = false scrollview.showsVerticalScrollIndicator = false scrollview.pagingEnabled = true scrollview.scrollEnabled=true scrollview.decelerationRate=UIScrollViewDecelerationRateFast // Controllers as empty array controllers = Array() titles = Array() colors = Array() labels = Array() navTitle = UILabel() images = Array() //ImageView bannerImage=JBKenBurnsView(); bannerAlpha=UIView(); bannerThin=UIView(); //NavBut navBar=UIView(); indicatorcolor=UIView(); menuBut = UIButton(type: UIButtonType.System) super.init(coder: aDecoder) } func createHorizontalScroller(){ var x , y ,buffer:CGFloat horiScroll=UIScrollView(); horiScroll.frame=CGRectMake(0, 145, self.view.frame.width, 64) view.insertSubview(horiScroll, aboveSubview: scrollview); x=0;y=0;buffer=10 for var i=0; i < titles.count; i++ { var titleLabel:UILabel! var bottomView:UIView! titleLabel=UILabel(); //Label titleLabel.font=UIFont(name: "Roboto-Medium", size: 14) titleLabel.text=titles[i].uppercaseString as String titleLabel.userInteractionEnabled=true let lblWidth:CGFloat lblWidth = titleLabel.intrinsicContentSize().width + 32 titleLabel.frame=CGRectMake(x, 16, lblWidth, 34) titleLabel.textAlignment=NSTextAlignment.Center titleLabel.tag=i+1 titleLabel.textColor=UIColor.whiteColor() //Bottom bottomView=UIView() bottomView.backgroundColor=UIColor.whiteColor() let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:")) tap.delegate = self titleLabel.addGestureRecognizer(tap) horiScroll.addSubview(titleLabel) labels.append(titleLabel) x+=lblWidth+buffer } horiScroll.showsHorizontalScrollIndicator=false; horiScroll.backgroundColor=UIColor.clearColor(); horiScroll.contentSize=CGSizeMake(x,64) horiScroll.contentInset = UIEdgeInsetsMake(0, self.view.center.x-25, 0, 0.0); horiScroll.contentOffset=CGPointMake(-(self.view.center.x-50), y) // horiScroll.delegate = self horiScroll.translatesAutoresizingMaskIntoConstraints = false if(titles.count != 0){ indicatorcolor.frame=CGRectMake(labels[0].frame.origin.x, 61, labels[0].intrinsicContentSize().width+32, 3) indicatorcolor.backgroundColor=colors[0] horiScroll.addSubview(indicatorcolor) } self.view.bringSubviewToFront(horiScroll) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?){ scrollview = UIScrollView() controllers = Array() titles = Array() colors = Array() bannerImage=JBKenBurnsView(); bannerAlpha=UIView(); images = Array(); bannerThin=UIView(); labels = Array() navTitle = UILabel() //NavBut indicatorcolor=UIView(); navBar=UIView(); menuBut = UIButton(type: UIButtonType.System) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // Initialize UIScrollView scrollview.delegate = self scrollview.backgroundColor=UIColor.clearColor() scrollview.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(scrollview, atIndex: 0) //scrollview is inserted as first view of the hierarchy // Set scrollview related constraints view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollview]-0-|", options:[], metrics: nil, views: ["scrollview":scrollview])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollview]-0-|", options:[], metrics: nil, views: ["scrollview":scrollview])) bannerImage.frame=CGRectMake(0, 0, self.view.frame.width, 250) view.insertSubview(bannerImage, belowSubview: scrollview); view.insertSubview(bannerAlpha, aboveSubview: bannerImage); view.insertSubview(bannerThin, aboveSubview: bannerAlpha); // bannerImage.image=UIImage(named: "bg.jpg"); bannerImage.clipsToBounds=true // bannerImage.contentMode=UIViewContentMode.ScaleAspectFill bannerImage.backgroundColor=UIColor.clearColor(); bannerAlpha.frame=bannerImage.frame; bannerAlpha.alpha=0.3; bannerThin.frame=bannerImage.frame; bannerThin.alpha=0.3; bannerAlpha.backgroundColor=UIColor.blackColor() bannerThin.backgroundColor=UIColor.blackColor() //NavBut navBar.frame=CGRectMake(0, 0, self.view.frame.width, 64); navBar.backgroundColor=UIColor.clearColor() menuBut.frame = CGRectMake(16, 27 , 20, 20) menuBut.tintColor=UIColor.whiteColor() menuBut.setImage(UIImage(named: "back2")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Normal) menuBut.addTarget(self, action: "handleCloseBtn", forControlEvents: .TouchUpInside) navTitle.frame = CGRectMake(50, 21 , 100, 30) navTitle.text = "Read Now" navTitle.textColor=UIColor.whiteColor() navTitle.alpha=0; navTitle.font=UIFont(name: "Roboto-Medium", size: 20) navBar.addSubview(menuBut) navBar.addSubview(navTitle) view.insertSubview(navBar, aboveSubview: scrollview); self.setNeedsStatusBarAppearanceUpdate() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func prefersStatusBarHidden() -> Bool { return showStatus } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); createHorizontalScroller() currentColor=colors[0] self.bannerAlpha.mdInflateAnimatedFromPoint(CGPointMake(self.bannerImage.center.x , self.bannerImage.center.y), backgroundColor: self.currentColor, duration: 0.6, completion: nil) images=Array() images.append(UIImage(named: "concert.jpg")!) images.append(UIImage(named: "fashion.jpg")!) images.append(UIImage(named: "festival.jpg")!) images.append(UIImage(named: "fun.jpg")!) images.append(UIImage(named: "mud.jpg")!) bannerImage.animateWithImages(images, transitionDuration:6, initialDelay: 0, loop: true, isLandscape: true) } // MARK: - Tap Gesture func handleCloseBtn() { dismissViewControllerAnimated(true, completion: nil) } func handleTap(sender:UIGestureRecognizer){ scrollview.scrollRectToVisible(controllers[sender.view!.tag-1].view.frame, animated: true) currentColor=colors[sender.view!.tag-1] // Notify delegate about the new page if(navBar.backgroundColor != UIColor.clearColor()){ UIView.animateWithDuration(0.2, animations: { () -> Void in self.indicatorcolor.frame=CGRectMake(self.labels[sender.view!.tag-1].frame.origin.x, 61, self.labels[sender.view!.tag-1].intrinsicContentSize().width+32, 3) self.indicatorcolor.backgroundColor=UIColor.whiteColor() self.horiScroll.scrollRectToVisible(self.labels[sender.view!.tag-1].frame, animated: true) self.navBar.backgroundColor=self.currentColor self.horiScroll.backgroundColor=self.currentColor }) } else{ UIView.animateWithDuration(0.2, animations: { () -> Void in self.indicatorcolor.frame=CGRectMake(self.labels[sender.view!.tag-1].frame.origin.x, 61, self.labels[sender.view!.tag-1].intrinsicContentSize().width+32, 3) self.indicatorcolor.backgroundColor=self.currentColor // self.horiScroll.scrollRectToVisible(self.labels[sender.view!.tag-1].frame, animated: true) //Center Content self.horiScroll.setContentOffset(CGPointMake(-(self.view.center.x-50)+self.labels[sender.view!.tag-1].center.x-self.labels[sender.view!.tag-1].frame.size.width/2, 0), animated: true) }) } self.bannerAlpha.mdInflateAnimatedFromPoint(CGPointMake(self.bannerImage.center.x , self.bannerImage.center.y), backgroundColor: self.currentColor, duration: 0.6, completion: nil) } /** addViewController */ func addViewController(vc:UIViewController)->Void{ controllers.append(vc) // Setup the viewController view vc.view.translatesAutoresizingMaskIntoConstraints = false scrollview.addSubview(vc.view) // Constraints let metricDict = ["w":vc.view.bounds.size.width,"h":vc.view.bounds.size.height] // - Generic cnst vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view(h)]", options:[], metrics: metricDict, views: ["view":vc.view])) vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[view(w)]", options:[], metrics: metricDict, views: ["view":vc.view])) scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]|", options:[], metrics: nil, views: ["view":vc.view,])) // cnst for position: 1st element if controllers.count == 1{ scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]", options:[], metrics: nil, views: ["view":vc.view,])) // cnst for position: other elements }else{ let previousVC = controllers[controllers.count-2] let previousView = previousVC.view; scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[previousView]-0-[view]", options:[], metrics: nil, views: ["previousView":previousView,"view":vc.view])) if let cst = lastViewConstraint{ scrollview.removeConstraints(cst as! [NSLayoutConstraint]) } lastViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:[view]-0-|", options:[], metrics: nil, views: ["view":vc.view]) scrollview.addConstraints(lastViewConstraint! as! [NSLayoutConstraint]) } } func addViewControllerWithTitleandColor(vc:UIViewController , title:NSString , color:UIColor)->Void{ controllers.append(vc) titles.append(title) colors.append(color) // NSLog("%@",titles) // Setup the viewController view vc.view.translatesAutoresizingMaskIntoConstraints = false scrollview.addSubview(vc.view) let metricDict = ["w":vc.view.bounds.size.width,"h":vc.view.bounds.size.height] // Constraints // - Generic cnst vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view(h)]", options:[], metrics: metricDict, views: ["view":vc.view])) vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[view(w)]", options:[], metrics: metricDict, views: ["view":vc.view])) scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]|", options:[], metrics: nil, views: ["view":vc.view,])) // cnst for position: 1st element if controllers.count == 1{ scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]", options:[], metrics: nil, views: ["view":vc.view,])) // cnst for position: other elements }else{ let previousVC = controllers[controllers.count-2] let previousView = previousVC.view; scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[previousView]-0-[view]", options:[], metrics: nil, views: ["previousView":previousView,"view":vc.view])) if let cst = lastViewConstraint{ scrollview.removeConstraints(cst as! [NSLayoutConstraint]) } lastViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:[view]-0-|", options:[], metrics: nil, views: ["view":vc.view]) scrollview.addConstraints(lastViewConstraint! as! [NSLayoutConstraint]) } } /** Update the UI to reflect the current walkthrough situation **/ private func updateUI(){ // Get the current page // NSLog("up %d",currentPage); // pageControl?.currentPage = currentPage currentColor=colors[currentPage] // Notify delegate about the new page if(navBar.backgroundColor != UIColor.clearColor()){ UIView.animateWithDuration(0.2, animations: { () -> Void in self.indicatorcolor.frame=CGRectMake(self.labels[self.currentPage].frame.origin.x, 61, self.labels[self.currentPage].intrinsicContentSize().width+32, 3) self.indicatorcolor.backgroundColor=UIColor.whiteColor() self.horiScroll.scrollRectToVisible(self.labels[self.currentPage].frame, animated: true) self.navBar.backgroundColor=self.currentColor self.horiScroll.backgroundColor=self.currentColor }) } else{ UIView.animateWithDuration(0.2, animations: { () -> Void in self.indicatorcolor.frame=CGRectMake(self.labels[self.currentPage].frame.origin.x, 61, self.labels[self.currentPage].intrinsicContentSize().width+32, 3) self.indicatorcolor.backgroundColor=self.currentColor //Center Content self.horiScroll.setContentOffset(CGPointMake(-(self.view.center.x-50)+self.labels[self.currentPage].center.x-self.labels[self.currentPage].frame.size.width/2, 0), animated: true) }) } self.bannerAlpha.mdInflateAnimatedFromPoint(CGPointMake(self.bannerImage.center.x , self.bannerImage.center.y), backgroundColor: self.currentColor, duration: 0.6, completion: nil) } // MARK: - Scrollview Delegate - func scrollViewDidScroll(sv: UIScrollView) { for var i=0; i < controllers.count; i++ { if let vc = controllers[i] as? MMPlayPageScroll{ let mx = ((scrollview.contentOffset.x + view.bounds.size.width) - (view.bounds.size.width * CGFloat(i))) / view.bounds.size.width // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. // print the mx value to get more info. // println("\(i):\(mx)") // We animate only the previous, current and next page // NSLog("%f %f", scrollview.contentOffset.x,mx) if(mx < 2 && mx > -2.0){ vc.walkthroughDidScroll(scrollview.contentOffset.x, offset: mx) } } } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { updateUI() } /* WIP */ override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { print("CHANGE") } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { print("SIZE") } //MARK Y-axis func scrollYAxis(offset:CGFloat ,translation:CGPoint) { if(offset > 0){ var horiScrollTransform : CATransform3D! = CATransform3DIdentity var navBarTransform : CATransform3D! = CATransform3DIdentity var imageTransform : CATransform3D! = CATransform3DIdentity // NSLog("Hello Y-Axis %f",offset) for var i=0; i < controllers.count; i++ { if(controllers[i].isKindOfClass(MMSampleTableViewController)){ let temp=controllers[i] as! MMSampleTableViewController temp.tableView.contentOffset=CGPointMake(0, offset) UIView.animateWithDuration(0.3, animations: { () -> Void in if(offset > 10){ temp.headerImage.alpha=0 } else { temp.headerImage.alpha=1 } }) } if( currentPage == i){ //Color Change if(lastOffset > offset){ if(offset < 100 ){ showStatus = false setNeedsStatusBarAppearanceUpdate() self.horiScroll.setContentOffset(CGPointMake(-(self.view.center.x-50)+self.labels[self.currentPage].center.x-self.labels[self.currentPage].frame.size.width/2, 0), animated: true) UIView.animateWithDuration(0.3, delay: 0, options: [], animations: { () -> Void in self.horiScroll.contentInset = UIEdgeInsetsMake(0, self.view.center.x-25, 0, 0.0); // self.horiScroll.setContentOffset(CGPointMake(-(self.view.center.x-50), 0), animated: true) self.horiScroll.backgroundColor=UIColor.clearColor() self.navBar.backgroundColor=UIColor.clearColor() self.indicatorcolor.backgroundColor=self.currentColor; self.navTitle.alpha=0; }, completion: nil) } } else{ if(offset > 220 ){ UIView.animateWithDuration(0.3, delay: 0, options: [], animations: { () -> Void in self.horiScroll.backgroundColor=self.currentColor self.navBar.backgroundColor=self.currentColor self.navTitle.alpha=1; self.indicatorcolor.backgroundColor=UIColor.whiteColor() self.horiScroll.contentInset = UIEdgeInsetsMake(0, 0, 0, 0.0); //horiScroll.contentOffset=CGPointMake(0, 0) self.horiScroll.scrollRectToVisible(self.labels[self.currentPage].frame, animated: true) }, completion: nil) } } //Translation if(offset > 0){ horiScrollTransform=CATransform3DTranslate(horiScrollTransform, 0, -offset, 0) horiScroll.layer.transform=horiScrollTransform let x = bannerImage.frame.origin.x let w = bannerImage.bounds.width let h = bannerImage.bounds.height let y = -((offset - bannerImage.frame.origin.y) / 75) * 25 imageTransform=CATransform3DTranslate(imageTransform, 0, -offset, 0) bannerImage.frame = CGRectMake(x, y, w, h) bannerAlpha.frame = CGRectMake(x, y, w, h) bannerThin.frame = CGRectMake(x, y, w, h) //bannerImage.layer.transform=imageTransform //bannerAlpha.layer.transform=imageTransform //bannerThin.layer.transform=imageTransform if(offset > 100){ showStatus = true setNeedsStatusBarAppearanceUpdate() navBarTransform=CATransform3DTranslate(navBarTransform, 0, -offset+100, 0) navBar.layer.transform=navBarTransform } else{ } } } } } lastOffset=offset } func getframeindexpathOfController()-> CGRect{ let temp = controllers[currentPage] as! MMSampleTableViewController return temp.tableView.framesForRowAtIndexPath(temp.tableView.indexPathForSelectedRow!) } }
mit
c47051ab0b052fe2c8618da8f47887e7
44.860507
206
0.60474
5.300461
false
false
false
false
wyxy2005/SEGSegmentedViewController
SegmentedViewControllerTests/Mocks/SegmentedViewControllerItemPresenterMock.swift
1
869
// // SegmentedViewControllerItemPresenterMock.swift // SegmentedViewController // // Created by Thomas Sherwood on 08/09/2014. // Copyright (c) 2014 Thomas Sherwood. All rights reserved. // import Foundation import SegmentedViewController import UIKit class SegmentedViewControllerItemPresenterMock: SegmentedViewControllerItemPresenter { var item: SegmentedViewControllerItem? var index: Int? var animated: Bool? var cleared: Bool = false init() {} func presentItem(item: SegmentedViewControllerItem, atIndex index: Int, usingAnimation animated: Bool) { self.item = item self.index = index self.animated = animated } func refreshItem(item: SegmentedViewControllerItem, atIndex index: Int, usingAnimation animated: Bool) { self.item = item self.index = index self.animated = animated } func clearItems() { cleared = true } }
mit
7b85f6b2796419acd9aa10fd2899ec3c
21.868421
105
0.756041
4.138095
false
false
false
false
srxboys/RXSwiftExtention
Pods/SwifterSwift/Source/Extensions/UIKit/UIColorExtensions.swift
1
33557
// // UIColorExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/6/16. // Copyright © 2016 Omar Albeik. All rights reserved. // #if !os(macOS) import UIKit // MARK: - Properties public extension UIColor { /// SwifterSwift: Red component of UIColor (read-only). public var redComponent: Int { var red: CGFloat = 0.0 getRed(&red, green: nil, blue: nil, alpha: nil) return Int(red * 255) } /// SwifterSwift: Green component of UIColor (read-only). public var greenComponent: Int { var green: CGFloat = 0.0 getRed(nil, green: &green, blue: nil, alpha: nil) return Int(green * 255) } /// SwifterSwift: blue component of UIColor (read-only). public var blueComponent: Int { var blue: CGFloat = 0.0 getRed(nil, green: nil, blue: &blue, alpha: nil) return Int(blue * 255) } /// SwifterSwift: Alpha of UIColor (read-only). public var alpha: CGFloat { var a: CGFloat = 0.0 getRed(nil, green: nil, blue: nil, alpha: &a) return a } /// SwifterSwift: Hexadecimal value string (read-only). public var hexString: String { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) let rgb: Int = (Int)(red*255)<<16 | (Int)(green*255)<<8 | (Int)(blue*255)<<0 return NSString(format:"#%06x", rgb).uppercased as String } /// SwifterSwift: Short hexadecimal value string (read-only, if applicable). public var shortHexString: String? { let string = hexString.replacing("#", with: "") guard let first = string[0], first == string[1], let second = string[2], second == string[3], let third = string[4], third == string[5] else { return nil } return "#" + first + second + third } /// SwifterSwift: Short hexadecimal value string, or full hexadecimal string if not possible (read-only). public var shortHexOrHexString: String { return shortHexString ?? hexString } /// SwifterSwift: Get color complementary (read-only, if applicable). public var complementary: UIColor? { return UIColor.init(complementaryFor: self) } /// SwifterSwift: Random color. public static var random: UIColor { let r = Int(arc4random_uniform(255)) let g = Int(arc4random_uniform(255)) let b = Int(arc4random_uniform(255)) return UIColor(red: r, green: g, blue: b) } } // MARK: - Methods public extension UIColor { /// SwifterSwift: Blend two UIColors /// /// - Parameters: /// - color1: first color to blend /// - intensity1: intensity of first color (default is 0.5) /// - color2: second color to blend /// - intensity2: intensity of second color (default is 0.5) /// - Returns: UIColor created by blending first and seond colors. public static func blend(_ color1: UIColor, intensity1: CGFloat = 0.5, with color2: UIColor, intensity2: CGFloat = 0.5) -> UIColor { // http://stackoverflow.com/questions/27342715/blend-uicolors-in-swift let total = intensity1 + intensity2 let l1 = intensity1/total let l2 = intensity2/total guard l1 > 0 else { return color2} guard l2 > 0 else { return color1} var (r1, g1, b1, a1): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0) var (r2, g2, b2, a2): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0) color1.getRed(&r1, green: &g1, blue: &b1, alpha: &a1) color2.getRed(&r2, green: &g2, blue: &b2, alpha: &a2) return UIColor(red: l1*r1 + l2*r2, green: l1*g1 + l2*g2, blue: l1*b1 + l2*b2, alpha: l1*a1 + l2*a2) } } // MARK: - Initializers public extension UIColor { /// SwifterSwift: Create UIColor from hexadecimal value with optional transparency. /// /// - Parameters: /// - hex: hex Int (example: 0xDECEB5). /// - transparency: optional transparency value (default is 1). public convenience init(hex: Int, transparency: CGFloat = 1) { var trans: CGFloat { if transparency > 1 { return 1 } else if transparency < 0 { return 0 } else { return transparency } } self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff, transparency: trans) } /// SwifterSwift: Create UIColor from hexadecimal string with optional transparency (if applicable). /// /// - Parameters: /// - hexString: hexadecimal string (examples: EDE7F6, 0xEDE7F6, #EDE7F6, #0ff, 0xF0F, ..). /// - transparency: optional transparency value (default is 1). public convenience init?(hexString: String, transparency: CGFloat = 1) { var string = "" if hexString.lowercased().starts(with: "0x") { string = hexString.replacing("0x", with: "") } else if hexString.starts(with: "#") { string = hexString.replacing("#", with: "") } else { string = hexString } if string.characters.count == 3 { // convert hex to 6 digit format if in short format var str = "" string.characters.forEach({ str.append($0 * 2) }) string = str } guard let hexValue = Int(string, radix: 16) else { return nil } self.init(hex: Int(hexValue), transparency: transparency) } /// SwifterSwift: Create UIColor from RGB values with optional transparency. /// /// - Parameters: /// - red: red component. /// - green: green component. /// - blue: blue component. /// - transparency: optional transparency value (default is 1). public convenience init(red: Int, green: Int, blue: Int, transparency: CGFloat = 1) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") var trans: CGFloat { if transparency > 1 { return 1 } else if transparency < 0 { return 0 } else { return transparency } } self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: trans) } /// SwifterSwift: Create UIColor from a complementary of a UIColor (if applicable). /// /// - Parameter color: color of which opposite color is desired. public convenience init?(complementaryFor color: UIColor) { let colorSpaceRGB = CGColorSpaceCreateDeviceRGB() let convertColorToRGBSpace : ((_ color : UIColor) -> UIColor?) = { (color) -> UIColor? in if color.cgColor.colorSpace!.model == CGColorSpaceModel.monochrome { let oldComponents = color.cgColor.components let components : [CGFloat] = [ oldComponents![0], oldComponents![0], oldComponents![0], oldComponents![1] ] let colorRef = CGColor(colorSpace: colorSpaceRGB, components: components) let colorOut = UIColor(cgColor: colorRef!) return colorOut } else { return color } } let c = convertColorToRGBSpace(color) guard let componentColors = c?.cgColor.components else { return nil } let r: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[0]*255), 2.0))/255 let g: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[1]*255), 2.0))/255 let b: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[2]*255), 2.0))/255 self.init(red: r, green: g, blue: b, alpha: 1.0) } } //MARK: - Social Colors public extension UIColor { /// SwifterSwift: Brand identity color of popular social media platform. public struct social { // https://www.lockedowndesign.com/social-media-colors/ public static let facebook = UIColor(red: 59, green: 89, blue: 152) public static let twitter = UIColor(red: 0, green: 182, blue: 241) public static let googlePlus = UIColor(red: 223, green: 74, blue: 50) public static let linkedIn = UIColor(red: 0, green: 123, blue: 182) public static let vimeo = UIColor(red: 69, green: 187, blue: 255) public static let youtube = UIColor(red: 179, green: 18, blue: 23) public static let instagram = UIColor(red: 195, green: 42, blue: 163) public static let pinterest = UIColor(red: 203, green: 32, blue: 39) public static let flickr = UIColor(red: 244, green: 0, blue: 131) public static let yahoo = UIColor(red: 67, green: 2, blue: 151) public static let soundCloud = UIColor(red: 255, green: 85, blue: 0) public static let tumblr = UIColor(red: 44, green: 71, blue: 98) public static let foursquare = UIColor(red: 252, green: 69, blue: 117) public static let swarm = UIColor(red: 255, green: 176, blue: 0) public static let dribbble = UIColor(red: 234, green: 76, blue: 137) public static let reddit = UIColor(red: 255, green: 87, blue: 0) public static let devianArt = UIColor(red: 74, green: 93, blue: 78) public static let pocket = UIColor(red: 238, green: 64, blue: 86) public static let quora = UIColor(red: 170, green: 34, blue: 182) public static let slideShare = UIColor(red: 247, green: 146, blue: 30) public static let px500 = UIColor(red: 0, green: 153, blue: 229) public static let listly = UIColor(red: 223, green: 109, blue: 70) public static let vine = UIColor(red: 0, green: 180, blue: 137) public static let skype = UIColor(red: 0, green: 175, blue: 240) public static let stumbleUpon = UIColor(red: 235, green: 73, blue: 36) public static let snapchat = UIColor(red: 255, green: 252, blue: 0) } } //MARK: - Material colors public extension UIColor { /// SwifterSwift: Google Material design colors palette. public struct material { // https://material.google.com/style/color.html public static let red = red500 public static let red50 = UIColor(hex: 0xFFEBEE) public static let red100 = UIColor(hex: 0xFFCDD2) public static let red200 = UIColor(hex: 0xEF9A9A) public static let red300 = UIColor(hex: 0xE57373) public static let red400 = UIColor(hex: 0xEF5350) public static let red500 = UIColor(hex: 0xF44336) public static let red600 = UIColor(hex: 0xE53935) public static let red700 = UIColor(hex: 0xD32F2F) public static let red800 = UIColor(hex: 0xC62828) public static let red900 = UIColor(hex: 0xB71C1C) public static let redA100 = UIColor(hex: 0xFF8A80) public static let redA200 = UIColor(hex: 0xFF5252) public static let redA400 = UIColor(hex: 0xFF1744) public static let redA700 = UIColor(hex: 0xD50000) public static let pink = pink500 public static let pink50 = UIColor(hex: 0xFCE4EC) public static let pink100 = UIColor(hex: 0xF8BBD0) public static let pink200 = UIColor(hex: 0xF48FB1) public static let pink300 = UIColor(hex: 0xF06292) public static let pink400 = UIColor(hex: 0xEC407A) public static let pink500 = UIColor(hex: 0xE91E63) public static let pink600 = UIColor(hex: 0xD81B60) public static let pink700 = UIColor(hex: 0xC2185B) public static let pink800 = UIColor(hex: 0xAD1457) public static let pink900 = UIColor(hex: 0x880E4F) public static let pinkA100 = UIColor(hex: 0xFF80AB) public static let pinkA200 = UIColor(hex: 0xFF4081) public static let pinkA400 = UIColor(hex: 0xF50057) public static let pinkA700 = UIColor(hex: 0xC51162) public static let purple = purple500 public static let purple50 = UIColor(hex: 0xF3E5F5) public static let purple100 = UIColor(hex: 0xE1BEE7) public static let purple200 = UIColor(hex: 0xCE93D8) public static let purple300 = UIColor(hex: 0xBA68C8) public static let purple400 = UIColor(hex: 0xAB47BC) public static let purple500 = UIColor(hex: 0x9C27B0) public static let purple600 = UIColor(hex: 0x8E24AA) public static let purple700 = UIColor(hex: 0x7B1FA2) public static let purple800 = UIColor(hex: 0x6A1B9A) public static let purple900 = UIColor(hex: 0x4A148C) public static let purpleA100 = UIColor(hex: 0xEA80FC) public static let purpleA200 = UIColor(hex: 0xE040FB) public static let purpleA400 = UIColor(hex: 0xD500F9) public static let purpleA700 = UIColor(hex: 0xAA00FF) public static let deepPurple = deepPurple500 public static let deepPurple50 = UIColor(hex: 0xEDE7F6) public static let deepPurple100 = UIColor(hex: 0xD1C4E9) public static let deepPurple200 = UIColor(hex: 0xB39DDB) public static let deepPurple300 = UIColor(hex: 0x9575CD) public static let deepPurple400 = UIColor(hex: 0x7E57C2) public static let deepPurple500 = UIColor(hex: 0x673AB7) public static let deepPurple600 = UIColor(hex: 0x5E35B1) public static let deepPurple700 = UIColor(hex: 0x512DA8) public static let deepPurple800 = UIColor(hex: 0x4527A0) public static let deepPurple900 = UIColor(hex: 0x311B92) public static let deepPurpleA100 = UIColor(hex: 0xB388FF) public static let deepPurpleA200 = UIColor(hex: 0x7C4DFF) public static let deepPurpleA400 = UIColor(hex: 0x651FFF) public static let deepPurpleA700 = UIColor(hex: 0x6200EA) public static let indigo = indigo500 public static let indigo50 = UIColor(hex: 0xE8EAF6) public static let indigo100 = UIColor(hex: 0xC5CAE9) public static let indigo200 = UIColor(hex: 0x9FA8DA) public static let indigo300 = UIColor(hex: 0x7986CB) public static let indigo400 = UIColor(hex: 0x5C6BC0) public static let indigo500 = UIColor(hex: 0x3F51B5) public static let indigo600 = UIColor(hex: 0x3949AB) public static let indigo700 = UIColor(hex: 0x303F9F) public static let indigo800 = UIColor(hex: 0x283593) public static let indigo900 = UIColor(hex: 0x1A237E) public static let indigoA100 = UIColor(hex: 0x8C9EFF) public static let indigoA200 = UIColor(hex: 0x536DFE) public static let indigoA400 = UIColor(hex: 0x3D5AFE) public static let indigoA700 = UIColor(hex: 0x304FFE) public static let blue = blue500 public static let blue50 = UIColor(hex: 0xE3F2FD) public static let blue100 = UIColor(hex: 0xBBDEFB) public static let blue200 = UIColor(hex: 0x90CAF9) public static let blue300 = UIColor(hex: 0x64B5F6) public static let blue400 = UIColor(hex: 0x42A5F5) public static let blue500 = UIColor(hex: 0x2196F3) public static let blue600 = UIColor(hex: 0x1E88E5) public static let blue700 = UIColor(hex: 0x1976D2) public static let blue800 = UIColor(hex: 0x1565C0) public static let blue900 = UIColor(hex: 0x0D47A1) public static let blueA100 = UIColor(hex: 0x82B1FF) public static let blueA200 = UIColor(hex: 0x448AFF) public static let blueA400 = UIColor(hex: 0x2979FF) public static let blueA700 = UIColor(hex: 0x2962FF) public static let lightBlue = lightBlue500 public static let lightBlue50 = UIColor(hex: 0xE1F5FE) public static let lightBlue100 = UIColor(hex: 0xB3E5FC) public static let lightBlue200 = UIColor(hex: 0x81D4FA) public static let lightBlue300 = UIColor(hex: 0x4FC3F7) public static let lightBlue400 = UIColor(hex: 0x29B6F6) public static let lightBlue500 = UIColor(hex: 0x03A9F4) public static let lightBlue600 = UIColor(hex: 0x039BE5) public static let lightBlue700 = UIColor(hex: 0x0288D1) public static let lightBlue800 = UIColor(hex: 0x0277BD) public static let lightBlue900 = UIColor(hex: 0x01579B) public static let lightBlueA100 = UIColor(hex: 0x80D8FF) public static let lightBlueA200 = UIColor(hex: 0x40C4FF) public static let lightBlueA400 = UIColor(hex: 0x00B0FF) public static let lightBlueA700 = UIColor(hex: 0x0091EA) public static let cyan = cyan500 public static let cyan50 = UIColor(hex: 0xE0F7FA) public static let cyan100 = UIColor(hex: 0xB2EBF2) public static let cyan200 = UIColor(hex: 0x80DEEA) public static let cyan300 = UIColor(hex: 0x4DD0E1) public static let cyan400 = UIColor(hex: 0x26C6DA) public static let cyan500 = UIColor(hex: 0x00BCD4) public static let cyan600 = UIColor(hex: 0x00ACC1) public static let cyan700 = UIColor(hex: 0x0097A7) public static let cyan800 = UIColor(hex: 0x00838F) public static let cyan900 = UIColor(hex: 0x006064) public static let cyanA100 = UIColor(hex: 0x84FFFF) public static let cyanA200 = UIColor(hex: 0x18FFFF) public static let cyanA400 = UIColor(hex: 0x00E5FF) public static let cyanA700 = UIColor(hex: 0x00B8D4) public static let teal = teal500 public static let teal50 = UIColor(hex: 0xE0F2F1) public static let teal100 = UIColor(hex: 0xB2DFDB) public static let teal200 = UIColor(hex: 0x80CBC4) public static let teal300 = UIColor(hex: 0x4DB6AC) public static let teal400 = UIColor(hex: 0x26A69A) public static let teal500 = UIColor(hex: 0x009688) public static let teal600 = UIColor(hex: 0x00897B) public static let teal700 = UIColor(hex: 0x00796B) public static let teal800 = UIColor(hex: 0x00695C) public static let teal900 = UIColor(hex: 0x004D40) public static let tealA100 = UIColor(hex: 0xA7FFEB) public static let tealA200 = UIColor(hex: 0x64FFDA) public static let tealA400 = UIColor(hex: 0x1DE9B6) public static let tealA700 = UIColor(hex: 0x00BFA5) public static let green = green500 public static let green50 = UIColor(hex: 0xE8F5E9) public static let green100 = UIColor(hex: 0xC8E6C9) public static let green200 = UIColor(hex: 0xA5D6A7) public static let green300 = UIColor(hex: 0x81C784) public static let green400 = UIColor(hex: 0x66BB6A) public static let green500 = UIColor(hex: 0x4CAF50) public static let green600 = UIColor(hex: 0x43A047) public static let green700 = UIColor(hex: 0x388E3C) public static let green800 = UIColor(hex: 0x2E7D32) public static let green900 = UIColor(hex: 0x1B5E20) public static let greenA100 = UIColor(hex: 0xB9F6CA) public static let greenA200 = UIColor(hex: 0x69F0AE) public static let greenA400 = UIColor(hex: 0x00E676) public static let greenA700 = UIColor(hex: 0x00C853) public static let lightGreen = lightGreen500 public static let lightGreen50 = UIColor(hex: 0xF1F8E9) public static let lightGreen100 = UIColor(hex: 0xDCEDC8) public static let lightGreen200 = UIColor(hex: 0xC5E1A5) public static let lightGreen300 = UIColor(hex: 0xAED581) public static let lightGreen400 = UIColor(hex: 0x9CCC65) public static let lightGreen500 = UIColor(hex: 0x8BC34A) public static let lightGreen600 = UIColor(hex: 0x7CB342) public static let lightGreen700 = UIColor(hex: 0x689F38) public static let lightGreen800 = UIColor(hex: 0x558B2F) public static let lightGreen900 = UIColor(hex: 0x33691E) public static let lightGreenA100 = UIColor(hex: 0xCCFF90) public static let lightGreenA200 = UIColor(hex: 0xB2FF59) public static let lightGreenA400 = UIColor(hex: 0x76FF03) public static let lightGreenA700 = UIColor(hex: 0x64DD17) public static let lime = lime500 public static let lime50 = UIColor(hex: 0xF9FBE7) public static let lime100 = UIColor(hex: 0xF0F4C3) public static let lime200 = UIColor(hex: 0xE6EE9C) public static let lime300 = UIColor(hex: 0xDCE775) public static let lime400 = UIColor(hex: 0xD4E157) public static let lime500 = UIColor(hex: 0xCDDC39) public static let lime600 = UIColor(hex: 0xC0CA33) public static let lime700 = UIColor(hex: 0xAFB42B) public static let lime800 = UIColor(hex: 0x9E9D24) public static let lime900 = UIColor(hex: 0x827717) public static let limeA100 = UIColor(hex: 0xF4FF81) public static let limeA200 = UIColor(hex: 0xEEFF41) public static let limeA400 = UIColor(hex: 0xC6FF00) public static let limeA700 = UIColor(hex: 0xAEEA00) public static let yellow = yellow500 public static let yellow50 = UIColor(hex: 0xFFFDE7) public static let yellow100 = UIColor(hex: 0xFFF9C4) public static let yellow200 = UIColor(hex: 0xFFF59D) public static let yellow300 = UIColor(hex: 0xFFF176) public static let yellow400 = UIColor(hex: 0xFFEE58) public static let yellow500 = UIColor(hex: 0xFFEB3B) public static let yellow600 = UIColor(hex: 0xFDD835) public static let yellow700 = UIColor(hex: 0xFBC02D) public static let yellow800 = UIColor(hex: 0xF9A825) public static let yellow900 = UIColor(hex: 0xF57F17) public static let yellowA100 = UIColor(hex: 0xFFFF8D) public static let yellowA200 = UIColor(hex: 0xFFFF00) public static let yellowA400 = UIColor(hex: 0xFFEA00) public static let yellowA700 = UIColor(hex: 0xFFD600) public static let amber = amber500 public static let amber50 = UIColor(hex: 0xFFF8E1) public static let amber100 = UIColor(hex: 0xFFECB3) public static let amber200 = UIColor(hex: 0xFFE082) public static let amber300 = UIColor(hex: 0xFFD54F) public static let amber400 = UIColor(hex: 0xFFCA28) public static let amber500 = UIColor(hex: 0xFFC107) public static let amber600 = UIColor(hex: 0xFFB300) public static let amber700 = UIColor(hex: 0xFFA000) public static let amber800 = UIColor(hex: 0xFF8F00) public static let amber900 = UIColor(hex: 0xFF6F00) public static let amberA100 = UIColor(hex: 0xFFE57F) public static let amberA200 = UIColor(hex: 0xFFD740) public static let amberA400 = UIColor(hex: 0xFFC400) public static let amberA700 = UIColor(hex: 0xFFAB00) public static let orange = orange500 public static let orange50 = UIColor(hex: 0xFFF3E0) public static let orange100 = UIColor(hex: 0xFFE0B2) public static let orange200 = UIColor(hex: 0xFFCC80) public static let orange300 = UIColor(hex: 0xFFB74D) public static let orange400 = UIColor(hex: 0xFFA726) public static let orange500 = UIColor(hex: 0xFF9800) public static let orange600 = UIColor(hex: 0xFB8C00) public static let orange700 = UIColor(hex: 0xF57C00) public static let orange800 = UIColor(hex: 0xEF6C00) public static let orange900 = UIColor(hex: 0xE65100) public static let orangeA100 = UIColor(hex: 0xFFD180) public static let orangeA200 = UIColor(hex: 0xFFAB40) public static let orangeA400 = UIColor(hex: 0xFF9100) public static let orangeA700 = UIColor(hex: 0xFF6D00) public static let deepOrange = deepOrange500 public static let deepOrange50 = UIColor(hex: 0xFBE9E7) public static let deepOrange100 = UIColor(hex: 0xFFCCBC) public static let deepOrange200 = UIColor(hex: 0xFFAB91) public static let deepOrange300 = UIColor(hex: 0xFF8A65) public static let deepOrange400 = UIColor(hex: 0xFF7043) public static let deepOrange500 = UIColor(hex: 0xFF5722) public static let deepOrange600 = UIColor(hex: 0xF4511E) public static let deepOrange700 = UIColor(hex: 0xE64A19) public static let deepOrange800 = UIColor(hex: 0xD84315) public static let deepOrange900 = UIColor(hex: 0xBF360C) public static let deepOrangeA100 = UIColor(hex: 0xFF9E80) public static let deepOrangeA200 = UIColor(hex: 0xFF6E40) public static let deepOrangeA400 = UIColor(hex: 0xFF3D00) public static let deepOrangeA700 = UIColor(hex: 0xDD2C00) public static let brown = brown500 public static let brown50 = UIColor(hex: 0xEFEBE9) public static let brown100 = UIColor(hex: 0xD7CCC8) public static let brown200 = UIColor(hex: 0xBCAAA4) public static let brown300 = UIColor(hex: 0xA1887F) public static let brown400 = UIColor(hex: 0x8D6E63) public static let brown500 = UIColor(hex: 0x795548) public static let brown600 = UIColor(hex: 0x6D4C41) public static let brown700 = UIColor(hex: 0x5D4037) public static let brown800 = UIColor(hex: 0x4E342E) public static let brown900 = UIColor(hex: 0x3E2723) public static let grey = grey500 public static let grey50 = UIColor(hex: 0xFAFAFA) public static let grey100 = UIColor(hex: 0xF5F5F5) public static let grey200 = UIColor(hex: 0xEEEEEE) public static let grey300 = UIColor(hex: 0xE0E0E0) public static let grey400 = UIColor(hex: 0xBDBDBD) public static let grey500 = UIColor(hex: 0x9E9E9E) public static let grey600 = UIColor(hex: 0x757575) public static let grey700 = UIColor(hex: 0x616161) public static let grey800 = UIColor(hex: 0x424242) public static let grey900 = UIColor(hex: 0x212121) public static let blueGrey = blueGrey500 public static let blueGrey50 = UIColor(hex: 0xECEFF1) public static let blueGrey100 = UIColor(hex: 0xCFD8DC) public static let blueGrey200 = UIColor(hex: 0xB0BEC5) public static let blueGrey300 = UIColor(hex: 0x90A4AE) public static let blueGrey400 = UIColor(hex: 0x78909C) public static let blueGrey500 = UIColor(hex: 0x607D8B) public static let blueGrey600 = UIColor(hex: 0x546E7A) public static let blueGrey700 = UIColor(hex: 0x455A64) public static let blueGrey800 = UIColor(hex: 0x37474F) public static let blueGrey900 = UIColor(hex: 0x263238) public static let black = UIColor(hex: 0x000000) public static let white = UIColor(hex: 0xFFFFFF) } } public extension UIColor { /// SwifterSwift: CSS colors. public struct css { // http://www.w3schools.com/colors/colors_names.asp public static let aliceBlue = UIColor(hex: 0xF0F8FF) public static let antiqueWhite = UIColor(hex: 0xFAEBD7) public static let aqua = UIColor(hex: 0x00FFFF) public static let aquamarine = UIColor(hex: 0x7FFFD4) public static let azure = UIColor(hex: 0xF0FFFF) public static let beige = UIColor(hex: 0xF5F5DC) public static let bisque = UIColor(hex: 0xFFE4C4) public static let black = UIColor(hex: 0x000000) public static let blanchedAlmond = UIColor(hex: 0xFFEBCD) public static let blue = UIColor(hex: 0x0000FF) public static let blueViolet = UIColor(hex: 0x8A2BE2) public static let brown = UIColor(hex: 0xA52A2A) public static let burlyWood = UIColor(hex: 0xDEB887) public static let cadetBlue = UIColor(hex: 0x5F9EA0) public static let chartreuse = UIColor(hex: 0x7FFF00) public static let chocolate = UIColor(hex: 0xD2691E) public static let coral = UIColor(hex: 0xFF7F50) public static let cornflowerBlue = UIColor(hex: 0x6495ED) public static let cornsilk = UIColor(hex: 0xFFF8DC) public static let crimson = UIColor(hex: 0xDC143C) public static let cyan = UIColor(hex: 0x00FFFF) public static let darkBlue = UIColor(hex: 0x00008B) public static let darkCyan = UIColor(hex: 0x008B8B) public static let darkGoldenRod = UIColor(hex: 0xB8860B) public static let darkGray = UIColor(hex: 0xA9A9A9) public static let darkGrey = UIColor(hex: 0xA9A9A9) public static let darkGreen = UIColor(hex: 0x006400) public static let darkKhaki = UIColor(hex: 0xBDB76B) public static let darkMagenta = UIColor(hex: 0x8B008B) public static let darkOliveGreen = UIColor(hex: 0x556B2F) public static let darkOrange = UIColor(hex: 0xFF8C00) public static let darkOrchid = UIColor(hex: 0x9932CC) public static let darkRed = UIColor(hex: 0x8B0000) public static let darkSalmon = UIColor(hex: 0xE9967A) public static let darkSeaGreen = UIColor(hex: 0x8FBC8F) public static let darkSlateBlue = UIColor(hex: 0x483D8B) public static let darkSlateGray = UIColor(hex: 0x2F4F4F) public static let darkSlateGrey = UIColor(hex: 0x2F4F4F) public static let darkTurquoise = UIColor(hex: 0x00CED1) public static let darkViolet = UIColor(hex: 0x9400D3) public static let deepPink = UIColor(hex: 0xFF1493) public static let deepSkyBlue = UIColor(hex: 0x00BFFF) public static let dimGray = UIColor(hex: 0x696969) public static let dimGrey = UIColor(hex: 0x696969) public static let dodgerBlue = UIColor(hex: 0x1E90FF) public static let fireBrick = UIColor(hex: 0xB22222) public static let floralWhite = UIColor(hex: 0xFFFAF0) public static let forestGreen = UIColor(hex: 0x228B22) public static let fuchsia = UIColor(hex: 0xFF00FF) public static let gainsboro = UIColor(hex: 0xDCDCDC) public static let ghostWhite = UIColor(hex: 0xF8F8FF) public static let gold = UIColor(hex: 0xFFD700) public static let goldenRod = UIColor(hex: 0xDAA520) public static let gray = UIColor(hex: 0x808080) public static let grey = UIColor(hex: 0x808080) public static let green = UIColor(hex: 0x008000) public static let greenYellow = UIColor(hex: 0xADFF2F) public static let honeyDew = UIColor(hex: 0xF0FFF0) public static let hotPink = UIColor(hex: 0xFF69B4) public static let indianRed = UIColor(hex: 0xCD5C5C) public static let indigo = UIColor(hex: 0x4B0082) public static let ivory = UIColor(hex: 0xFFFFF0) public static let khaki = UIColor(hex: 0xF0E68C) public static let lavender = UIColor(hex: 0xE6E6FA) public static let lavenderBlush = UIColor(hex: 0xFFF0F5) public static let lawnGreen = UIColor(hex: 0x7CFC00) public static let lemonChiffon = UIColor(hex: 0xFFFACD) public static let lightBlue = UIColor(hex: 0xADD8E6) public static let lightCoral = UIColor(hex: 0xF08080) public static let lightCyan = UIColor(hex: 0xE0FFFF) public static let lightGoldenRodYellow = UIColor(hex: 0xFAFAD2) public static let lightGray = UIColor(hex: 0xD3D3D3) public static let lightGrey = UIColor(hex: 0xD3D3D3) public static let lightGreen = UIColor(hex: 0x90EE90) public static let lightPink = UIColor(hex: 0xFFB6C1) public static let lightSalmon = UIColor(hex: 0xFFA07A) public static let lightSeaGreen = UIColor(hex: 0x20B2AA) public static let lightSkyBlue = UIColor(hex: 0x87CEFA) public static let lightSlateGray = UIColor(hex: 0x778899) public static let lightSlateGrey = UIColor(hex: 0x778899) public static let lightSteelBlue = UIColor(hex: 0xB0C4DE) public static let lightYellow = UIColor(hex: 0xFFFFE0) public static let lime = UIColor(hex: 0x00FF00) public static let limeGreen = UIColor(hex: 0x32CD32) public static let linen = UIColor(hex: 0xFAF0E6) public static let magenta = UIColor(hex: 0xFF00FF) public static let maroon = UIColor(hex: 0x800000) public static let mediumAquaMarine = UIColor(hex: 0x66CDAA) public static let mediumBlue = UIColor(hex: 0x0000CD) public static let mediumOrchid = UIColor(hex: 0xBA55D3) public static let mediumPurple = UIColor(hex: 0x9370DB) public static let mediumSeaGreen = UIColor(hex: 0x3CB371) public static let mediumSlateBlue = UIColor(hex: 0x7B68EE) public static let mediumSpringGreen = UIColor(hex: 0x00FA9A) public static let mediumTurquoise = UIColor(hex: 0x48D1CC) public static let mediumVioletRed = UIColor(hex: 0xC71585) public static let midnightBlue = UIColor(hex: 0x191970) public static let mintCream = UIColor(hex: 0xF5FFFA) public static let mistyRose = UIColor(hex: 0xFFE4E1) public static let moccasin = UIColor(hex: 0xFFE4B5) public static let navajoWhite = UIColor(hex: 0xFFDEAD) public static let navy = UIColor(hex: 0x000080) public static let oldLace = UIColor(hex: 0xFDF5E6) public static let olive = UIColor(hex: 0x808000) public static let oliveDrab = UIColor(hex: 0x6B8E23) public static let orange = UIColor(hex: 0xFFA500) public static let orangeRed = UIColor(hex: 0xFF4500) public static let orchid = UIColor(hex: 0xDA70D6) public static let paleGoldenRod = UIColor(hex: 0xEEE8AA) public static let paleGreen = UIColor(hex: 0x98FB98) public static let paleTurquoise = UIColor(hex: 0xAFEEEE) public static let paleVioletRed = UIColor(hex: 0xDB7093) public static let papayaWhip = UIColor(hex: 0xFFEFD5) public static let peachPuff = UIColor(hex: 0xFFDAB9) public static let peru = UIColor(hex: 0xCD853F) public static let pink = UIColor(hex: 0xFFC0CB) public static let plum = UIColor(hex: 0xDDA0DD) public static let powderBlue = UIColor(hex: 0xB0E0E6) public static let purple = UIColor(hex: 0x800080) public static let rebeccaPurple = UIColor(hex: 0x663399) public static let red = UIColor(hex: 0xFF0000) public static let rosyBrown = UIColor(hex: 0xBC8F8F) public static let royalBlue = UIColor(hex: 0x4169E1) public static let saddleBrown = UIColor(hex: 0x8B4513) public static let salmon = UIColor(hex: 0xFA8072) public static let sandyBrown = UIColor(hex: 0xF4A460) public static let seaGreen = UIColor(hex: 0x2E8B57) public static let seaShell = UIColor(hex: 0xFFF5EE) public static let sienna = UIColor(hex: 0xA0522D) public static let silver = UIColor(hex: 0xC0C0C0) public static let skyBlue = UIColor(hex: 0x87CEEB) public static let slateBlue = UIColor(hex: 0x6A5ACD) public static let slateGray = UIColor(hex: 0x708090) public static let slateGrey = UIColor(hex: 0x708090) public static let snow = UIColor(hex: 0xFFFAFA) public static let springGreen = UIColor(hex: 0x00FF7F) public static let steelBlue = UIColor(hex: 0x4682B4) public static let tan = UIColor(hex: 0xD2B48C) public static let teal = UIColor(hex: 0x008080) public static let thistle = UIColor(hex: 0xD8BFD8) public static let tomato = UIColor(hex: 0xFF6347) public static let turquoise = UIColor(hex: 0x40E0D0) public static let violet = UIColor(hex: 0xEE82EE) public static let wheat = UIColor(hex: 0xF5DEB3) public static let white = UIColor(hex: 0xFFFFFF) public static let whiteSmoke = UIColor(hex: 0xF5F5F5) public static let yellow = UIColor(hex: 0xFFFF00) public static let yellowGreen = UIColor(hex: 0x9ACD32) } } #endif
mit
e50f243fd7c8933cb0a3006d0155de33
45.605556
133
0.710335
2.976406
false
false
false
false
daviejaneway/OrbitFrontend
Sources/IdentifierRule.swift
1
1309
// // IdentifierRule.swift // OrbitFrontend // // Created by Davie Janeway on 07/09/2017. // // import Foundation import OrbitCompilerUtils public class IdentifierRule : ParseRule { public let name = "Orb.Core.Grammar.Identifier" public func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return token.type == .Identifier } public func parse(context: ParseContext) throws -> AbstractExpression { let id = try context.expect(type: .Identifier) return IdentifierExpression(value: id.value, startToken: id) } } public class OperatorRule : ParseRule { public let name = "Orb.Core.Grammar.Operator" private let position: OperatorPosition init(position: OperatorPosition) { self.position = position } public func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return token.type == .Operator } public func parse(context: ParseContext) throws -> AbstractExpression { let op = try context.expect(type: .Operator) return OperatorExpression(symbol: op.value, position: self.position, startToken: op) } }
mit
9222381d3a73dcf1f2a9da188dfb2c9e
27.456522
92
0.660046
4.25
false
false
false
false
hungrilla/meat
Meat/Menu.swift
2
923
// // Menu.swift // Meat // // Created by Umayr Shahid on 25/07/2015. // Copyright (c) 2015 Umayr Shahid. All rights reserved. // import Foundation public class Menu{ private var uuid: String private var restaurantId: String private var name: String private var description: String private var type: String private var serves: String private var price: String init(raw:AnyObject){ self.uuid = raw["uuid"] as! String self.restaurantId = raw["restaurantId"] as! String self.name = raw["name"] as! String self.description = raw["description"] as! String self.type = raw["type"] as! String self.serves = raw["serves"] as! String self.price = raw["price"] as! String } func getName() -> String{ return self.name } func getDescription() -> String{ return self.description ?? "N/A" } }
mit
78297f52cfc3c1bed328f4a504c95aba
23.972973
58
0.612134
3.92766
false
false
false
false
scinfu/SwiftSoup
Sources/HtmlTreeBuilder.swift
1
27195
// // HtmlTreeBuilder.swift // SwiftSoup // // Created by Nabil Chatbi on 24/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation /** * HTML Tree Builder; creates a DOM from Tokens. */ class HtmlTreeBuilder: TreeBuilder { private enum TagSets { // tag searches static let inScope = ["applet", "caption", "html", "table", "td", "th", "marquee", "object"] static let list = ["ol", "ul"] static let button = ["button"] static let tableScope = ["html", "table"] static let selectScope = ["optgroup", "option"] static let endTags = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"] static let titleTextarea = ["title", "textarea"] static let frames = ["iframe", "noembed", "noframes", "style", "xmp"] static let special: Set<String> = ["address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "command", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "marquee", "menu", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "style", "summary", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "title", "tr", "ul", "wbr", "xmp"] } private var _state: HtmlTreeBuilderState = HtmlTreeBuilderState.Initial // the current state private var _originalState: HtmlTreeBuilderState = HtmlTreeBuilderState.Initial // original / marked state private var baseUriSetFromDoc: Bool = false private var headElement: Element? // the current head element private var formElement: FormElement? // the current form element private var contextElement: Element? // fragment parse context -- could be null even if fragment parsing private var formattingElements: Array<Element?> = Array<Element?>() // active (open) formatting elements private var pendingTableCharacters: Array<String> = Array<String>() // chars in table to be shifted out private var emptyEnd: Token.EndTag = Token.EndTag() // reused empty end tag private var _framesetOk: Bool = true // if ok to go into frameset private var fosterInserts: Bool = false // if next inserts should be fostered private var fragmentParsing: Bool = false // if parsing a fragment of html public override init() { super.init() } public override func defaultSettings() -> ParseSettings { return ParseSettings.htmlDefault } override func parse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Document { _state = HtmlTreeBuilderState.Initial baseUriSetFromDoc = false return try super.parse(input, baseUri, errors, settings) } func parseFragment(_ inputFragment: String, _ context: Element?, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Array<Node> { // context may be null _state = HtmlTreeBuilderState.Initial initialiseParse(inputFragment, baseUri, errors, settings) contextElement = context fragmentParsing = true var root: Element? = nil if let context = context { if let d = context.ownerDocument() { // quirks setup: doc.quirksMode(d.quirksMode()) } // initialise the tokeniser state: switch context.tagName() { case TagSets.titleTextarea: tokeniser.transition(TokeniserState.Rcdata) case TagSets.frames: tokeniser.transition(TokeniserState.Rawtext) case "script": tokeniser.transition(TokeniserState.ScriptData) case "noscript": tokeniser.transition(TokeniserState.Data) // if scripting enabled, rawtext case "plaintext": tokeniser.transition(TokeniserState.Data) default: tokeniser.transition(TokeniserState.Data) } root = try Element(Tag.valueOf("html", settings), baseUri) try Validate.notNull(obj: root) try doc.appendChild(root!) stack.append(root!) resetInsertionMode() // setup form element to nearest form on context (up ancestor chain). ensures form controls are associated // with form correctly let contextChain: Elements = context.parents() contextChain.add(0, context) for parent: Element in contextChain.array() { if let x = (parent as? FormElement) { formElement = x break } } } try runParser() if (context != nil && root != nil) { return root!.getChildNodes() } else { return doc.getChildNodes() } } @discardableResult public override func process(_ token: Token)throws->Bool { currentToken = token return try self._state.process(token, self) } @discardableResult func process(_ token: Token, _ state: HtmlTreeBuilderState)throws->Bool { currentToken = token return try state.process(token, self) } func transition(_ state: HtmlTreeBuilderState) { self._state = state } func state() -> HtmlTreeBuilderState { return _state } func markInsertionMode() { _originalState = _state } func originalState() -> HtmlTreeBuilderState { return _originalState } func framesetOk(_ framesetOk: Bool) { self._framesetOk = framesetOk } func framesetOk() -> Bool { return _framesetOk } func getDocument() -> Document { return doc } func getBaseUri() -> String { return baseUri } func maybeSetBaseUri(_ base: Element)throws { if (baseUriSetFromDoc) { // only listen to the first <base href> in parse return } let href: String = try base.absUrl("href") if (href.count != 0) { // ignore <base target> etc baseUri = href baseUriSetFromDoc = true try doc.setBaseUri(href) // set on the doc so doc.createElement(Tag) will get updated base, and to update all descendants } } func isFragmentParsing() -> Bool { return fragmentParsing } func error(_ state: HtmlTreeBuilderState) { if (errors.canAddError() && currentToken != nil) { errors.add(ParseError(reader.getPos(), "Unexpected token [\(currentToken!.tokenType())] when in state [\(state.rawValue)]")) } } @discardableResult func insert(_ startTag: Token.StartTag)throws->Element { // handle empty unknown tags // when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag. if (startTag.isSelfClosing()) { let el: Element = try insertEmpty(startTag) stack.append(el) tokeniser.transition(TokeniserState.Data) // handles <script />, otherwise needs breakout steps from script data try tokeniser.emit(emptyEnd.reset().name(el.tagName())) // ensure we get out of whatever state we are in. emitted for yielded processing return el } try Validate.notNull(obj: startTag._attributes) let el: Element = try Element(Tag.valueOf(startTag.name(), settings), baseUri, settings.normalizeAttributes(startTag._attributes)) try insert(el) return el } @discardableResult func insertStartTag(_ startTagName: String)throws->Element { let el: Element = try Element(Tag.valueOf(startTagName, settings), baseUri) try insert(el) return el } func insert(_ el: Element)throws { try insertNode(el) stack.append(el) } @discardableResult func insertEmpty(_ startTag: Token.StartTag)throws->Element { let tag: Tag = try Tag.valueOf(startTag.name(), settings) try Validate.notNull(obj: startTag._attributes) let el: Element = Element(tag, baseUri, startTag._attributes) try insertNode(el) if (startTag.isSelfClosing()) { if (tag.isKnownTag()) { if (tag.isSelfClosing()) {tokeniser.acknowledgeSelfClosingFlag()} // if not acked, promulagates error } else { // unknown tag, remember this is self closing for output tag.setSelfClosing() tokeniser.acknowledgeSelfClosingFlag() // not an distinct error } } return el } @discardableResult func insertForm(_ startTag: Token.StartTag, _ onStack: Bool)throws->FormElement { let tag: Tag = try Tag.valueOf(startTag.name(), settings) try Validate.notNull(obj: startTag._attributes) let el: FormElement = FormElement(tag, baseUri, startTag._attributes) setFormElement(el) try insertNode(el) if (onStack) { stack.append(el) } return el } func insert(_ commentToken: Token.Comment)throws { let comment: Comment = Comment(commentToken.getData(), baseUri) try insertNode(comment) } func insert(_ characterToken: Token.Char)throws { var node: Node // characters in script and style go in as datanodes, not text nodes let tagName: String? = currentElement()?.tagName() if (tagName=="script" || tagName=="style") { try Validate.notNull(obj: characterToken.getData()) node = DataNode(characterToken.getData()!, baseUri) } else { try Validate.notNull(obj: characterToken.getData()) node = TextNode(characterToken.getData()!, baseUri) } try currentElement()?.appendChild(node) // doesn't use insertNode, because we don't foster these; and will always have a stack. } private func insertNode(_ node: Node)throws { // if the stack hasn't been set up yet, elements (doctype, comments) go into the doc if (stack.count == 0) { try doc.appendChild(node) } else if (isFosterInserts()) { try insertInFosterParent(node) } else { try currentElement()?.appendChild(node) } // connect form controls to their form element if let n = (node as? Element) { if(n.tag().isFormListed()) { if ( formElement != nil) { formElement!.addElement(n) } } } } @discardableResult func pop() -> Element { let size: Int = stack.count return stack.remove(at: size-1) } func push(_ element: Element) { stack.append(element) } func getStack()->Array<Element> { return stack } @discardableResult func onStack(_ el: Element) -> Bool { return isElementInQueue(stack, el) } private func isElementInQueue(_ queue: Array<Element?>, _ element: Element?) -> Bool { for pos in (0..<queue.count).reversed() { let next: Element? = queue[pos] if (next == element) { return true } } return false } func getFromStack(_ elName: String) -> Element? { for pos in (0..<stack.count).reversed() { let next: Element = stack[pos] if next.nodeName() == elName { return next } } return nil } @discardableResult func removeFromStack(_ el: Element) -> Bool { for pos in (0..<stack.count).reversed() { let next: Element = stack[pos] if (next == el) { stack.remove(at: pos) return true } } return false } func popStackToClose(_ elName: String) { for pos in (0..<stack.count).reversed() { let next: Element = stack[pos] stack.remove(at: pos) if (next.nodeName() == elName) { break } } } func popStackToClose(_ elNames: String...) { popStackToClose(elNames) } func popStackToClose(_ elNames: [String]) { for pos in (0..<stack.count).reversed() { let next: Element = stack[pos] stack.remove(at: pos) if elNames.contains(next.nodeName()) { break } } } func popStackToBefore(_ elName: String) { for pos in (0..<stack.count).reversed() { let next: Element = stack[pos] if (next.nodeName() == elName) { break } else { stack.remove(at: pos) } } } func clearStackToTableContext() { clearStackToContext("table") } func clearStackToTableBodyContext() { clearStackToContext("tbody", "tfoot", "thead") } func clearStackToTableRowContext() { clearStackToContext("tr") } private func clearStackToContext(_ nodeNames: String...) { clearStackToContext(nodeNames) } private func clearStackToContext(_ nodeNames: [String]) { for pos in (0..<stack.count).reversed() { let next: Element = stack[pos] let nextName = next.nodeName() if nodeNames.contains(nextName) || nextName == "html" { break } else { stack.remove(at: pos) } } } func aboveOnStack(_ el: Element) -> Element? { //assert(onStack(el), "Invalid parameter") onStack(el) for pos in (0..<stack.count).reversed() { let next: Element = stack[pos] if (next == el) { return stack[pos-1] } } return nil } func insertOnStackAfter(_ after: Element, _ input: Element)throws { let i: Int = stack.lastIndexOf(after) try Validate.isTrue(val: i != -1) stack.insert(input, at: i + 1 ) } func replaceOnStack(_ out: Element, _ input: Element)throws { try stack = replaceInQueue(stack, out, input) } private func replaceInQueue(_ queue: Array<Element>, _ out: Element, _ input: Element)throws->Array<Element> { var queue = queue let i: Int = queue.lastIndexOf(out) try Validate.isTrue(val: i != -1) queue[i] = input return queue } private func replaceInQueue(_ queue: Array<Element?>, _ out: Element, _ input: Element)throws->Array<Element?> { var queue = queue var i: Int = -1 for index in 0..<queue.count { if(out == queue[index]) { i = index } } try Validate.isTrue(val: i != -1) queue[i] = input return queue } func resetInsertionMode() { var last = false for pos in (0..<stack.count).reversed() { var node: Element = stack[pos] if (pos == 0) { last = true //Validate node node = contextElement! } let name: String = node.nodeName() if ("select".equals(name)) { transition(HtmlTreeBuilderState.InSelect) break // frag } else if (("td".equals(name) || "th".equals(name) && !last)) { transition(HtmlTreeBuilderState.InCell) break } else if ("tr".equals(name)) { transition(HtmlTreeBuilderState.InRow) break } else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) { transition(HtmlTreeBuilderState.InTableBody) break } else if ("caption".equals(name)) { transition(HtmlTreeBuilderState.InCaption) break } else if ("colgroup".equals(name)) { transition(HtmlTreeBuilderState.InColumnGroup) break // frag } else if ("table".equals(name)) { transition(HtmlTreeBuilderState.InTable) break } else if ("head".equals(name)) { transition(HtmlTreeBuilderState.InBody) break // frag } else if ("body".equals(name)) { transition(HtmlTreeBuilderState.InBody) break } else if ("frameset".equals(name)) { transition(HtmlTreeBuilderState.InFrameset) break // frag } else if ("html".equals(name)) { transition(HtmlTreeBuilderState.BeforeHead) break // frag } else if (last) { transition(HtmlTreeBuilderState.InBody) break // frag } } } private func inSpecificScope(_ targetName: String, _ baseTypes: [String], _ extraTypes: [String]? = nil)throws->Bool { return try inSpecificScope([targetName], baseTypes, extraTypes) } private func inSpecificScope(_ targetNames: [String], _ baseTypes: [String], _ extraTypes: [String]? = nil)throws->Bool { for pos in (0..<stack.count).reversed() { let el = stack[pos] let elName = el.nodeName() if targetNames.contains(elName) { return true } if baseTypes.contains(elName) { return false } if let extraTypes = extraTypes, extraTypes.contains(elName) { return false } } try Validate.fail(msg: "Should not be reachable") return false } func inScope(_ targetNames: [String])throws->Bool { return try inSpecificScope(targetNames, TagSets.inScope) } func inScope(_ targetName: String, _ extras: [String]? = nil)throws->Bool { return try inSpecificScope(targetName, TagSets.inScope, extras) // todo: in mathml namespace: mi, mo, mn, ms, mtext annotation-xml // todo: in svg namespace: forignOjbect, desc, title } func inListItemScope(_ targetName: String)throws->Bool { return try inScope(targetName, TagSets.list) } func inButtonScope(_ targetName: String)throws->Bool { return try inScope(targetName, TagSets.button) } func inTableScope(_ targetName: String)throws->Bool { return try inSpecificScope(targetName, TagSets.tableScope) } func inSelectScope(_ targetName: String)throws->Bool { for pos in (0..<stack.count).reversed() { let elName = stack[pos].nodeName() if elName == targetName { return true } if !TagSets.selectScope.contains(elName) { return false } } try Validate.fail(msg: "Should not be reachable") return false } func setHeadElement(_ headElement: Element) { self.headElement = headElement } func getHeadElement() -> Element? { return headElement } func isFosterInserts() -> Bool { return fosterInserts } func setFosterInserts(_ fosterInserts: Bool) { self.fosterInserts = fosterInserts } func getFormElement() -> FormElement? { return formElement } func setFormElement(_ formElement: FormElement?) { self.formElement = formElement } func newPendingTableCharacters() { pendingTableCharacters = Array<String>() } func getPendingTableCharacters()->Array<String> { return pendingTableCharacters } func setPendingTableCharacters(_ pendingTableCharacters: Array<String>) { self.pendingTableCharacters = pendingTableCharacters } /** 11.2.5.2 Closing elements that have implied end tags<p/> When the steps below require the UA to generate implied end tags, then, while the current node is a dd element, a dt element, an li element, an option element, an optgroup element, a p element, an rp element, or an rt element, the UA must pop the current node off the stack of open elements. @param excludeTag If a step requires the UA to generate implied end tags but lists an element to exclude from the process, then the UA must perform the above steps as if that element was not in the above list. */ func generateImpliedEndTags(_ excludeTag: String? = nil) { // Is this correct? I get the sense that something is supposed to happen here // even if excludeTag == nil. But the original code doesn't seem to do that. -GS // // while ((excludeTag != nil && !currentElement()!.nodeName().equals(excludeTag!)) && // StringUtil.inString(currentElement()!.nodeName(), HtmlTreeBuilder.TagSearchEndTags)) { // pop() // } guard let excludeTag = excludeTag else { return } while true { let nodeName = currentElement()!.nodeName() guard nodeName != excludeTag else { return } guard TagSets.endTags.contains(nodeName) else { return } pop() } } func isSpecial(_ el: Element) -> Bool { // todo: mathml's mi, mo, mn // todo: svg's foreigObject, desc, title let name: String = el.nodeName() return TagSets.special.contains(name) } func lastFormattingElement() -> Element? { return formattingElements.count > 0 ? formattingElements[formattingElements.count-1] : nil } func removeLastFormattingElement() -> Element? { let size: Int = formattingElements.count if (size > 0) { return formattingElements.remove(at: size-1) } else { return nil } } // active formatting elements func pushActiveFormattingElements(_ input: Element) { var numSeen: Int = 0 for pos in (0..<formattingElements.count).reversed() { let el: Element? = formattingElements[pos] if (el == nil) { // marker break } if (isSameFormattingElement(input, el!)) { numSeen += 1 } if (numSeen == 3) { formattingElements.remove(at: pos) break } } formattingElements.append(input) } private func isSameFormattingElement(_ a: Element, _ b: Element) -> Bool { // same if: same namespace, tag, and attributes. Element.equals only checks tag, might in future check children if(a.attributes == nil) { return false } return a.nodeName().equals(b.nodeName()) && // a.namespace().equals(b.namespace()) && a.getAttributes()!.equals(o: b.getAttributes()) // todo: namespaces } func reconstructFormattingElements()throws { let last: Element? = lastFormattingElement() if (last == nil || onStack(last!)) { return } var entry: Element? = last let size: Int = formattingElements.count var pos: Int = size - 1 var skip: Bool = false while (true) { if (pos == 0) { // step 4. if none before, skip to 8 skip = true break } pos -= 1 entry = formattingElements[pos] // step 5. one earlier than entry if (entry == nil || onStack(entry!)) // step 6 - neither marker nor on stack {break} // jump to 8, else continue back to 4 } while(true) { if (!skip) // step 7: on later than entry { pos += 1 entry = formattingElements[pos] } try Validate.notNull(obj: entry) // should not occur, as we break at last element // 8. create new element from element, 9 insert into current node, onto stack skip = false // can only skip increment from 4. let newEl: Element = try insertStartTag(entry!.nodeName()) // todo: avoid fostering here? // newEl.namespace(entry.namespace()) // todo: namespaces newEl.getAttributes()?.addAll(incoming: entry!.getAttributes()) // 10. replace entry with new entry formattingElements[pos] = newEl // 11 if (pos == size-1) // if not last entry in list, jump to 7 {break} } } func clearFormattingElementsToLastMarker() { while (!formattingElements.isEmpty) { let el: Element? = removeLastFormattingElement() if (el == nil) { break } } } func removeFromActiveFormattingElements(_ el: Element?) { for pos in (0..<formattingElements.count).reversed() { let next: Element? = formattingElements[pos] if (next == el) { formattingElements.remove(at: pos) break } } } func isInActiveFormattingElements(_ el: Element) -> Bool { return isElementInQueue(formattingElements, el) } func getActiveFormattingElement(_ nodeName: String) -> Element? { for pos in (0..<formattingElements.count).reversed() { let next: Element? = formattingElements[pos] if (next == nil) { // scope marker break } else if (next!.nodeName().equals(nodeName)) { return next } } return nil } func replaceActiveFormattingElement(_ out: Element, _ input: Element)throws { try formattingElements = replaceInQueue(formattingElements, out, input) } func insertMarkerToFormattingElements() { formattingElements.append(nil) } func insertInFosterParent(_ input: Node)throws { let fosterParent: Element? let lastTable: Element? = getFromStack("table") var isLastTableParent: Bool = false if let lastTable = lastTable { if (lastTable.parent() != nil) { fosterParent = lastTable.parent()! isLastTableParent = true } else { fosterParent = aboveOnStack(lastTable) } } else { // no table == frag fosterParent = stack[0] } if (isLastTableParent) { try Validate.notNull(obj: lastTable) // last table cannot be null by this point. try lastTable!.before(input) } else { try fosterParent?.appendChild(input) } } } fileprivate func ~= (pattern: [String], value: String) -> Bool { return pattern.contains(value) }
mit
20ee44722409d8c76608aa2f52e32102
33.819462
161
0.568912
4.656507
false
false
false
false
zoeyzhong520/SlidingMenu
SlidingMenu/SlidingMenu/SlidingMenuKit/Controller/CreateImaginationViewController.swift
1
11277
// // CreateImaginationViewController.swift // SlidingMenu // // Created by JOE on 2017/10/12. // Copyright © 2017年 Hongyear Information Technology (Shanghai) Co.,Ltd. All rights reserved. // import UIKit ///CreateImaginationType, default is create with no selected content. enum CreateImaginationType: Int { case WithNoSelectedContent = 0 case WithSelectedContent } class CreateImaginationViewController: UIViewController { fileprivate var createImaginationType:CreateImaginationType? var model:CreateImaginationModel? ///Create imaginationTextView fileprivate var imaginationTextView:UITextView! ///ImaginationTextViewHeight fileprivate var ImaginationTextViewHeight = fontSizeScale(200) ///PlaceHolderLabel fileprivate var placeHolderLabel:UILabel? ///ContentLabel fileprivate var contentLabel:UILabel! ///bottomMenuView fileprivate var bottomMenuView:UIView! override func viewDidLoad() { super.viewDidLoad() createView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK: - UI extension CreateImaginationViewController { ///UI fileprivate func createView() { view.backgroundColor = UIColor.white //Exit 退出. let exitBtn = UIButton() exitBtn.setTitle("⬅︎", for: .normal) exitBtn.setTitleColor(UIColor.black, for: .normal) exitBtn.addTarget(self, action: #selector(exit), for: .touchUpInside) view.addSubview(exitBtn) exitBtn.snp.makeConstraints { (make) in make.top.equalTo(self.view).offset(fontSizeScale(20)) make.left.equalTo(self.view) make.width.height.equalTo(tabbarHeight) } //Line View. let lineViewOne = UIView() lineViewOne.backgroundColor = UIColor.lightGray view.addSubview(lineViewOne) lineViewOne.snp.makeConstraints { (make) in make.top.equalTo(exitBtn.snp.bottom) make.left.right.equalTo(self.view) make.height.equalTo(fontSizeScale(1)) } //ImaginationTextView imaginationTextView = UITextView(backgroundColor: UIColor.white, textAlignment: .left, textColor: UIColor.black, font: zzj_SystemFontWithSize(13), isEditable: true, isScrollEnabled: true, isUserInteractionEnabled: true) imaginationTextView.delegate = self imaginationTextView.becomeFirstResponder() view.addSubview(imaginationTextView) imaginationTextView.snp.makeConstraints { (make) in make.top.equalTo(lineViewOne.snp.bottom) make.left.right.equalTo(self.view) make.height.equalTo(ImaginationTextViewHeight) } //placeHolder let placeHolderLabel = UILabel(text: "写下你这一刻的想法", font: zzj_SystemFontWithSize(13), textColor: RGB(218, 218, 218), textAlignment: .left) if imaginationTextView.text.isEmpty == false { placeHolderLabel.isHidden = true } imaginationTextView.addSubview(placeHolderLabel) self.placeHolderLabel = placeHolderLabel placeHolderLabel.snp.makeConstraints { (make) in make.left.top.equalTo(imaginationTextView).offset((fontSizeScale(12))) make.right.equalTo(imaginationTextView) } //LineViewTwo. let lineViewTwo = UIView() lineViewTwo.backgroundColor = UIColor.lightGray view.addSubview(lineViewTwo) lineViewTwo.snp.makeConstraints { (make) in make.top.equalTo(imaginationTextView.snp.bottom) make.height.equalTo(fontSizeScale(1)) make.left.right.equalTo(self.view) } setupContentLabel() setupQuoteLabel() setupBottomMenuView() } ///Setup ContentLabel. fileprivate func setupContentLabel() { let contentLabel = UILabel() contentLabel.text = model?.selectedContent contentLabel.font = zzj_SystemFontWithSize(13) contentLabel.textColor = UIColor.lightGray contentLabel.textAlignment = .left contentLabel.numberOfLines = 2 view.addSubview(contentLabel) self.contentLabel = contentLabel contentLabel.snp.makeConstraints { (make) in if self.model == nil { make.top.equalTo(imaginationTextView.snp.bottom).offset(fontSizeScale(1)) }else if self.model?.selectedContent?.isEmpty == false { make.top.equalTo(imaginationTextView.snp.bottom).offset(fontSizeScale(6)) }else{ make.top.equalTo(imaginationTextView.snp.bottom).offset(fontSizeScale(1)) } make.left.equalTo(self.view).offset(fontSizeScale(10)) make.right.equalTo(self.view).offset(-fontSizeScale(10)) let height = UILabel.getHeightByWidth(title: contentLabel.text, width: view.bounds.size.width - fontSizeScale(20), font: zzj_SystemFontWithSize(13)) print(height) if height >= 47.0 { make.height.equalTo(47.0) }else{ make.height.equalTo(height) } } } ///Setup quoteLabel. fileprivate func setupQuoteLabel() { let lineView = UIView() lineView.backgroundColor = UIColor.lightGray view.addSubview(lineView) lineView.snp.makeConstraints { (make) in if self.model == nil { make.top.equalTo(self.contentLabel.snp.bottom) lineView.backgroundColor = UIColor.clear }else if self.model?.bookName?.isEmpty == false { make.top.equalTo(self.contentLabel.snp.bottom).offset(fontSizeScale(5)) }else{ make.top.equalTo(self.contentLabel.snp.bottom) lineView.backgroundColor = UIColor.clear } make.left.right.equalTo(self.view) make.height.equalTo(fontSizeScale(1)) } let quoteLabel = UILabel() if self.model == nil { quoteLabel.text = "引自" }else if self.model?.bookName?.isEmpty == false { guard let bookName = model?.bookName else { return } quoteLabel.text = "引自" + " " + bookName }else{ quoteLabel.text = "引自" } quoteLabel.textColor = UIColor.gray quoteLabel.font = zzj_SystemFontWithSize(14) quoteLabel.textAlignment = .left view.addSubview(quoteLabel) quoteLabel.snp.makeConstraints { (make) in make.left.equalTo(self.view).offset(fontSizeScale(10)) make.right.equalTo(self.view).offset(-fontSizeScale(10)) make.height.equalTo(fontSizeScale(14)) make.top.equalTo(lineView.snp.bottom).offset(fontSizeScale(10)) } } @objc fileprivate func exit() { self.imaginationTextView.resignFirstResponder() dismiss() } ///Setup bottomMenuView. fileprivate func setupBottomMenuView() { bottomMenuView = UIView() bottomMenuView.backgroundColor = UIColor.white view.addSubview(bottomMenuView) bottomMenuView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self.view) make.height.equalTo(tabbarHeight) } ///Line view. let lineView = UIView() lineView.backgroundColor = UIColor.lightGray bottomMenuView.addSubview(lineView) lineView.snp.makeConstraints { (make) in make.left.right.top.equalTo(bottomMenuView) make.height.equalTo(fontSizeScale(1)) } ///Close btn. let closeBtn = UIButton() closeBtn.setTitle("×", for: .normal) closeBtn.setTitleColor(UIColor.black, for: .normal) closeBtn.tag = 100 closeBtn.addTarget(self, action: #selector(bottomMenuViewClick(btn:)), for: .touchUpInside) bottomMenuView.addSubview(closeBtn) closeBtn.snp.makeConstraints { (make) in make.centerY.equalTo(bottomMenuView) make.left.equalTo(bottomMenuView).offset(fontSizeScale(10)) make.width.height.equalTo(navigationBarHeight) } ///Reaease btn. let releaseBtn = UIButton() releaseBtn.setTitle("发布", for: .normal) releaseBtn.setTitleColor(UIColor.black, for: .normal) releaseBtn.tag = 101 releaseBtn.addTarget(self, action: #selector(bottomMenuViewClick(btn:)), for: .touchUpInside) bottomMenuView.addSubview(releaseBtn) releaseBtn.snp.makeConstraints { (make) in make.center.equalTo(bottomMenuView) make.width.height.equalTo(navigationBarHeight) } ///Confirm btn. let confirmBtn = UIButton() confirmBtn.setTitle("√", for: .normal) confirmBtn.setTitleColor(UIColor.black, for: .normal) confirmBtn.tag = 102 confirmBtn.addTarget(self, action: #selector(bottomMenuViewClick(btn:)), for: .touchUpInside) bottomMenuView.addSubview(confirmBtn) confirmBtn.snp.makeConstraints { (make) in make.centerY.equalTo(bottomMenuView) make.right.equalTo(bottomMenuView).offset(-fontSizeScale(10)) make.width.height.equalTo(navigationBarHeight) } } @objc fileprivate func bottomMenuViewClick(btn: UIButton) { if btn.tag == 100 { setupAlertController() }else if btn.tag == 101 { dismiss() }else if btn.tag == 102 { dismiss() } } ///Setup AlertController. fileprivate func setupAlertController() { let alertCtrl = UIAlertController(title: "提示", message: "确定退出编辑吗?", preferredStyle: .alert) alertCtrl.addAction(UIAlertAction(title: "是", style: .default, handler: { (action) in self.dismiss() })) alertCtrl.addAction(UIAlertAction(title: "否", style: .default, handler: nil)) self.present(alertCtrl, animated: true, completion: nil) } ///Dissmiss void. fileprivate func dismiss() { self.dismiss(animated: true, completion: nil) } } //MARK: - UITextViewDelegate extension CreateImaginationViewController: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { placeHolderLabel?.isHidden = true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { // 回车时退出编辑 if text == "\n" { textView.resignFirstResponder() return true } return true } func textViewDidEndEditing(_ textView: UITextView) { if textView.text.isEmpty { placeHolderLabel?.isHidden = false }else{ placeHolderLabel?.isHidden = true } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } }
mit
459a9671f97db8a484eae0e2372826d5
34.86859
227
0.628809
4.93648
false
false
false
false
theadam/SwiftClient
Sources/Constants.swift
1
3598
// // Constants.swift // SwiftClient // // Created by Adam Nalisnick on 10/30/14. // Copyright (c) 2014 Adam Nalisnick. All rights reserved. // import Foundation internal func base64Encode(string:String) -> String { return dataToString(data: stringToData(string: string).base64EncodedData(options: [])) } internal func uriDecode(string:String) -> String{ return string.removingPercentEncoding! } internal func uriEncode(string:Any) -> String{ let allowedCharacters = CharacterSet(charactersIn:" \"#%/<>?@\\^`{}[]|&+").inverted return (string as AnyObject).addingPercentEncoding(withAllowedCharacters: allowedCharacters)! } internal func stringToData(string:String) -> Data { return string.data(using: String.Encoding.utf8, allowLossyConversion: true)! } internal func dataToString(data:Data) -> String { return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String } internal func queryPair(key:String, value:Any) -> String{ return uriEncode(string: key) + "=" + uriEncode(string: value) } internal func queryString(query:Any) -> String?{ var pairs:[String]? if let dict = query as? Dictionary<String, Any> { pairs = Array() for (key, value) in dict { pairs!.append(queryPair(key: key, value: value)) } } else if let array = query as? [String] { pairs = array } if let pairs = pairs { return pairs.joined(separator: "&") } return nil } // PARSERS private func parseJson(data:Data, string: String) -> Any?{ do { return try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) } catch { print(error) } return nil; } private func parseForm(data:Data, string:String) -> Any?{ let pairs = string.components(separatedBy: "&") var form:[String : String] = Dictionary() for pair in pairs { let parts = pair.components(separatedBy: "=") form[uriDecode(string: parts[0])] = uriDecode(string: parts[1]) } return form } //SERIALIZERS private func serializeJson(data:Any) -> Data? { if let arrayData = data as? NSArray { do { return try JSONSerialization.data(withJSONObject: arrayData, options: JSONSerialization.WritingOptions()) } catch { print(error) } } if let dictionaryData = data as? NSDictionary { do { return try JSONSerialization.data(withJSONObject: dictionaryData, options: JSONSerialization.WritingOptions()) } catch { print(error) } } if let dataString = data as? String{ return stringToData(string: dataString) } return nil } private func serializeForm(data:Any) -> Data? { if let queryString = queryString(query: data) { return stringToData(string: queryString) } else if let dataString = (data as? String ?? String(describing: data)) as String? { return stringToData(string: dataString) } return nil } internal let types = [ "html": "text/html", "json": "application/json", "xml": "application/xml", "urlencoded": "application/x-www-form-urlencoded", "form": "application/x-www-form-urlencoded", "form-data": "application/x-www-form-urlencoded", "text": "text/plain" ] internal let serializers = [ "application/x-www-form-urlencoded": serializeForm, "application/json": serializeJson ] internal let parsers = [ "application/x-www-form-urlencoded": parseForm, "application/json": parseJson ]
mit
13c464d9b846c4ccb94d26ccb634dc10
25.850746
122
0.648972
4.047244
false
false
false
false
huangboju/Moots
Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Features/Comments/CommentViewModel.swift
1
1185
// // CommentViewModel.swift // RedditOs // // Created by Thomas Ricouard on 12/08/2020. // import Foundation import SwiftUI import Combine import Backend class CommentViewModel: ObservableObject { @Published var comment: Comment private var cancellableStore: [AnyCancellable] = [] init(comment: Comment) { self.comment = comment } func postVote(vote: Vote) { let oldValue = comment.likes let cancellable = comment.vote(vote: vote) .receive(on: DispatchQueue.main) .sink{ [weak self] response in if response.error != nil { self?.comment.likes = oldValue } } cancellableStore.append(cancellable) } func toggleSave() { let oldValue = comment.saved let cancellable = (comment.saved == true ? comment.unsave() : comment.save()) .receive(on: DispatchQueue.main) .sink{ [weak self] response in if response.error != nil { self?.comment.saved = oldValue } } cancellableStore.append(cancellable) } }
mit
a8bc6c4f0d089d2779fcd52ff22bd586
24.76087
85
0.564557
4.702381
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/ViewController.swift
1
5861
// // ViewController.swift // RunTime // // Created by 伯驹 黄 on 2016/10/19. // Copyright © 2016年 伯驹 黄. All rights reserved. // import UIKit class ViewController: UIViewController { fileprivate lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.frame, style: .grouped) tableView.dataSource = self tableView.delegate = self return tableView }() lazy var data: [[UIViewController.Type]] = [ [ FriendTableViewController.self, PagingEnabled.self, InfiniteScrollViewController.self, ScrollViewController.self, PagingSecondController.self, ConvertController.self, AutoLayoutController.self, CollectionViewSelfSizing.self, TableViewSelfsizing.self, LayoutTrasition.self, ExpandingCollectionViewController.self, ], [ RulerControllerWithScrollView.self, RulerController.self, RulerControllerWithLayout.self ], [ CardViewController.self ], [ BubbleViewController.self, ResizableImageVC.self, TableNestCollectionController.self ], [ MaskShapeLayerVC.self, MaskViewVC.self ], [ BlurController.self ], [ WindowVC.self ], [ GestureVC.self, GestureButtonViewController.self ], [ AlertController.self ], [ VisionMenuVC.self ], [ DiffableDatasourceMenuVC.self ] ] override func viewDidLoad() { super.viewDidLoad() title = "UIScrollView" let bannerView = BannerView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 130)) bannerView.set(content: ["", "", "", ""]) bannerView.pageStepTime = 1 bannerView.handleBack = { print($0) } tableView.tableHeaderView = bannerView let subView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") view.addSubview(tableView) print(subView.isDescendant(of: view)) let array = NSArray(objects: "2.0", "2.3", "3.0", "4.0", "10") guard let sum = array.value(forKeyPath: "@sum.floatValue"), let avg = array.value(forKeyPath: "@avg.floatValue"), let max = array.value(forKeyPath: "@max.floatValue"), let min = array.value(forKeyPath: "@min.floatValue") else { return } print(sum, avg, max, min) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return data.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.textLabel?.text = "\(data[indexPath.section][indexPath.row].classForCoder())" } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let controllerName = "\(data[indexPath.section][indexPath.row].classForCoder())" if let controller = controllerName.fromClassName() as? UIViewController { controller.title = controllerName controller.hidesBottomBarWhenPushed = true navigationController?.pushViewController(controller, animated: true) } } } extension String { func fromClassName() -> NSObject { let className = Bundle.main.infoDictionary!["CFBundleName"] as! String + "." + self let aClass = NSClassFromString(className) as! UIViewController.Type return aClass.init() } } extension UIView { // var viewController: UIViewController? { // var viewController: UIViewController? // var next = self.next // while next != nil { // if next!.isKind(of: UIViewController.self) { // viewController = next as? UIViewController // break // } // next = next?.next // } // return viewController // } public func viewController<T: UIViewController>() -> T? { var viewController: UIViewController? var next = self.next while let _next = next { if _next.isKind(of: UIViewController.self) { viewController = next as? UIViewController break } next = _next.next } return viewController as? T } var safeAreaBottom: CGFloat { if #available(iOS 11, *) { if let window = UIApplication.shared.keyWindowInConnectedScenes { return window.safeAreaInsets.bottom } } return 0 } var safeAreaTop: CGFloat { if #available(iOS 11, *) { if let window = UIApplication.shared.keyWindowInConnectedScenes { return window.safeAreaInsets.top } } return 0 } }
mit
ee6cf2126c9dd3532ca6bc0845477833
28.675127
112
0.582278
5.101222
false
false
false
false
zhuxietong/Eelay
Sources/Eelay/object/Collection+mutable.swift
1
3713
// // NSArray-Array.swift // app // // Created by tong on 16/6/1. // Copyright © 2016年 zhuxietong. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #endif public protocol NSJsonObj { func jsonObj<T>() -> T? } public protocol NSJsonSerial:NSJsonObj{ associatedtype NSJson var nsjson:NSJson{get} } extension Array:NSJsonSerial{ public func jsonObj<T>() -> T? { return nsjson as? T } public typealias NSJson = NSMutableArray public var nsjson: NSJson{ get{ return self.mutable_array } } } extension Dictionary:NSJsonSerial{ public func jsonObj<T>() -> T? { return nsjson as? T } public typealias NSJson = NSMutableDictionary public var nsjson: NSJson{ get{ return self.mutable_dictionary } } } extension NSDictionary:NSJsonSerial{ public func jsonObj<T>() -> T? { return nsjson as? T } public typealias NSJson = NSMutableDictionary public var nsjson: NSJson{ get{ return self.mutable_dictionary } } } extension NSArray:NSJsonSerial{ public func jsonObj<T>() -> T? { return nsjson as? T } public typealias NSJson = NSMutableArray public var nsjson: NSJson{ get{ return self.mutable_array } } } public extension Array { var mutable_array:NSMutableArray { return (self as NSArray).mutable_array } } public extension Dictionary { var mutable_dictionary:NSMutableDictionary { return (self as NSDictionary).mutable_dictionary } } public extension NSArray { var mutable_array:NSMutableArray{ let mutable_a = NSMutableArray() for v in self { switch v { case let dic as NSDictionary: mutable_a.add(dic.mutable_dictionary);break case let arr as NSArray: mutable_a.add(arr.mutable_array);break case let str as String: mutable_a.add(str);break case let int as Int64: mutable_a.add(int);break case let int as Int32: mutable_a.add(int);break case let int as Int: mutable_a.add(int);break case let flt as Float: mutable_a.add(flt);break case let dbl as Double: mutable_a.add(dbl);break case let cgf as CGFloat: mutable_a.add(cgf);break default: mutable_a.add(v) } } return mutable_a } } public extension NSDictionary { var mutable_dictionary:NSMutableDictionary { let mutable_d = NSMutableDictionary() for (k,v) in self { switch v { case let dic as NSDictionary: mutable_d[k] = dic.mutable_dictionary;break case let arr as NSArray: mutable_d[k] = arr.mutable_array;break case let str as String: mutable_d[k] = str;break case let int as Int64: mutable_d[k] = int;break case let int as Int32: mutable_d[k] = int;break case let int as Int: mutable_d[k] = int;break case let flt as Float: mutable_d[k] = flt;break case let dbl as Double: mutable_d[k] = dbl;break case let cgf as CGFloat: mutable_d[k] = cgf;break default: mutable_d[k] = v;break } } return mutable_d } }
mit
9e2af35b8b2b1377f674ff133e95bf7b
21.901235
59
0.540701
4.359577
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 02/MyFirstPlayground.playground/section-1.swift
1
409
import UIKit var str = "Hello, playground" var counter = 0; var secondCounter = 0; for i in 0..<10 { counter += i print("Counter: \(counter)") for j in 1...10 { secondCounter += j } } let textField = UITextField(); textField.frame = CGRect(x: 0, y: 0, width: 200, height: 50); textField.text = "hello"; textField.backgroundColor = .red; textField.borderStyle = .bezel; textField;
mit
def45397456eae6ba4979d82c62df244
17.590909
61
0.638142
3.352459
false
false
false
false
mightydeveloper/swift
validation-test/compiler_crashers_2_fixed/0003-rdar20564378.swift
9
4384
// RUN: not %target-swift-frontend %s -parse public protocol Q_SequenceDefaultsType { typealias Element typealias Generator : GeneratorType func generate() -> Generator } extension Q_SequenceDefaultsType { public final func underestimateCount() -> Int { return 0 } public final func preprocessingPass<R>(body: (Self)->R) -> R? { return nil } /// Create a ContiguousArray containing the elements of `self`, /// in the same order. public final func copyToContiguousArray() -> ContiguousArray<Generator.Element> { let initialCapacity = underestimateCount() var result = _ContiguousArrayBuffer<Generator.Element>( count: initialCapacity, minimumCapacity: 0) var g = self.generate() while let x = g.next() { result += CollectionOfOne(x) } return ContiguousArray(result) } /// Initialize the storage at baseAddress with the contents of this /// sequence. public final func initializeRawMemory( baseAddress: UnsafeMutablePointer<Generator.Element> ) { var p = baseAddress var g = self.generate() while let element = g.next() { p.initialize(element) ++p } } public final static func _constrainElement(Generator.Element) {} } /// A type that can be iterated with a `for`\ ...\ `in` loop. /// /// `SequenceType` makes no requirement on conforming types regarding /// whether they will be destructively "consumed" by iteration. To /// ensure non-destructive iteration, constrain your *sequence* to /// `CollectionType`. public protocol Q_SequenceType : Q_SequenceDefaultsType { /// A type that provides the *sequence*\ 's iteration interface and /// encapsulates its iteration state. typealias Generator : GeneratorType /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> Generator /// Return a value less than or equal to the number of elements in /// self, **nondestructively**. /// /// Complexity: O(N) func underestimateCount() -> Int /// If `self` is multi-pass (i.e., a `CollectionType`), invoke the function /// on `self` and return its result. Otherwise, return `nil`. func preprocessingPass<R>(body: (Self)->R) -> R? /// Create a ContiguousArray containing the elements of `self`, /// in the same order. func copyToContiguousArray() -> ContiguousArray<Element> /// Initialize the storage at baseAddress with the contents of this /// sequence. func initializeRawMemory( baseAddress: UnsafeMutablePointer<Element> ) static func _constrainElement(Element) } public extension GeneratorType { typealias Generator = Self public final func generate() -> Generator { return self } } public protocol Q_CollectionDefaultsType : Q_SequenceType { typealias Index : ForwardIndexType subscript(position: Index) -> Element {get} var startIndex: Index {get} var endIndex: Index {get} } extension Q_CollectionDefaultsType { public final func count() -> Index.Distance { return distance(startIndex, endIndex) } public final func underestimateCount() -> Int { let n = count().toIntMax() return n > IntMax(Int.max) ? Int.max : Int(n) } public final func preprocessingPass<R>(body: (Self)->R) -> R? { return body(self) } /* typealias Generator = Q_IndexingGenerator<Self> public final func generate() -> Q_IndexingGenerator<Self> { return Q_IndexingGenerator(pos: self.startIndex, elements: self) } */ } public struct Q_IndexingGenerator<C: Q_CollectionDefaultsType> : GeneratorType { public typealias Element = C.Element var pos: C.Index let elements: C public mutating func next() -> Element? { if pos == elements.endIndex { return nil } let ret = elements[pos] ++pos return ret } } public protocol Q_CollectionType : Q_CollectionDefaultsType { func count() -> Index.Distance subscript(position: Index) -> Element {get} } extension Array : Q_CollectionType { public func copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(self~>_copyToNativeArrayBuffer()) } } struct Boo : Q_CollectionType { let startIndex: Int = 0 let endIndex: Int = 10 func generate() -> Q_IndexingGenerator<Boo> { return Q_IndexingGenerator(pos: self.startIndex, elements: self) } subscript(i: Int) -> String { return "Boo" } }
apache-2.0
5eb6314ac46cf6c75274bcafef3c3472
26.4
83
0.690922
4.323471
false
false
false
false
Anvics/Amber
Amber/Classes/AmberController+UI.swift
1
1904
// // AmberControllerHelper.swift // TrainBrain // // Created by Nikita Arkhipov on 09.10.2017. // Copyright © 2017 Nikita Arkhipov. All rights reserved. // import UIKit extension AmberPresentable{ public static func instantiate() -> Self{ let sb = UIStoryboard(name: storyboardFile, bundle: nil) guard let vc = sb.instantiateViewController(withIdentifier: storyboardID) as? Self else { fatalError() } return vc } } extension UIViewController: AmberPresenter{ public func push(_ viewController: UIViewController, animated: Bool){ navigationController?.pushViewController(viewController, animated: animated) } public func embedIn(view: UIView, container: UIViewController){ self.view.frame = view.bounds container.addChildViewController(self) view.addSubview(self.view) didMove(toParentViewController: container) } public func show(_ viewController: UIViewController, animated: Bool){ if navigationController != nil { push(viewController, animated: true) } else { present(viewController, animated: true, completion: nil) } } public func close(animated: Bool){ if let nav = navigationController{ nav.popViewController(animated: animated) } else if parent != nil { unembed() } else{ dismiss(animated: animated, completion: nil) } } public func dismiss(animated: Bool) { dismiss(animated: animated, completion: nil) } public func pop(animated: Bool){ navigationController?.popViewController(animated: animated) } public func popToRoot(animated: Bool){ navigationController?.popToRootViewController(animated: animated) } private func unembed(){ removeFromParentViewController() view.removeFromSuperview() didMove(toParentViewController: nil) } }
mit
5bb2c23a7830f3221ee6990b76ff619f
31.254237
112
0.682081
4.930052
false
false
false
false
chaoyang805/DoubanMovie
DoubanMovie/UIDevice+ModelName.swift
1
2706
// // UIDevice+ModelName.swift // DoubanMovie // // Created by chaoyang805 on 16/10/23. // Copyright © 2016年 jikexueyuan. All rights reserved. // import UIKit public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 , value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return "Simulator" default: return identifier } } }
apache-2.0
3e862746fb23d18a1de5f0b6d2b94343
50.980769
92
0.470218
3.872493
false
false
false
false
xu6148152/binea_project_for_ios
SportDemo/SportDemo/Soccer/AppDelegate.swift
1
7664
// // AppDelegate.swift // Soccer // // Created by Binea Xu on 8/1/15. // Copyright (c) 2015 Binea Xu. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var appWindow: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. setupApperance() self.appWindow = self.window 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.binea.Soccer" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Soccer", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Soccer.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } func setupApperance(){ UINavigationBar.appearance().barStyle = UIBarStyle.Black let barTextFont = UIFont(name: "Avenir-Medium", size: 16) ?? UIFont.systemFontOfSize(16) UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: barTextFont, NSForegroundColorAttributeName: UIColor.whiteColor()] UINavigationBar.appearance().setBackgroundImage(UIImage(named: "common_bar_background"), forBarMetrics: .Default) UINavigationBar.appearance().shadowImage = UIImage(named: "common_bar_shadow") UINavigationBar.appearance().tintColor = UIGlobal.ZEPPGREENCOLOR var backButtonBackgroundImage = UIImage(named: "common_topnav_back"); let myInsets = UIEdgeInsetsMake(13, 37, 13, 37) backButtonBackgroundImage = backButtonBackgroundImage!.resizableImageWithCapInsets(myInsets) UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonBackgroundImage, forState: UIControlState.Normal, barMetrics: .Default) UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Avenir-Heavy", size: 16) ?? UIFont.systemFontOfSize(16)], forState: UIControlState.Normal) } }
mit
2e0cf6339421ec72b0d51a030f947c3a
52.594406
290
0.703941
5.758077
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Home/HomePanelViewController.swift
1
15221
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import SnapKit import UIKit import Storage private struct HomePanelViewControllerUX { // Height of the top panel switcher button toolbar. static let ButtonContainerHeight: CGFloat = 40 static let ButtonHighlightLineHeight: CGFloat = 2 static let ButtonSelectionAnimationDuration = 0.2 } protocol HomePanelViewControllerDelegate: AnyObject { func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) func homePanelViewController(_ HomePanelViewController: HomePanelViewController, didSelectPanel panel: Int) func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) } protocol HomePanel: AnyObject, Themeable { var homePanelDelegate: HomePanelDelegate? { get set } } struct HomePanelUX { static let EmptyTabContentOffset = -180 } protocol HomePanelDelegate: AnyObject { func homePanelDidRequestToSignIn(_ homePanel: HomePanel) func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) } struct HomePanelState { var selectedIndex: Int = 0 } enum HomePanelType: Int { case topSites = 0 case bookmarks = 1 case history = 2 case readingList = 3 case downloads = 4 var localhostURL: URL { return URL(string: "#panel=\(self.rawValue)", relativeTo: UIConstants.AboutHomePage as URL)! } } class HomePanelViewController: UIViewController, UITextFieldDelegate, HomePanelDelegate { var profile: Profile! var notificationToken: NSObjectProtocol! var panels: [HomePanelDescriptor]! var url: URL? weak var delegate: HomePanelViewControllerDelegate? fileprivate var buttonContainerView = UIStackView() fileprivate var buttonContainerBottomBorderView: UIView! fileprivate var controllerContainerView: UIView! fileprivate var buttons: [UIButton] = [] fileprivate var highlightLine = UIView() //The line underneath a panel button that shows which one is selected fileprivate var buttonTintColor: UIColor? fileprivate var buttonSelectedTintColor: UIColor? var homePanelState: HomePanelState { return HomePanelState(selectedIndex: selectedPanel?.rawValue ?? 0) } override func viewDidLoad() { view.backgroundColor = UIColor.theme.browser.background buttonContainerView.axis = .horizontal buttonContainerView.alignment = .fill buttonContainerView.distribution = .fillEqually buttonContainerView.spacing = 14 buttonContainerView.clipsToBounds = true buttonContainerView.accessibilityNavigationStyle = .combined buttonContainerView.accessibilityLabel = NSLocalizedString("Panel Chooser", comment: "Accessibility label for the Home panel's top toolbar containing list of the home panels (top sites, bookmarks, history, remote tabs, reading list).") view.addSubview(buttonContainerView) buttonContainerView.addSubview(highlightLine) self.buttonContainerBottomBorderView = UIView() self.view.addSubview(buttonContainerBottomBorderView) buttonContainerBottomBorderView.backgroundColor = UIColor.theme.homePanel.buttonContainerBorder controllerContainerView = UIView() view.addSubview(controllerContainerView) buttonContainerView.snp.makeConstraints { make in make.top.equalTo(self.view) make.leading.trailing.equalTo(self.view).inset(14) make.height.equalTo(HomePanelViewControllerUX.ButtonContainerHeight) } buttonContainerBottomBorderView.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom).offset(-1) make.bottom.equalTo(self.buttonContainerView) make.leading.trailing.equalToSuperview() } controllerContainerView.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } self.panels = HomePanels().enabledPanels updateButtons() // Gesture recognizer to dismiss the keyboard in the URLBarView when the buttonContainerView is tapped let dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) dismissKeyboardGestureRecognizer.cancelsTouchesInView = false buttonContainerView.addGestureRecognizer(dismissKeyboardGestureRecognizer) } @objc func dismissKeyboard(_ gestureRecognizer: UITapGestureRecognizer) { view.window?.rootViewController?.view.endEditing(true) } var selectedPanel: HomePanelType? = nil { didSet { if oldValue == selectedPanel { // Prevent flicker, allocations, and disk access: avoid duplicate view controllers. return } if let index = oldValue?.rawValue { if index < buttons.count { let currentButton = buttons[index] currentButton.isSelected = false currentButton.isUserInteractionEnabled = true } } hideCurrentPanel() if let index = selectedPanel?.rawValue { if index < buttons.count { let newButton = buttons[index] newButton.isSelected = true newButton.isUserInteractionEnabled = false } if index < panels.count { let panel = self.panels[index].makeViewController(profile) let accessibilityLabel = self.panels[index].accessibilityLabel if let panelController = panel as? UINavigationController, let rootPanel = panelController.viewControllers.first { setupHomePanel(rootPanel, accessibilityLabel: accessibilityLabel) self.showPanel(panelController) } else { setupHomePanel(panel, accessibilityLabel: accessibilityLabel) self.showPanel(panel) } } } self.updateButtonTints() } } func setupHomePanel(_ panel: UIViewController, accessibilityLabel: String) { (panel as? HomePanel)?.homePanelDelegate = self panel.view.accessibilityNavigationStyle = .combined panel.view.accessibilityLabel = accessibilityLabel } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } fileprivate func hideCurrentPanel() { if let panel = childViewControllers.first { panel.willMove(toParentViewController: nil) panel.beginAppearanceTransition(false, animated: false) panel.view.removeFromSuperview() panel.endAppearanceTransition() panel.removeFromParentViewController() } } fileprivate func showPanel(_ panel: UIViewController) { addChildViewController(panel) panel.beginAppearanceTransition(true, animated: false) controllerContainerView.addSubview(panel.view) panel.endAppearanceTransition() panel.view.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } panel.didMove(toParentViewController: self) } @objc func tappedButton(_ sender: UIButton!) { for (index, button) in buttons.enumerated() where button == sender { selectedPanel = HomePanelType(rawValue: index) delegate?.homePanelViewController(self, didSelectPanel: index) if selectedPanel == .bookmarks { UnifiedTelemetry.recordEvent(category: .action, method: .view, object: .bookmarksPanel, value: .homePanelTabButton) } else if selectedPanel == .downloads { UnifiedTelemetry.recordEvent(category: .action, method: .view, object: .downloadsPanel, value: .homePanelTabButton) } break } } fileprivate func updateButtons() { for panel in panels { let button = UIButton() button.addTarget(self, action: #selector(tappedButton), for: .touchUpInside) if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)") { button.setImage(image, for: .normal) } button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 4, right: 0) button.accessibilityLabel = panel.accessibilityLabel button.accessibilityIdentifier = panel.accessibilityIdentifier buttons.append(button) self.buttonContainerView.addArrangedSubview(button) } } func updateButtonTints() { var selectedbutton: UIView? for (index, button) in self.buttons.enumerated() { if index == self.selectedPanel?.rawValue { button.tintColor = self.buttonSelectedTintColor selectedbutton = button } else { button.tintColor = self.buttonTintColor } } guard let button = selectedbutton else { return } // Calling this before makes sure that only the highlightline animates and not the homepanels self.view.setNeedsUpdateConstraints() self.view.layoutIfNeeded() UIView.animate(withDuration: HomePanelViewControllerUX.ButtonSelectionAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { self.highlightLine.snp.remakeConstraints { make in make.leading.equalTo(button.snp.leading) make.trailing.equalTo(button.snp.trailing) make.bottom.equalToSuperview() make.height.equalTo(HomePanelViewControllerUX.ButtonHighlightLineHeight) } self.view.setNeedsUpdateConstraints() self.view.layoutIfNeeded() }, completion: nil) } func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) { // If we can't get a real URL out of what should be a URL, we let the user's // default search engine give it a shot. // Typically we'll be in this state if the user has tapped a bookmarked search template // (e.g., "http://foo.com/bar/?query=%s"), and this will get them the same behavior as if // they'd copied and pasted into the URL bar. // See BrowserViewController.urlBar:didSubmitText:. guard let url = URIFixup.getURL(url) ?? profile.searchEngines.defaultEngine.searchURLForQuery(url) else { Logger.browserLogger.warning("Invalid URL, and couldn't generate a search URL for it.") return } return self.homePanel(homePanel, didSelectURL: url, visitType: visitType) } func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) { delegate?.homePanelViewController(self, didSelectURL: url, visitType: visitType) dismiss(animated: true, completion: nil) } func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToCreateAccount(self) } func homePanelDidRequestToSignIn(_ homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToSignIn(self) } func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { delegate?.homePanelViewControllerDidRequestToOpenInNewTab(url, isPrivate: isPrivate) } } // MARK: UIAppearance extension HomePanelViewController: Themeable { func applyTheme() { func apply(_ vc: UIViewController) -> Bool { guard let vc = vc as? Themeable else { return false } vc.applyTheme() return true } childViewControllers.forEach { if !apply($0) { // BookmarksPanel is nested in a UINavigationController, go one layer deeper $0.childViewControllers.forEach { _ = apply($0) } } } buttonContainerView.backgroundColor = UIColor.theme.homePanel.toolbarBackground view.backgroundColor = UIColor.theme.homePanel.toolbarBackground buttonTintColor = UIColor.theme.homePanel.toolbarTint buttonSelectedTintColor = UIColor.theme.homePanel.toolbarHighlight highlightLine.backgroundColor = UIColor.theme.homePanel.toolbarHighlight updateButtonTints() } } protocol HomePanelContextMenu { func getSiteDetails(for indexPath: IndexPath) -> Site? func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? func presentContextMenu(for indexPath: IndexPath) func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) } extension HomePanelContextMenu { func presentContextMenu(for indexPath: IndexPath) { guard let site = getSiteDetails(for: indexPath) else { return } presentContextMenu(for: site, with: indexPath, completionHandler: { return self.contextMenu(for: site, with: indexPath) }) } func contextMenu(for site: Site, with indexPath: IndexPath) -> PhotonActionSheet? { guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil } let contextMenu = PhotonActionSheet(site: site, actions: actions) contextMenu.modalPresentationStyle = .overFullScreen contextMenu.modalTransitionStyle = .crossDissolve return contextMenu } func getDefaultContextMenuActions(for site: Site, homePanelDelegate: HomePanelDelegate?) -> [PhotonActionSheetItem]? { guard let siteURL = URL(string: site.url) else { return nil } let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { action in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) } let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { action in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } return [openInNewTabAction, openInNewPrivateTabAction] } }
mpl-2.0
8fd6f8040d2161f8da4ea60774cfabe5
41.876056
243
0.684449
5.743774
false
false
false
false
amarcu5/PiPer
src/safari/App/DonateViewController.swift
1
2849
// // DonateViewController.swift // PiPer // // Created by Adam Marcus on 17/11/2018. // Copyright © 2018 Adam Marcus. All rights reserved. // import Cocoa class DonateViewController: NSViewController { @IBOutlet var totalDonations: NSTextField! @objc dynamic var donationProducts = [DonationProduct]() @IBOutlet var donationTableView: NSTableView! @IBOutlet var tableViewHeightConstraint: NSLayoutConstraint! @IBOutlet var tableViewWidthConstraint: NSLayoutConstraint! @IBOutlet var confettiView: ConfettiView! func loadProducts(completionHandler: @escaping (_ success: Bool) -> ()) { DonationManager.shared.getDonationProducts(completionHandler: { productsResponse, error in if let products = productsResponse { self.donationProducts = products completionHandler(true) } else { completionHandler(false) } }) } override func viewDidLoad() { super.viewDidLoad() self.donationTableView.postsFrameChangedNotifications = true NotificationCenter.default.addObserver( self, selector: #selector(sizeDonationTableViewToFitContents), name: NSView.frameDidChangeNotification, object: self.donationTableView) sizeDonationTableViewToFitContents() updateTotalDonations() } @objc private func sizeDonationTableViewToFitContents() { var computedWidth: CGFloat = 0 for row in 0..<self.donationTableView.numberOfRows { if let tableCellView = self.donationTableView.view(atColumn: 0, row:row, makeIfNecessary: true) { computedWidth = max(computedWidth, tableCellView.fittingSize.width) } } self.tableViewHeightConstraint.constant = self.donationTableView.frame.size.height self.tableViewWidthConstraint.constant = computedWidth self.donationTableView.tableColumns.first?.width = computedWidth self.donationTableView.needsUpdateConstraints = true } func updateTotalDonations() { let totalDonations = DonationManager.shared.totalDonations if let priceString = DonationManager.shared.localizedStringForPrice(totalDonations), let emoticon = DonationManager.shared.emoticonForPrice(totalDonations) { self.totalDonations.stringValue = priceString + " " + emoticon } } @IBAction func buyClicked(sender: NSButton) { let row = self.donationTableView.row(for: sender) let donationProduct = self.donationProducts[row] DonationManager.shared.buyDonationProduct(donationProduct, completionHandler: { transaction in let state = transaction.transactionState if state == .purchased || state == .restored { self.confettiView.dropConfetti() self.updateTotalDonations() } }) } @IBAction func dismissClicked(sender: NSButton) { self.parent?.dismiss(self.parent) } }
gpl-3.0
1e59e23a486cf8ca42d12613017bd540
31.363636
103
0.726124
4.927336
false
false
false
false
JimmyPeng4iOS/JMCarouselView
JMCarouselView/JMCarousel/JMCarouselScrollView.swift
1
9069
// // JMCarouselScrollView.swift // JMCarouselView // // Created by JimmyPeng on 15/12/17. // Copyright © 2015年 Jimmy. All rights reserved. // import UIKit //广告数目 class JMCarouselScrollView: UIView,UIScrollViewDelegate { //MARK: - 属性 //是否URL加载 private var isFromURL:Bool = true //页码 private var index:Int = 0 //图片数量 private var imgViewNum:Int = 0 //宽度 private var sWidth:CGFloat = 0 //高度 private var sHeight:CGFloat = 0 //广告每一页停留时间 private var pageStepTime:NSTimeInterval = 0 //定时器 private var timer:NSTimer? //图片数组 private var imgArray: [UIImage]? //图片url数组 private var imgURLArray:[String]? //MARK: - 初始化方法 /** 初始化方法1,传入图片URL数组,以及pageControl的当前page点的颜色,特别注意需要SDWebImage框架支持 - parameter frame: frame - parameter imgURLArray: 图片URL数组 - parameter pagePointColor: pageControl的当前page点的颜色 - parameter stepTime: 广告每一页停留时间 - returns: ScrollView图片轮播器 */ init(frame: CGRect, imageURLArray:[String], pagePointColor: UIColor, stepTime: NSTimeInterval) { super.init(frame: frame) imgURLArray = imageURLArray prepareUI(imageURLArray.count, pagePointColor: pagePointColor,stepTime: stepTime) } /** 初始化方法2,传入图片数组,以及pageControl的当前page点的颜色,无需依赖第三方库 - parameter frame: frame - parameter imgArray: 图片数组 - parameter pagePointColor: pageControl的当前page点的颜色 - parameter stepTime: 广告每一页停留时间 - returns: ScrollView图片轮播器 */ init(frame: CGRect, imageArray:[UIImage], pagePointColor: UIColor, stepTime: NSTimeInterval) { super.init(frame: frame) imgArray = imageArray isFromURL = false prepareUI(imageArray.count, pagePointColor: pagePointColor,stepTime: stepTime) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - 准备UI private func prepareUI(numberOfImage:Int, pagePointColor: UIColor,stepTime: NSTimeInterval) { //设置图片数量 imgViewNum = numberOfImage //广告每一页停留时间 pageStepTime = stepTime //添加scrollView addSubview(ScrollView) //添加pageControl addSubview(pageControl) //pageControl数量 pageControl.numberOfPages = imgViewNum; //pageControl颜色 pageControl.currentPageIndicatorTintColor = pagePointColor //view宽度 sWidth = self.frame.size.width //view高度 sHeight = self.frame.size.height //设置代理 ScrollView.delegate = self; //一页页滚动 ScrollView.pagingEnabled = true; //隐藏滚动条 ScrollView.showsHorizontalScrollIndicator = false; //设置一开始偏移量 ScrollView.contentOffset = CGPointMake(sWidth , 0); //设置timer setTheTimer() //设置图片 prepareImage() } //布局子控件 override func layoutSubviews() { super.layoutSubviews() //布局ScrollView ScrollView.frame = self.bounds //布局pageControl let pW = ScrollView.frame.width let pH = CGFloat(15) let pX = CGFloat(0) let pY = ScrollView.frame.height - CGFloat(pH * 2) pageControl.frame = CGRect(x: pX, y: pY, width: pW, height: pH) } deinit { print("scrollDeinit") } //MARK: - 创建广告图片 /** * 创建广告图片 */ private func prepareImage() { dispatch_async(dispatch_get_main_queue(), { () -> Void in //设置一开始偏移量 self.ScrollView.contentOffset = CGPointMake(self.sWidth, 0); //设置滚动范围 self.ScrollView.contentSize = CGSizeMake(CGFloat(self.imgViewNum + 2) * self.sWidth, 0) }) for i in 0 ..< imgViewNum + 2 { var imgX = CGFloat(i) * sWidth; let imgY:CGFloat = 0; let imgW = sWidth; let imgH = sHeight; let imgView = UIImageView() if i == 0 { //第0张 显示广告最后一张 imgX = 0; if !isFromURL { imgView.image = imgArray?.last } else { imgView.sd_setImageWithURL(NSURL(string: (imgURLArray?.last)!), placeholderImage: UIImage(named: "holder")) } } else if i == imgViewNum + 1 { //第n+1张,显示广告第一张 imgX = CGFloat(imgViewNum + 1) * sWidth; if !isFromURL { imgView.image = imgArray?.first } else { imgView.sd_setImageWithURL(NSURL(string: (imgURLArray?.first)!), placeholderImage: UIImage(named: "holder")) } } else { //正常显示广告 if !isFromURL { imgView.image = imgArray?[i - 1] } else { imgView.sd_setImageWithURL(NSURL(string: (imgURLArray?[i - 1])!), placeholderImage: UIImage(named: "holder")) } } imgView.frame = CGRect(x: imgX, y: imgY, width: imgW, height: imgH) //添加子控件 ScrollView.addSubview(imgView) } } /** * 执行下一页的方法 */ @objc private func nextImage() { //取得当前pageControl页码 var indexP = self.pageControl.currentPage if indexP == imgViewNum { indexP = 1; } else { indexP++; } ScrollView.setContentOffset(CGPoint(x: CGFloat(indexP + 1) * sWidth, y: 0), animated: true) } //MARK: - pragma mark- 代理 /** * 动画减速时的判断 * */ func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { carousel() } /** * 拖拽减速时的判断 * */ func scrollViewDidEndDecelerating(scrollView: UIScrollView) { carousel() } func carousel() { //获取偏移值 let offset = ScrollView.contentOffset.x; //当前页 let page = Int((offset + sWidth/2) / sWidth); //如果是N+1页 if page == imgViewNum + 1 { //瞬间跳转第1页 ScrollView.setContentOffset(CGPoint(x: sWidth, y: 0), animated: false) index = 1 } //如果是第0页 else if page == 0 { //瞬间跳转最后一页 ScrollView.setContentOffset(CGPoint(x: CGFloat(imgViewNum) * sWidth, y: 0), animated: false) } } /** * 滚动时判断页码 */ func scrollViewDidScroll(scrollView: UIScrollView) { //获取偏移值 let offset = ScrollView.contentOffset.x - sWidth; //页码 let pageIndex = Int((offset + sWidth / 2.0) / sWidth); pageControl.currentPage = pageIndex } /** * 拖拽广告时停止timer */ func scrollViewWillBeginDragging(scrollView: UIScrollView) { stopTimer() } /** 销毁timer */ func stopTimer() { timer?.invalidate() timer = nil } /** * 结束拖拽时重新创建timer */ func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { setTheTimer() } //MARK:设置timer private func setTheTimer() { timer = NSTimer.scheduledTimerWithTimeInterval(pageStepTime, target: self, selector: "nextImage", userInfo: nil, repeats: true) let runloop = NSRunLoop.currentRunLoop() runloop.addTimer(timer!, forMode: NSRunLoopCommonModes) } //MARL: - 懒加载 //广告滚动view private lazy var ScrollView: UIScrollView = UIScrollView() private lazy var pageControl: UIPageControl = UIPageControl() }
apache-2.0
90588ab77590e42d6a85cd05bc8d1069
23.221574
135
0.516731
4.824623
false
false
false
false
gowansg/firefox-ios
Sync/Synchronizers/Synchronizer.swift
1
3412
/* 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 Storage import XCGLogger // TODO: same comment as for SyncAuthState.swift! private let log = XCGLogger.defaultInstance() public typealias Success = Deferred<Result<()>> func succeed() -> Success { return deferResult(()) } /** * This exists to pass in external context: e.g., the UIApplication can * expose notification functionality in this way. */ public protocol SyncDelegate { func displaySentTabForURL(URL: NSURL, title: String) // TODO: storage. } // TODO: return values? /** * A Synchronizer is (unavoidably) entirely in charge of what it does within a sync. * For example, it might make incremental progress in building a local cache of remote records, never actually performing an upload or modifying local storage. * It might only upload data. Etc. * * Eventually I envision an intent-like approach, or additional methods, to specify preferences and constraints * (e.g., "do what you can in a few seconds", or "do a full sync, no matter how long it takes"), but that'll come in time. * * A Synchronizer is a two-stage beast. It needs to support synchronization, of course; that * needs a completely configured client, which can only be obtained from Ready. But it also * needs to be able to do certain things beforehand: * * * Wipe its collections from the server (presumably via a delegate from the state machine). * * Prepare to sync from scratch ("reset") in response to a changed set of keys, syncID, or node assignment. * * Wipe local storage ("wipeClient"). * * Those imply that some kind of 'Synchronizer' exists throughout the state machine. We *could* * pickle instructions for eventual delivery next time one is made and synchronized… */ public protocol Synchronizer { init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) //func synchronize(client: Sync15StorageClient, info: InfoCollections) -> Deferred<Result<Scratchpad>> } public class FatalError: SyncError { let message: String init(message: String) { self.message = message } public var description: String { return self.message } } public protocol SingleCollectionSynchronizer { func remoteHasChanges(info: InfoCollections) -> Bool } public class BaseSingleCollectionSynchronizer: SingleCollectionSynchronizer { let collection: String let scratchpad: Scratchpad let delegate: SyncDelegate let prefs: Prefs init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, collection: String) { self.scratchpad = scratchpad self.delegate = delegate self.collection = collection let branchName = "synchronizer." + collection + "." self.prefs = basePrefs.branch(branchName) log.info("Synchronizer configured with prefs \(branchName).") } var lastFetched: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastFetched") } get { return self.prefs.unsignedLongForKey("lastFetched") ?? 0 } } public func remoteHasChanges(info: InfoCollections) -> Bool { return info.modified(self.collection) > self.lastFetched } }
mpl-2.0
cd62a25d41720e749259927f31d75951
33.806122
159
0.712903
4.546667
false
false
false
false
Pluto-Y/SwiftyEcharts
DemoOptions/ThemeRiverOptions.swift
1
5540
// // ThemeRiverOptions.swift // SwiftyEcharts // // Created by Pluto-Y on 16/01/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import SwiftyEcharts public final class ThemeRiverOptions { // MARK: 主题河流图 /// 地址: http://echarts.baidu.com/demo.html#themeRiver-basic static func themeRiverBasicOption() -> Option { guard let plistUrl = Bundle.main.path(forResource: "ThemeRiverBasicData", ofType: "plist") else { return Option() } guard let plistDatas = NSDictionary(contentsOfFile: plistUrl) else { return Option() } let datas: [Jsonable] = (plistDatas["datas"] as! [[Any]]).map { $0 } return Option( .tooltip(Tooltip( .trigger(.axis), .axisPointer(AxisPointerForTooltip( .type(.line), .lineStyle(LineStyle( .color(.rgba(0, 0, 0, 0.2)), .width(1), .type(.solid) )) )) )), .legend(Legend( .data(["DQ", "TY", "SS", "QG", "SY", "DD"]) )), .singleAxis(SingleAxis( .axisTick(AxisTick()), .axisLabel(AxisLabel()), .type(.time), .splitLine(SplitLine( .show(true), .lineStyle(LineStyle( .type(.dashed), .opacity(0.2) )) )) )), .series([ ThemeRiverSerie( .itemStyle(ItemStyle( .emphasis(CommonItemStyleContent( .shadowBlur(20), .shadowColor(.rgba(0, 0, 0, 0.8)) )) )), .data(datas) ) ]) ) } // MARK: ThemeRiver Lastfm /// 地址: http://echarts.baidu.com/demo.html#themeRiver-lastfm static func themeRiverLastfmOption() -> Option { let rawData = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 49, 67, 16, 0, 19, 19, 0, 0, 1, 10, 5, 6, 1, 1, 0, 25, 0, 0, 0], [0, 6, 3, 34, 0, 16, 1, 0, 0, 1, 6, 0, 1, 56, 0, 2, 0, 2, 0, 0], [0, 8, 13, 15, 0, 12, 23, 0, 0, 1, 0, 1, 0, 0, 6, 0, 0, 1, 0, 1], [0, 9, 28, 0, 91, 6, 1, 0, 0, 0, 7, 18, 0, 9, 16, 0, 1, 0, 0, 0], [0, 3, 42, 36, 21, 0, 1, 0, 0, 0, 0, 16, 30, 1, 4, 62, 55, 1, 0, 0], [0, 7, 13, 12, 64, 5, 0, 0, 0, 8, 17, 3, 72, 1, 1, 53, 1, 0, 0, 0], [1, 14, 13, 7, 8, 8, 7, 0, 1, 1, 14, 6, 44, 8, 7, 17, 21, 1, 0, 0], [0, 6, 14, 2, 14, 1, 0, 0, 0, 0, 2, 2, 7, 15, 6, 3, 0, 0, 0, 0], [0, 9, 11, 3, 0, 8, 0, 0, 14, 2, 0, 1, 1, 1, 7, 13, 2, 1, 0, 0], [0, 7, 5, 10, 8, 21, 0, 0, 130, 1, 2, 18, 6, 1, 5, 1, 4, 1, 0, 7], [0, 2, 15, 1, 5, 5, 0, 0, 6, 0, 0, 0, 4, 1, 3, 1, 17, 0, 0, 9], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [6, 27, 26, 1, 0, 11, 1, 0, 0, 0, 1, 1, 2, 0, 0, 9, 1, 0, 0, 0], [31, 81, 11, 6, 11, 0, 0, 0, 0, 0, 0, 0, 3, 2, 0, 3, 14, 0, 0, 12], [19, 53, 6, 20, 0, 4, 37, 0, 30, 86, 43, 7, 5, 7, 17, 19, 2, 0, 0, 5], [0, 22, 14, 6, 10, 24, 18, 0, 13, 21, 5, 2, 13, 35, 7, 1, 8, 0, 0, 1], [0, 56, 5, 0, 0, 0, 0, 0, 7, 24, 0, 17, 7, 0, 0, 3, 0, 0, 0, 8], [18, 29, 3, 6, 11, 0, 15, 0, 12, 42, 37, 0, 3, 3, 13, 8, 0, 0, 0, 1], [32, 39, 37, 3, 33, 21, 6, 0, 4, 17, 0, 11, 8, 2, 3, 0, 23, 0, 0, 17], [72, 15, 28, 0, 0, 0, 0, 0, 1, 3, 0, 35, 0, 9, 17, 1, 9, 1, 0, 8], [11, 15, 4, 2, 0, 18, 10, 0, 20, 3, 0, 0, 2, 0, 0, 2, 2, 30, 0, 0], [14, 29, 19, 3, 2, 17, 13, 0, 7, 12, 2, 0, 6, 0, 0, 1, 1, 34, 0, 1], [1, 1, 7, 6, 1, 1, 15, 1, 1, 2, 1, 3, 1, 1, 9, 1, 1, 25, 1, 72] ] let labels = [ "The Sea and Cake", "Andrew Bird", "Laura Veirs", "Brian Eno", "Christopher Willits", "Wilco", "Edgar Meyer", "Bxc3xa9la Fleck", "Fleet Foxes", "Kings of Convenience", "Brett Dennen", "Psapp", "The Bad Plus", "Feist", "Battles", "Avishai Cohen", "Rachael Yamagata", "Norah Jones", "Bxc3xa9la Fleck and the Flecktones", "Joshua Redman" ] var data: [Jsonable] = [] for i in 0..<rawData.count { for j in 0..<rawData[i].count { var l: String = "null" if i < labels.count { l = labels[i] } let d: [Jsonable] = [j, rawData[i][j], l] data.append(d) } } return Option( .singleAxis(SingleAxis( .max("dataMax") )), .series([ ThemeRiverSerie( .data(data), .label(EmphasisLabel( .normal(LabelStyle( .show(false) )) )) ) ]) ) } }
mit
d8c8be6c276ddf85cc8b04ed9cdd9b02
37.340278
105
0.364789
3.144077
false
false
false
false