repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dogo/AKMediaViewer
refs/heads/develop
AKMediaViewer/AKMediaViewerManager.swift
mit
1
// // AKMediaViewerManager.swift // AKMediaViewer // // Created by Diogo Autilio on 3/18/16. // Copyright © 2016 AnyKey Entertainment. All rights reserved. // import Foundation import UIKit let kAnimateElasticSizeRatio: CGFloat = 0.03 let kAnimateElasticDurationRatio: Double = 0.6 let kAnimateElasticSecondMoveSizeRatio: CGFloat = 0.5 let kAnimateElasticThirdMoveSizeRatio: CGFloat = 0.2 let kAnimationDuration: Double = 0.5 let kSwipeOffset: CGFloat = 100 // MARK: - <AKMediaViewerDelegate> @objc public protocol AKMediaViewerDelegate: NSObjectProtocol { // Returns the view controller in which the focus controller is going to be added. This can be any view controller, full screen or not. func parentViewControllerForMediaViewerManager(_ manager: AKMediaViewerManager) -> UIViewController // Returns the URL where the media (image or video) is stored. The URL may be local (file://) or distant (http://). func mediaViewerManager(_ manager: AKMediaViewerManager, mediaURLForView view: UIView) -> URL // Returns the title for this media view. Return nil if you don't want any title to appear. func mediaViewerManager(_ manager: AKMediaViewerManager, titleForView view: UIView) -> String // MARK: - <AKMediaViewerDelegate> Optional /* Returns an image view that represents the media view. This image from this view is used in the focusing animation view. It is usually a small image. If not implemented, default is the initial media view in case it's an UIImageview. */ @objc optional func mediaViewerManager(_ manager: AKMediaViewerManager, imageViewForView view: UIView) -> UIImageView // Returns the final focused frame for this media view. This frame is usually a full screen frame. If not implemented, default is the parent view controller's view frame. @objc optional func mediaViewerManager(_ manager: AKMediaViewerManager, finalFrameForView view: UIView) -> CGRect // Called when a focus view is about to be shown. For example, you might use this method to hide the status bar. @objc optional func mediaViewerManagerWillAppear(_ manager: AKMediaViewerManager) // Called when a focus view has been shown. @objc optional func mediaViewerManagerDidAppear(_ manager: AKMediaViewerManager) // Called when the view is about to be dismissed by the 'done' button or by gesture. For example, you might use this method to show the status bar (if it was hidden before). @objc optional func mediaViewerManagerWillDisappear(_ manager: AKMediaViewerManager) // Called when the view has be dismissed by the 'done' button or by gesture. @objc optional func mediaViewerManagerDidDisappear(_ manager: AKMediaViewerManager) // Called before mediaURLForView to check if image is already on memory. @objc optional func mediaViewerManager(_ manager: AKMediaViewerManager, cachedImageForView view: UIView) -> UIImage } // MARK: - AKMediaViewerManager public class AKMediaViewerManager: NSObject, UIGestureRecognizerDelegate { // The animation duration. Defaults to 0.5. public var animationDuration: TimeInterval // The background color. Defaults to transparent black. public var backgroundColor: UIColor // Enables defocus on vertical swipe. Defaults to True. public var defocusOnVerticalSwipe: Bool // Returns whether the animation has an elastic effect. Defaults to True. public var elasticAnimation: Bool // Returns whether zoom is enabled on fullscreen image. Defaults to True. public var zoomEnabled: Bool // Enables focus on pinch gesture. Defaults to False. public var focusOnPinch: Bool // Returns whether gesture is disabled during zooming. Defaults to True. public var gestureDisabledDuringZooming: Bool // Returns whether defocus is enabled with a tap on view. Defaults to False. public var isDefocusingWithTap: Bool // Returns wheter a play icon is automatically added to media view which corresponding URL is of video type. Defaults to True. public var addPlayIconOnVideo: Bool // Controller used to show custom accessories. If none is specified a default controller is used with a simple close button. public var topAccessoryController: UIViewController? // Image used to show a play icon on video thumbnails. Defaults to nil (uses internal image). public let playImage: UIImage? //Infinite loop for video files. public var infiniteLoop: Bool public weak var delegate: AKMediaViewerDelegate? // The media view being focused. var mediaView = UIView() var focusViewController: AKMediaViewerController? var isZooming: Bool var videoBehavior: AKVideoBehavior override public init() { animationDuration = kAnimationDuration backgroundColor = UIColor(white: 0.0, alpha: 0.8) defocusOnVerticalSwipe = true elasticAnimation = true zoomEnabled = true isZooming = false focusOnPinch = false gestureDisabledDuringZooming = true isDefocusingWithTap = false addPlayIconOnVideo = true videoBehavior = AKVideoBehavior() playImage = UIImage() infiniteLoop = false super.init() } // Install focusing gesture on the specified array of views. public func installOnViews(_ views: [UIView]) { for view in views { installOnView(view) } } // Install focusing gesture on the specified view. public func installOnView(_ view: UIView) { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleFocusGesture(_:))) view.addGestureRecognizer(tapGesture) view.isUserInteractionEnabled = true let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchFocusGesture(_:))) pinchRecognizer.delegate = self view.addGestureRecognizer(pinchRecognizer) let url = delegate?.mediaViewerManager(self, mediaURLForView: view) if addPlayIconOnVideo && isVideoURL(url) { videoBehavior.addVideoIconToView(view, image: playImage) } } func installDefocusActionOnFocusViewController(_ focusViewController: AKMediaViewerController) { // We need the view to be loaded. if focusViewController.view != nil { if isDefocusingWithTap { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDefocusGesture(_:))) tapGesture.require(toFail: focusViewController.doubleTapGesture) focusViewController.view.addGestureRecognizer(tapGesture) } else { setupAccessoryViewOnFocusViewController(focusViewController) } } } func setupAccessoryViewOnFocusViewController(_ focusViewController: AKMediaViewerController) { if topAccessoryController == nil { let defaultController = AKMediaFocusBasicToolbarController(nibName: "AKMediaFocusBasicToolbar", bundle: Bundle.AKMediaFrameworkBundle()) defaultController.view.backgroundColor = .clear defaultController.doneButton.addTarget(self, action: #selector(endFocusing), for: .touchUpInside) topAccessoryController = defaultController } if let topAccessoryController = topAccessoryController { var frame = topAccessoryController.view.frame frame.size.width = focusViewController.accessoryView.frame.size.width topAccessoryController.view.frame = frame focusViewController.accessoryView.addSubview(topAccessoryController.view) } } // MARK: - Utilities // Taken from https://github.com/rs/SDWebImage/blob/master/SDWebImage/SDWebImageDecoder.m func decodedImageWithImage(_ image: UIImage) -> UIImage? { // do not decode animated images if image.images != nil { return image } guard let imageRef = image.cgImage else { return nil } let alpha: CGImageAlphaInfo = imageRef.alphaInfo let anyAlpha: Bool = (alpha == CGImageAlphaInfo.first || alpha == CGImageAlphaInfo.last || alpha == CGImageAlphaInfo.premultipliedFirst || alpha == CGImageAlphaInfo.premultipliedLast) if anyAlpha { return image } // current guard var colorSpaceRef = imageRef.colorSpace else { return nil } let imageColorSpaceModel = colorSpaceRef.model let unsupportedColorSpace: Bool = (imageColorSpaceModel == CGColorSpaceModel.unknown || imageColorSpaceModel == CGColorSpaceModel.monochrome || imageColorSpaceModel == CGColorSpaceModel.cmyk || imageColorSpaceModel == CGColorSpaceModel.indexed) if unsupportedColorSpace { colorSpaceRef = CGColorSpaceCreateDeviceRGB() } let width: size_t = imageRef.width let height: size_t = imageRef.height let bytesPerPixel: Int = 4 let bytesPerRow: Int = bytesPerPixel * width let bitsPerComponent: Int = 8 // CGImageAlphaInfo.None is not supported in CGBitmapContextCreate. // Since the original image here has no alpha info, use CGImageAlphaInfo.NoneSkipLast // to create bitmap graphics contexts without alpha info. let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpaceRef, bitmapInfo: CGBitmapInfo().rawValue | CGImageAlphaInfo.noneSkipLast.rawValue)! // Draw the image into the context and retrieve the new bitmap image without alpha context.draw(imageRef, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) let imageRefWithoutAlpha: CGImage = context.makeImage()! let imageWithoutAlpha: UIImage = UIImage(cgImage: imageRefWithoutAlpha, scale: image.scale, orientation: image.imageOrientation) return imageWithoutAlpha } func rectInsetsForRect(_ frame: CGRect, withRatio ratio: CGFloat) -> CGRect { let dx = frame.size.width * ratio let dy = frame.size.height * ratio var resultFrame = frame.insetBy(dx: dx, dy: dy) resultFrame = CGRect(x: round(resultFrame.origin.x), y: round(resultFrame.origin.y), width: round(resultFrame.size.width), height: round(resultFrame.size.height)) return resultFrame } func sizeThatFitsInSize(_ boundingSize: CGSize, initialSize size: CGSize) -> CGSize { // Compute the final size that fits in boundingSize in order to keep aspect ratio from initialSize. let fittingSize: CGSize let widthRatio = boundingSize.width / size.width let heightRatio = boundingSize.height / size.height if widthRatio < heightRatio { fittingSize = CGSize(width: boundingSize.width, height: floor(size.height * widthRatio)) } else { fittingSize = CGSize(width: floor(size.width * heightRatio), height: boundingSize.height) } return fittingSize } func focusViewControllerForView(_ mediaView: UIView) -> AKMediaViewerController? { let viewController: AKMediaViewerController let image: UIImage? var imageView: UIImageView? imageView = delegate?.mediaViewerManager?(self, imageViewForView: mediaView) if imageView == nil && mediaView is UIImageView { imageView = mediaView as? UIImageView } image = imageView?.image if (imageView == nil) || (image == nil) { return nil } guard let url = delegate?.mediaViewerManager(self, mediaURLForView: mediaView) else { print("Warning: url is nil") return nil } viewController = AKMediaViewerController(nibName: "AKMediaViewerController", bundle: Bundle.AKMediaFrameworkBundle()) installDefocusActionOnFocusViewController(viewController) viewController.titleLabel.text = delegate?.mediaViewerManager(self, titleForView: mediaView) viewController.mainImageView.image = image viewController.mainImageView.contentMode = imageView!.contentMode viewController.infiniteLoop = infiniteLoop let cachedImage = delegate?.mediaViewerManager?(self, cachedImageForView: mediaView) if cachedImage != nil { viewController.mainImageView.image = cachedImage return viewController } if isVideoURL(url) { viewController.showPlayerWithURL(url) } else { DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { self.loadImageFromURL(url, onImageView: viewController.mainImageView) DispatchQueue.main.async { viewController.mainImageView.isHidden = false } } } return viewController } func loadImageFromURL(_ url: URL, onImageView imageView: UIImageView) { let data: Data do { try data = Data(contentsOf: url, options: .dataReadingMapped) if let image = UIImage(data: data), let decImage = decodedImageWithImage(image) { DispatchQueue.main.async { imageView.image = decImage } } } catch { print("Warning: Unable to load image at %@. %@", url, error) } } func isVideoURL(_ url: URL?) -> Bool { guard let fileExtension = url?.pathExtension.lowercased() else { return false } return (fileExtension == "mp4" || fileExtension == "mov") } // MARK: - Focus/Defocus // Start the focus animation on the specified view. The focusing gesture must have been installed on this view. public func startFocusingView(_ mediaView: UIView) { var untransformedFinalImageFrame: CGRect = .zero guard let focusViewController = focusViewControllerForView(mediaView) else { return } self.focusViewController = focusViewController if self.defocusOnVerticalSwipe { installSwipeGestureOnFocusView() } // This should be called after swipe gesture is installed to make sure the nav bar doesn't hide before animation begins. delegate?.mediaViewerManagerWillAppear?(self) self.mediaView = mediaView let parentViewController: UIViewController = (delegate?.parentViewControllerForMediaViewerManager(self))! parentViewController.addChild(focusViewController) parentViewController.view.addSubview(focusViewController.view) focusViewController.view.frame = parentViewController.view.bounds mediaView.isHidden = true let imageView: UIImageView = focusViewController.mainImageView let center: CGPoint = (imageView.superview?.convert(mediaView.center, from: mediaView.superview))! imageView.center = center imageView.transform = mediaView.transform imageView.bounds = mediaView.bounds imageView.layer.cornerRadius = mediaView.layer.cornerRadius self.isZooming = true var finalImageFrame = self.delegate?.mediaViewerManager?(self, finalFrameForView: mediaView) ?? parentViewController.view.bounds if imageView.contentMode == .scaleAspectFill { let size: CGSize = sizeThatFitsInSize(finalImageFrame.size, initialSize: imageView.image!.size) finalImageFrame.size = size finalImageFrame.origin.x = (focusViewController.view.bounds.size.width - size.width) / 2 finalImageFrame.origin.y = (focusViewController.view.bounds.size.height - size.height) / 2 } UIView.animate(withDuration: self.animationDuration) { focusViewController.view.backgroundColor = self.backgroundColor focusViewController.beginAppearanceTransition(true, animated: true) } let duration = (elasticAnimation ? animationDuration * (1.0 - kAnimateElasticDurationRatio) : self.animationDuration) UIView.animate(withDuration: self.animationDuration, animations: { var frame: CGRect let initialFrame: CGRect let initialTransform: CGAffineTransform frame = finalImageFrame // Trick to keep the right animation on the image frame. // The image frame shoud animate from its current frame to a final frame. // The final frame is computed by taking care of a possible rotation regarding the current device orientation, done by calling updateOrientationAnimated. // As this method changes the image frame, it also replaces the current animation on the image view, which is not wanted. // Thus to recreate the right animation, the image frame is set back to its inital frame then to its final frame. // This very last frame operation recreates the right frame animation. initialTransform = imageView.transform imageView.transform = .identity initialFrame = imageView.frame imageView.frame = frame // This is the final image frame. No transform. untransformedFinalImageFrame = imageView.frame frame = self.elasticAnimation ? self.rectInsetsForRect(untransformedFinalImageFrame, withRatio: -kAnimateElasticSizeRatio) : untransformedFinalImageFrame // It must now be animated from its initial frame and transform. imageView.frame = initialFrame imageView.transform = initialTransform imageView.layer .removeAllAnimations() imageView.transform = .identity imageView.frame = frame if mediaView.layer.cornerRadius > 0 { self.animateCornerRadiusOfView(imageView, withDuration: duration, from: Float(mediaView.layer.cornerRadius), to: 0.0) } }, completion: { _ -> Void in UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in var frame: CGRect = untransformedFinalImageFrame frame = (self.elasticAnimation ? self.rectInsetsForRect(frame, withRatio: kAnimateElasticSizeRatio * kAnimateElasticSecondMoveSizeRatio) : frame) imageView.frame = frame }, completion: { _ -> Void in UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in var frame: CGRect = untransformedFinalImageFrame frame = (self.elasticAnimation ? self.rectInsetsForRect(frame, withRatio: -kAnimateElasticSizeRatio * kAnimateElasticThirdMoveSizeRatio) : frame) imageView.frame = frame }, completion: { _ -> Void in UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in imageView.frame = untransformedFinalImageFrame }, completion: { _ -> Void in self.focusViewController?.focusDidEndWithZoomEnabled(self.zoomEnabled) self.isZooming = false self.delegate?.mediaViewerManagerDidAppear?(self) }) }) }) }) } func animateCornerRadiusOfView(_ view: UIView, withDuration duration: TimeInterval, from initialValue: Float, to finalValue: Float) { let animation: CABasicAnimation = CABasicAnimation(keyPath: "cornerRadius") animation.timingFunction = CAMediaTimingFunction(name: .linear) animation.fromValue = initialValue animation.toValue = finalValue animation.duration = duration view.layer.cornerRadius = CGFloat(finalValue) view.layer.add(animation, forKey: "cornerRadius") } func updateAnimatedView(_ view: UIView, fromFrame initialFrame: CGRect, toFrame finalFrame: CGRect) { // On iOS8 previous animations are not replaced when a new one is defined with the same key. // Instead the new animation is added a number suffix on its key. // To prevent from having additive animations, previous animations are removed. // Note: We don't want to remove all animations as there might be some opacity animation that must remain. view.layer.removeAnimation(forKey: "bounds.size") view.layer.removeAnimation(forKey: "bounds.origin") view.layer.removeAnimation(forKey: "position") view.frame = initialFrame view.layer.removeAnimation(forKey: "bounds.size") view.layer.removeAnimation(forKey: "bounds.origin") view.layer.removeAnimation(forKey: "position") view.frame = finalFrame } func updateBoundsDuringAnimationWithElasticRatio(_ ratio: CGFloat) { if let playerView = focusViewController?.playerView { let initialFrame: CGRect = playerView.frame var frame: CGRect = mediaView.bounds frame = elasticAnimation ? rectInsetsForRect(frame, withRatio: ratio) : frame focusViewController?.mainImageView.bounds = frame updateAnimatedView(playerView, fromFrame: initialFrame, toFrame: frame) } } // Start the close animation on the current focused view. @objc public func endFocusing() { let contentView: UIView if isZooming && gestureDisabledDuringZooming { return } focusViewController?.defocusWillStart() contentView = self.focusViewController!.mainImageView UIView.animate(withDuration: self.animationDuration) { self.focusViewController?.view.backgroundColor = .clear } UIView.animate(withDuration: self.animationDuration / 2) { self.focusViewController?.beginAppearanceTransition(false, animated: true) } let duration = (self.elasticAnimation ? self.animationDuration * (1.0 - kAnimateElasticDurationRatio) : self.animationDuration) if self.mediaView.layer.cornerRadius > 0 { animateCornerRadiusOfView(contentView, withDuration: duration, from: 0.0, to: Float(self.mediaView.layer.cornerRadius)) } UIView.animate(withDuration: duration, animations: { () -> Void in self.delegate?.mediaViewerManagerWillDisappear?(self) self.focusViewController?.contentView.transform = .identity contentView.center = contentView.superview!.convert(self.mediaView.center, from: self.mediaView.superview) contentView.transform = self.mediaView.transform self.updateBoundsDuringAnimationWithElasticRatio(kAnimateElasticSizeRatio) }, completion: { _ -> Void in UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in self.updateBoundsDuringAnimationWithElasticRatio(-kAnimateElasticSizeRatio * kAnimateElasticSecondMoveSizeRatio) }, completion: { _ -> Void in UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in self.updateBoundsDuringAnimationWithElasticRatio(kAnimateElasticSizeRatio * kAnimateElasticThirdMoveSizeRatio) }, completion: { _ -> Void in UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in self.updateBoundsDuringAnimationWithElasticRatio(0.0) }, completion: { _ -> Void in self.mediaView.isHidden = false self.focusViewController?.view .removeFromSuperview() self.focusViewController?.removeFromParent() self.focusViewController = nil self.delegate?.mediaViewerManagerDidDisappear?(self) }) }) }) }) } // MARK: - Gestures @objc func handlePinchFocusGesture(_ gesture: UIPinchGestureRecognizer) { if gesture.state == .began && !isZooming && gesture.scale > 1 { startFocusingView(gesture.view!) } } @objc func handleFocusGesture(_ gesture: UIGestureRecognizer) { startFocusingView(gesture.view!) } @objc func handleDefocusGesture(_ gesture: UIGestureRecognizer) { endFocusing() } public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer is UIPinchGestureRecognizer { return focusOnPinch } return true } // MARK: - Dismiss on swipe func installSwipeGestureOnFocusView() { var swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleDefocusBySwipeGesture(_:))) swipeGesture.direction = .up focusViewController?.view.addGestureRecognizer(swipeGesture) swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleDefocusBySwipeGesture(_:))) swipeGesture.direction = .down focusViewController?.view.addGestureRecognizer(swipeGesture) focusViewController?.view.isUserInteractionEnabled = true } @objc func handleDefocusBySwipeGesture(_ gesture: UISwipeGestureRecognizer) { let contentView: UIView let duration = self.animationDuration focusViewController?.defocusWillStart() let offset = (gesture.direction == UISwipeGestureRecognizer.Direction.up ? -kSwipeOffset : kSwipeOffset) contentView = focusViewController!.mainImageView UIView.animate(withDuration: duration) { self.focusViewController?.view.backgroundColor = .clear } UIView.animate(withDuration: duration / 2) { self.focusViewController?.beginAppearanceTransition(false, animated: true) } UIView.animate(withDuration: 0.4 * duration, animations: { self.delegate?.mediaViewerManagerWillDisappear?(self) self.focusViewController?.contentView.transform = .identity contentView.center = CGPoint(x: self.focusViewController!.view.center.x, y: self.focusViewController!.view.center.y + offset) }, completion: { _ -> Void in UIView.animate(withDuration: 0.6 * duration, animations: { contentView.center = contentView.superview!.convert(self.mediaView.center, from: self.mediaView.superview) contentView.transform = self.mediaView.transform self.updateBoundsDuringAnimationWithElasticRatio(0) }, completion: { _ -> Void in self.mediaView.isHidden = false self.focusViewController?.view.removeFromSuperview() self.focusViewController?.removeFromParent() self.focusViewController = nil self.delegate?.mediaViewerManagerDidDisappear?(self) }) }) } // MARK: - Customization // Set minimal customization to default "Done" button. (Text and Color) public func setDefaultDoneButtonText(_ text: String, withColor color: UIColor) { (topAccessoryController as? AKMediaFocusBasicToolbarController)?.doneButton.setTitle(text, for: .normal) (topAccessoryController as? AKMediaFocusBasicToolbarController)?.doneButton.setTitleColor(color, for: .normal) } }
2fea28a62c5b15188aa31c221656873a
45.236884
177
0.65093
false
false
false
false
dehesa/Utilities
refs/heads/master
Sources/common/swift/Optional.swift
mit
2
public extension Optional { /// Executes the side-effect given as a parameter. /// - parameter transform: Closure executing a side-effect (it will not modify the value wrapped in the optional). This closure will get executed *if* the optional is not `nil`. /// - parameter wrapped: Value wrapped within the optional. public func on(_ transform: (_ wrapped: Wrapped)->Void) { guard case .some(let value) = self else { return } transform(value) } } public extension Optional where Wrapped: MutableCollection & RandomAccessCollection & RangeReplaceableCollection, Wrapped.Iterator.Element: Comparable { /// Appends an element to an optional collection. If the optional is `nil`, a collection is created holding the given element. /// /// Before addition, the array is checked for element existance. If it already exists, no operation is performed. /// - parameter newElement: Element to be added to the collection wrapped within the optional. public mutating func append(_ newElement: Wrapped.Iterator.Element) { guard case .some(var result) = self else { self = .some(Wrapped([newElement])) return } guard !result.contains(newElement) else { return } result.append(newElement) self = .some(result) } /// Appends the elements of an optional collection to another optional collection. If the optional is `nil` and the given collection is not `nil`, a collection is created holding the given elements. /// /// Before addition the array is checked for element existance. If it already exists, no operation is performed. /// - parameter newElements: Collection to be added to the collection wrapped within the optional. public mutating func append(_ newElements: Wrapped) { guard case .some(var result) = self else { return self = newElements } for element in newElements { guard !result.contains(element) else { continue } result.append(element) } self = result } }
26234bc45e05aaa099767df669077d5c
48.046512
202
0.673779
false
false
false
false
antonyharfield/grader
refs/heads/master
Sources/App/Common/Extensions/PFColorHash.swift
mit
1
// // PFColorHash.swift // PFColorHash // // Created by Cee on 20/08/2015. // Copyright (c) 2015 Cee. All rights reserved. // import Foundation open class PFColorHash { lazy var lightness: [Double] = [0.35, 0.5, 0.65] lazy var saturation: [Double] = [0.35, 0.5, 0.65] lazy var hash = { (_ str: String) -> Int64 in let seed1: Int64 = 131 let seed2: Int64 = 137 var ret: Int64 = 0 let hashString = str + "x" var constantInt: Int64 = 9007199254740991 // pow(2, 53) - 1 let maxSafeInt: Int64 = constantInt / seed2 for element in hashString.characters { if (ret > maxSafeInt) { ret = ret / seed2 } ret = ret * seed1 + Int64(element.unicodeScalarCodePoint()) } return ret } // MARK: Init Methods init() {} init(lightness: [Double]) { self.lightness = lightness } init(saturation: [Double]) { self.saturation = saturation } init(lightness: [Double], saturation: [Double]) { self.lightness = lightness self.saturation = saturation } init(hash: @escaping (String) -> Int64) { self.hash = hash } // MARK: Public Methods final func hsl(_ str: String) -> (h: Double, s: Double, l: Double) { var hashValue: Int64 = hash(str) let h = hashValue % 359 hashValue = hashValue / 360 var count: Int64 = Int64(saturation.count) var index = Int(hashValue % count) let s = saturation[index] hashValue = hashValue / count count = Int64(lightness.count) index = Int(hashValue % count) let l = lightness[index] return (Double(h), Double(s), Double(l)) } final func rgb(_ str: String) -> (r: Int, g: Int, b: Int) { let hslValue = hsl(str) return hsl2rgb(hslValue.h, s: hslValue.s, l: hslValue.l) } final func hex(_ str: String) -> String { let rgbValue = rgb(str) return rgb2hex(rgbValue.r, g: rgbValue.g, b: rgbValue.b) } // MARK: Private Methods fileprivate final func hsl2rgb(_ h: Double, s: Double, l:Double) -> (r: Int, g: Int, b: Int) { let hue = h / 360 let q = l < 0.5 ? l * (1 + s) :l + s - l * s let p = 2 * l - q let array = [hue + 1/3, hue, hue - 1/3].map({ (color: Double) -> Int in var ret = color if (ret < 0) { ret = ret + 1 } if (ret > 1) { ret = ret - 1 } if (ret < 1 / 6) { ret = p + (q - p) * 6 * ret } else if (ret < 0.5) { ret = q } else if (ret < 2 / 3) { ret = p + (q - p) * 6 * (2 / 3 - ret) } else { ret = p } return Int(ret * 255) } ) return (array[0], array[1], array[2]) } fileprivate final func rgb2hex(_ r: Int, g: Int, b: Int) -> String { return String(format:"%X", r) + String(format:"%X", g) + String(format:"%X", b) } } // MARK: Character To ASCII extension Character { func unicodeScalarCodePoint() -> Int { let characterString = String(self) let scalars = characterString.unicodeScalars return Int(scalars[scalars.startIndex].value) } }
93986eb63e544e3155d85a78364ee26c
26.856
98
0.494543
false
false
false
false
mLewisLogic/codepath-assignment2
refs/heads/master
yelp/yelp/Controllers/RestaurantTableViewCell.swift
mit
1
// // RestaurantTableViewCell.swift // yelp // // Created by Michael Lewis on 2/14/15. // Copyright (c) 2015 Machel. All rights reserved. // import UIKit class RestaurantTableViewCell: UITableViewCell { @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var starsImageView: UIImageView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var numReviewsLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! var restaurantInfo: NSDictionary? override func awakeFromNib() { super.awakeFromNib() // Initialization code photoImageView.contentMode = .ScaleAspectFit } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setRestaurantInfo(info: NSDictionary) { restaurantInfo = info reloadData() } private func reloadData() { if let info = restaurantInfo { if let imageUrl = info["image_url"] as? String { photoImageView.setImageWithURL(NSURL(string: imageUrl)) } if let name = info["name"] as? String { nameLabel.text = name } if let distance = info["distance"] as? Double { let distance_in_km = distance / 1000.0 let distance_in_mi = distance_in_km * 0.621371 // Start wide, and narrow the formatting based upon distance var format_string = "%.0f mi" if distance_in_mi < 10.0 { format_string = "%.1f mi" } if distance_in_mi < 0.2 { format_string = "%.2f mi" } distanceLabel.text = String(format: format_string, distance_in_mi) } if let starsUrl = info["rating_img_url"] as? String { starsImageView.setImageWithURL(NSURL(string: starsUrl)) } if let location = info["location"] as? NSDictionary { if let address = location["display_address"] as? NSArray { addressLabel.text = "\(address[0]) \(address[1])" } } if let reviewCount = info["review_count"] as? Int { numReviewsLabel.text = "\(reviewCount) reviews" } if let categories = info["categories"] as? Array<NSArray> { // Each category is actually a tuple. Grab the first of each. categoriesLabel.text = ", ".join( categories.map { (var cat) -> String in return cat[0] as String } ) as String } } } }
492d342df179322a0d919501ed12cdfd
27.406593
74
0.632495
false
false
false
false
alltheflow/iCopyPasta
refs/heads/master
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift
mit
2
// // GitHubSearchRepositoriesViewController.swift // RxExample // // Created by Yoshinori Sano on 9/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegate { static let startLoadingOffset: CGFloat = 20.0 static func isNearTheBottomEdge(contentOffset: CGPoint, _ tableView: UITableView) -> Bool { return contentOffset.y + tableView.frame.size.height + startLoadingOffset > tableView.contentSize.height } @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Repository>>() override func viewDidLoad() { super.viewDidLoad() let tableView = self.tableView let searchBar = self.searchBar dataSource.cellFactory = { (tv, ip, repository: Repository) in let cell = tv.dequeueReusableCellWithIdentifier("Cell")! cell.textLabel?.text = repository.name cell.detailTextLabel?.text = repository.url return cell } dataSource.titleForHeaderInSection = { [unowned dataSource] sectionIndex in let section = dataSource.sectionAtIndex(sectionIndex) return section.items.count > 0 ? "Repositories (\(section.items.count))" : "No repositories found" } let loadNextPageTrigger = tableView.rx_contentOffset .flatMap { offset in GitHubSearchRepositoriesViewController.isNearTheBottomEdge(offset, tableView) ? Observable.just() : Observable.empty() } let searchResult = searchBar.rx_text.asDriver() .throttle(0.3) .distinctUntilChanged() .flatMapLatest { query -> Driver<RepositoriesState> in if query.isEmpty { return Driver.just(RepositoriesState.empty) } else { return GitHubSearchRepositoriesAPI.sharedAPI.search(query, loadNextPageTrigger: loadNextPageTrigger) .asDriver(onErrorJustReturn: RepositoriesState.empty) } } searchResult .map { $0.serviceState } .drive(navigationController!.rx_serviceState) .addDisposableTo(disposeBag) searchResult .map { [SectionModel(model: "Repositories", items: $0.repositories)] } .drive(tableView.rx_itemsWithDataSource(dataSource)) .addDisposableTo(disposeBag) searchResult .filter { $0.limitExceeded } .driveNext { n in showAlert("Exceeded limit of 10 non authenticated requests per minute for GitHub API. Please wait a minute. :(\nhttps://developer.github.com/v3/#rate-limiting") } .addDisposableTo(disposeBag) // dismiss keyboard on scroll tableView.rx_contentOffset .subscribe { _ in if searchBar.isFirstResponder() { _ = searchBar.resignFirstResponder() } } .addDisposableTo(disposeBag) // so normal delegate customization can also be used tableView.rx_setDelegate(self) .addDisposableTo(disposeBag) // activity indicator in status bar // { GitHubSearchRepositoriesAPI.sharedAPI.activityIndicator .driveNext { active in UIApplication.sharedApplication().networkActivityIndicatorVisible = active } .addDisposableTo(disposeBag) // } } // MARK: Table view delegate func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } deinit { // I know, I know, this isn't a good place of truth, but it's no self.navigationController?.navigationBar.backgroundColor = nil } }
bcadb70c48c1228708595daebfd4d40b
34.417391
177
0.627547
false
false
false
false
gyro-n/PaymentsIos
refs/heads/master
GyronPayments/Classes/Resources/SubscriptionResource.swift
mit
1
// // SubscriptionResource.swift // GyronPayments // // Created by Ye David on 11/4/16. // Copyright © 2016 gyron. All rights reserved. // import Foundation import PromiseKit /** SubscriptionListRequestData is a class that defines the request pararmeters that is used to get a list of subscription objects. */ open class SubscriptionListRequestData: ExtendedAnyObject, RequestDataDelegate, SortRequestDelegate, PaginationRequestDelegate { /** The sort order for the list (ASC or DESC) */ public var sortOrder: String? /** The property name to sort by */ public var sortBy: String? /** The desired page no */ public var page: Int? /** The desired page size of the returning data set */ public var pageSize: Int? /** Search for ids or values in the metadata field. */ public var search: String? /** Filter by subscription status. One of (unverified, cancelled, unpaid, or current) */ public var status: SubscriptionStatus? /** Filter by processing mode. One of (live or test) */ public var mode: ProcessingMode? public init(sortOrder: String? = nil, sortBy: String? = "created_on", page: Int? = nil, pageSize: Int? = nil, search: String? = nil, status: SubscriptionStatus? = nil, mode: ProcessingMode? = nil) { self.sortOrder = sortOrder self.sortBy = sortBy self.page = page self.pageSize = pageSize self.search = search self.status = status self.mode = mode } public func convertToMap() -> RequestData { return convertToRequestData() } } /** SubscriptionCreateRequestData is a class that defines the request pararmeters that is used to create a subscription. */ open class SubscriptionCreateRequestData: ExtendedAnyObject, RequestDataDelegate { public var transactionTokenId: String public var amount: Int public var currency: String public var period: String public var metadata: Metadata? public init(transactionTokenId: String, amount: Int, currency: String, period: SubscriptionPeriod, metadata: Metadata? = nil) { self.transactionTokenId = transactionTokenId self.amount = amount self.currency = currency self.period = period.rawValue self.metadata = metadata } public func convertToMap() -> RequestData { return convertToRequestData() } } /** SubscriptionUpdateRequestData is a class that defines the request pararmeters that is used to update a subscription. */ open class SubscriptionUpdateRequestData: ExtendedAnyObject, RequestDataDelegate { public var transactionTokenId: String? public var amount: Int? public var metadata: Metadata? public init(transactionTokenId: String? = nil, amount: Int? = nil, metadata: Metadata? = nil) { self.transactionTokenId = transactionTokenId self.amount = amount self.metadata = metadata } public func convertToMap() -> RequestData { return convertToRequestData() } } /** The SubscriptionResource class is used to perform operations related to the management of subscriptions. */ open class SubscriptionResource: BaseResource { /** The base root path for the request url */ let basePath: String = "/stores/:storeId/subscriptions" /** The parameters that are requried in order to make the request for a particular route */ public let requiredParams: [String] = ["transaction_token_id", "amount", "currency", "period"] ///--------------------------- /// @name Routes ///--------------------------- /** Lists the subscriptions available. @param callback the callback function to be called when the request is completed @return A promise object with the Subscriptions list */ public func list(callback: ResponseCallback<Subscriptions>?) -> Promise<Subscriptions> { let routePath: String = "/subscriptions" return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: routePath, pathParams: nil, data: nil, callback: callback) } /** Lists the subscriptions available for a store id. @param storeId the store id @param callback the callback function to be called when the request is completed @return A promise object with the Subscriptions list */ public func listByStore(storeId: String, data: SubscriptionListRequestData?, callback: ResponseCallback<Subscriptions>?) -> Promise<Subscriptions> { let routePath: String = self.getStoresRoutePath(storeId: storeId, id: nil, basePath: basePath) return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: routePath, pathParams: nil, data: data, callback: callback) } /** Gets a subscription based on the store and subscription ids. @param storeId the store id @param id the subscription id @param callback the callback function to be called when the request is completed @return A promise object with the Subscription object */ public func getByStore(storeId: String, id: String, callback: ResponseCallback<Subscription>?) -> Promise<Subscription> { let routePath: String = self.getStoresRoutePath(storeId: storeId, id: id, basePath: basePath) return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: routePath, pathParams: nil, data: nil, callback: callback) } /** Creates a subscription. @param data the parameters to be passed to the request @param callback the callback function to be called when the request is completed @return A promise object with the Subscription object */ public func create(data: SubscriptionCreateRequestData?, callback: ResponseCallback<Subscription>?) -> Promise<Subscription> { let routePath: String = "/subscriptions" return self.runRoute(requiredParams: requiredParams, method: HttpProtocol.HTTPMethod.POST, path: routePath, pathParams: nil, data: data, callback: callback) } /** Updates a subscription. @param storeId the store id @param id the subscription id @param data the parameters to be passed to the request @param callback the callback function to be called when the request is completed @return A promise object with the Subscription object */ public func update(storeId: String, id: String, data: SubscriptionUpdateRequestData?, callback: ResponseCallback<Subscription>?) -> Promise<Subscription> { let routePath: String = self.getStoresRoutePath(storeId: storeId, id: id, basePath: basePath) return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.PATCH, path: routePath, pathParams: nil, data: data, callback: callback) } /** Deletes a subscription. @param storeId the store id @param id the subscription id @param data the parameters to be passed to the request @param callback the callback function to be called when the request is completed @return A promise object with the Subscription object (But would be empty regardless of outcome) */ public func delete(storeId: String, id: String, callback: ResponseCallback<Subscription>?) -> Promise<Subscription> { let routePath: String = self.getStoresRoutePath(storeId: storeId, id: id, basePath: basePath) return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.DELETE, path: routePath, pathParams: nil, data: nil, callback: callback) } /** Gets a list of charges for a subscription. @param storeId the store id @param id the subscription id @param data the parameters to be passed to the request @param callback the callback function to be called when the request is completed @return A promise object with the Charges object */ public func getCharges(storeId: String, id: String, data: ChargeListRequestData?, callback: ResponseCallback<Charges>?) -> Promise<Charges> { let routePath: String = self.getStoresRoutePath(storeId:storeId, id: id, basePath: basePath).appending("/charges") return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: routePath, pathParams: nil, data: data, callback: callback) } public func poll(storeId: String, id: String, callback: ResponseCallback<Subscription>?) -> Promise<Subscription> { let routePath: String = self.getRoutePath(id: id, basePath: basePath, pathParams: [(":storeId", storeId)]) let condition: LongPollCondition<Subscription> = { d in d.status != SubscriptionStatus.unverified } return self.performPoll(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: routePath, pathParams: nil, data: nil, condition: condition, callback: callback) } }
b18c7edae038667adc9c882638d7e4bf
37.690083
164
0.66389
false
false
false
false
DTVD/APIKitExt
refs/heads/master
Carthage/Checkouts/APIKit/Sources/APIKit/BodyParameters/Data+InputStream.swift
mit
4
import Foundation enum InputStreamError: Error { case invalidDataCapacity(Int) case unreadableStream(InputStream) } extension Data { init(inputStream: InputStream, capacity: Int = Int(UInt16.max)) throws { var data = Data(capacity: capacity) let bufferSize = Swift.min(Int(UInt16.max), capacity) let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) var readSize: Int repeat { readSize = inputStream.read(buffer, maxLength: bufferSize) switch readSize { case let x where x > 0: data.append(buffer, count: readSize) case let x where x < 0: throw InputStreamError.unreadableStream(inputStream) default: break } } while readSize > 0 buffer.deallocate(capacity: bufferSize) self.init(data) } }
b11b334a4995d648271ec1adad0fe234
24.5
79
0.604575
false
false
false
false
artyom-stv/TextInputKit
refs/heads/develop
Example/Example/macOS/Code/TestFormatterViewController.swift
mit
1
// // TestFormatterViewController.swift // Example // // Created by Artem Starosvetskiy on 20/11/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // import Cocoa import Foundation final class TestFormatterViewController: NSViewController { struct Configuration { let title: String let formatter: Formatter } @IBOutlet private var titleLabel: NSTextField! @IBOutlet private var textField: NSTextField! @IBOutlet private var valueLabel: NSTextField! func configure(_ config: Configuration) { self.config = config } fileprivate var config: Configuration! } extension TestFormatterViewController { override func viewDidLoad() { super.viewDidLoad() guard config != nil else { fatalError("\(String(describing: type(of: self))) wasn't configured.") } titleLabel.stringValue = config.title textField.formatter = config.formatter updateStringValue() } override var representedObject: Any? { get { return textField?.objectValue } set { textField?.objectValue = newValue } } } extension TestFormatterViewController { func controlTextDidChange(_ notification: Notification) { let control = notification.object as! NSControl if control === textField { updateStringValue() } } } extension TestFormatterViewController: NSTextFieldDelegate { func control(_ control: NSControl, didFailToFormatString string: String, errorDescription error: String?) -> Bool { if control === textField { // TODO: Implement. } return true } func control(_ control: NSControl, didFailToValidatePartialString string: String, errorDescription error: String?) { if control === textField { // TODO: Implement. } } } private extension TestFormatterViewController { func updateStringValue() { let stringValue: String if let string = config.formatter.string(for: textField.objectValue) { stringValue = string } else { stringValue = "" } valueLabel.stringValue = stringValue } }
5cd60221c677ea90e38312ab475488c5
23.311828
120
0.639982
false
true
false
false
xu6148152/binea_project_for_ios
refs/heads/master
SlidingMenuLikeQQ/SlidingMenuLikeQQ/AppDelegate.swift
mit
1
// // AppDelegate.swift // SlidingMenuLikeQQ // // Created by Binea Xu on 9/14/15. // Copyright © 2015 Binea Xu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. application.statusBarStyle = UIStatusBarStyle.LightContent let navigationBarAppearance = UINavigationBar.appearance() navigationBarAppearance.translucent = false navigationBarAppearance.barTintColor = UIColor(hex: 0x25b6ed) navigationBarAppearance.tintColor = UIColor.whiteColor() navigationBarAppearance.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] 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:. } }
72eb3ab2d744086d646eb64ae6b1883c
47.018519
285
0.75241
false
false
false
false
SwiftyVK/SwiftyVK
refs/heads/master
Library/Sources/LongPoll/LongPollEvent.swift
mit
2
import Foundation /// Represents LongPoll event. More info - https://vk.com/dev/using_longpoll public enum LongPollEvent { case forcedStop case historyMayBeLost case type1(data: Data) case type2(data: Data) case type3(data: Data) case type4(data: Data) case type5(data: Data) case type6(data: Data) case type7(data: Data) case type8(data: Data) case type9(data: Data) case type10(data: Data) case type11(data: Data) case type12(data: Data) case type13(data: Data) case type14(data: Data) case type51(data: Data) case type52(data: Data) case type61(data: Data) case type62(data: Data) case type70(data: Data) case type80(data: Data) case type114(data: Data) var data: Data? { return associatedValue(of: self) } // swiftlint:disable cyclomatic_complexity next init?(json: JSON) { guard let type = json.int("0"), let updates = (json.value as? [Any])?.dropFirst().toArray(), let updatesData = JSON(value: updates).data("*") else { return nil } switch type { case 1: self = .type1(data: updatesData) case 2: self = .type2(data: updatesData) case 3: self = .type3(data: updatesData) case 4: self = .type4(data: updatesData) case 6: self = .type6(data: updatesData) case 5: self = .type5(data: updatesData) case 7: self = .type7(data: updatesData) case 8: self = .type8(data: updatesData) case 9: self = .type9(data: updatesData) case 10: self = .type10(data: updatesData) case 11: self = .type11(data: updatesData) case 12: self = .type12(data: updatesData) case 13: self = .type13(data: updatesData) case 14: self = .type14(data: updatesData) case 51: self = .type51(data: updatesData) case 52: self = .type52(data: updatesData) case 61: self = .type61(data: updatesData) case 62: self = .type62(data: updatesData) case 70: self = .type70(data: updatesData) case 80: self = .type80(data: updatesData) case 114: self = .type114(data: updatesData) default: return nil } } }
c819b1d920653775e9b94b79ee6a7dff
27.393258
76
0.537396
false
false
false
false
jindulys/Leetcode_Solutions_Swift
refs/heads/master
Sources/DynamicProgramming/53_MaximumSubarry.swift
mit
1
// // 53_MaximumSubarry.swift // LeetcodeSwift // // Created by yansong li on 2016-09-14. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:53 Maximum Subarray URL: https://leetcode.com/problems/maximum-subarray/ Space: O(n) Time: O(n) */ class MaximumSubarray_Solution { func maxSubArray(_ nums: [Int]) -> Int { guard nums.count > 1 else { if nums.count == 1 { return nums[0] } return 0 } var maxSums = Array(repeating: 0, count: nums.count) maxSums[0] = nums[0] var ret = nums[0] for i in 1..<nums.count { maxSums[i] = (maxSums[i - 1] > 0 ? maxSums[i - 1] : 0) + nums[i] ret = max(ret, maxSums[i]) } return ret } }
fafc921211d772a370e8fcdada23f5d2
20.057143
70
0.588874
false
false
false
false
palasjir/keyboard-switch-notifier
refs/heads/master
Keyboard Switch Notifier/InputSourceObserver.swift
mit
1
// // InputSourceObserver.swift // Keyboard Switch Notifier // // Created by Jiří Palas on 07.06.17. // Copyright © 2017 Jiří Palas. All rights reserved. // import Cocoa class InputSourceObserver: NSObject, NSUserNotificationCenterDelegate { let name = Notification.Name("NSTextInputContextKeyboardSelectionDidChangeNotification") let nc = NotificationCenter.default let unc = NSUserNotificationCenter.default override init() { super.init() nc.addObserver( self, selector:#selector(handleNotif(sender:)), name: name, object: nil) unc.delegate = self } func handleNotif(sender: AnyObject) { let ins = InputSource() let notif = KeyboardChangedNotification(name: ins.getName(), icon: ins.getIcon()) unc.deliver(notif) } func remove() { nc.removeObserver(self) } func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool { return true } }
faf99dfd1acc9a7100edca2aa9e35c4b
25.560976
125
0.645546
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGraphics/ColorSpace/ColorSpaceBase/ICC/iccProfile/iccType/iccMatrix.swift
mit
1
// // iccMatrix.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // struct iccMatrix3x3: ByteCodable { var e00: Fixed16Number<BEInt32> var e01: Fixed16Number<BEInt32> var e02: Fixed16Number<BEInt32> var e10: Fixed16Number<BEInt32> var e11: Fixed16Number<BEInt32> var e12: Fixed16Number<BEInt32> var e20: Fixed16Number<BEInt32> var e21: Fixed16Number<BEInt32> var e22: Fixed16Number<BEInt32> init(_ matrix: Matrix) { self.e00 = Fixed16Number(matrix.a) self.e01 = Fixed16Number(matrix.b) self.e02 = Fixed16Number(matrix.c) self.e10 = Fixed16Number(matrix.e) self.e11 = Fixed16Number(matrix.f) self.e12 = Fixed16Number(matrix.g) self.e20 = Fixed16Number(matrix.i) self.e21 = Fixed16Number(matrix.j) self.e22 = Fixed16Number(matrix.k) } var matrix: Matrix { return Matrix(a: e00.representingValue, b: e01.representingValue, c: e02.representingValue, d: 0, e: e10.representingValue, f: e11.representingValue, g: e12.representingValue, h: 0, i: e20.representingValue, j: e21.representingValue, k: e22.representingValue, l: 0) } init(from data: inout Data) throws { self.e00 = try data.decode(Fixed16Number.self) self.e01 = try data.decode(Fixed16Number.self) self.e02 = try data.decode(Fixed16Number.self) self.e10 = try data.decode(Fixed16Number.self) self.e11 = try data.decode(Fixed16Number.self) self.e12 = try data.decode(Fixed16Number.self) self.e20 = try data.decode(Fixed16Number.self) self.e21 = try data.decode(Fixed16Number.self) self.e22 = try data.decode(Fixed16Number.self) } func write<Target: ByteOutputStream>(to stream: inout Target) { stream.encode(e00) stream.encode(e01) stream.encode(e02) stream.encode(e10) stream.encode(e11) stream.encode(e12) stream.encode(e20) stream.encode(e21) stream.encode(e22) } } struct iccMatrix3x4: ByteCodable { var m: iccMatrix3x3 var e03: Fixed16Number<BEInt32> var e13: Fixed16Number<BEInt32> var e23: Fixed16Number<BEInt32> init(_ matrix: Matrix) { self.m = iccMatrix3x3(matrix) self.e03 = Fixed16Number(matrix.d) self.e13 = Fixed16Number(matrix.h) self.e23 = Fixed16Number(matrix.l) } var matrix: Matrix { return Matrix(a: m.e00.representingValue, b: m.e01.representingValue, c: m.e02.representingValue, d: e03.representingValue, e: m.e10.representingValue, f: m.e11.representingValue, g: m.e12.representingValue, h: e13.representingValue, i: m.e20.representingValue, j: m.e21.representingValue, k: m.e22.representingValue, l: e23.representingValue) } init(from data: inout Data) throws { self.m = try data.decode(iccMatrix3x3.self) self.e03 = try data.decode(Fixed16Number.self) self.e13 = try data.decode(Fixed16Number.self) self.e23 = try data.decode(Fixed16Number.self) } func write<Target: ByteOutputStream>(to stream: inout Target) { stream.encode(m) stream.encode(e03) stream.encode(e13) stream.encode(e23) } }
702fbf3d712b927fd708a53d3c881df4
38.069565
131
0.66726
false
false
false
false
barteljan/VISPER
refs/heads/master
VISPER/Classes/Deprecated/DeprecatedVISPERFeatureObserver.swift
mit
1
// // DeprecatedVISPERFeatureObserver.swift // // Created by bartel on 28.12.17. // import Foundation import VISPER_Swift import VISPER_Core import VISPER_Objc import VISPER_Wireframe open class DeprecatedVISPERFeatureObserver: WireframeFeatureObserver { let wireframe: Wireframe let commandBus: VISPERCommandBus public init(wireframe: Wireframe, commandBus: VISPERCommandBus){ self.wireframe = wireframe self.commandBus = commandBus } public func featureAdded(application: WireframeApp, feature: Feature) throws { guard let visperFeature = feature as? DeprecatedVISPERFeatureWrapper else { return } let wireFrameObjc = WireframeObjc(wireframe: self.wireframe) let visperWireframe = VISPERWireframe(wireframe: wireFrameObjc) if let bootstrapWireframe = visperFeature.visperFeature.bootstrapWireframe { bootstrapWireframe(visperWireframe,self.commandBus) } if let routepatterns = visperFeature.visperFeature.routePatterns { for routepattern in routepatterns() { if let pattern = routepattern as? String { do { try self.wireframe.add(routePattern: pattern) } catch let error { print("Error: \(error)") } } } } } }
3a5c18358a8980f082df5a4e89ef345e
27.846154
84
0.600667
false
false
false
false
ikait/KernLabel
refs/heads/master
KernLabelSample/KernLabelSample/ViewController.swift
mit
1
// // ViewController.swift // KernLabelSample // // Created by Taishi Ikai on 2016/05/28. // Copyright © 2016年 Taishi Ikai. All rights reserved. // import UIKit import KernLabel private let kLabelHeight: CGFloat = 130 class ViewController: TableViewController { var uiLabel = UILabel() var kernLabel = KernLabel() var text = "" var numberOfLines = 0 var textAlignment = NSTextAlignment.left var kerningMode = KernLabelKerningMode.normal var kerningModeSegmentedControl = UISegmentedControl() var alignmentSegmentedControl = UISegmentedControl() override func viewDidLoad() { super.viewDidLoad() self.prepareText() self.prepareAlignmentSegmentedControl() self.prepareKerningModeSegmentedControl() } fileprivate func prepareText() { self.text = "" self.text += "【行頭つめ】あいう「えお」「か」、!?\n" self.text += "(連続)する約物「:」!「」、。;折り返し「1」(2)〈3〉【4】[5]《6》\n" self.text += "英数123abc@“ん”〘〛{[』〕…【括弧)終\n" self.text += "2016年1月1日(金)" } fileprivate func prepareUILabel(with cell: UITableViewCell) { self.uiLabel.removeFromSuperview() if #available(iOS 9.0, *) { self.uiLabel.frame = cell.readableContentGuide.layoutFrame self.uiLabel.frame.origin.y = 0 self.uiLabel.frame.size.height = kLabelHeight } else { self.uiLabel.frame = cell.bounds.insetBy(dx: 10, dy: 0) } self.uiLabel.frame.size.height = kLabelHeight self.uiLabel.text = self.text self.uiLabel.backgroundColor = UIColor.white self.uiLabel.numberOfLines = 0 self.uiLabel.textAlignment = self.textAlignment cell.contentView.addSubview(self.uiLabel) } fileprivate func prepareKernLabel(with cell: UITableViewCell) { self.kernLabel.removeFromSuperview() if #available(iOS 9.0, *) { self.kernLabel.frame = cell.readableContentGuide.layoutFrame self.kernLabel.frame.origin.y = 0 } else { self.kernLabel.frame = (cell.bounds).insetBy(dx: 10, dy: 0) } self.kernLabel.frame.size.height = kLabelHeight self.kernLabel.text = self.text self.kernLabel.backgroundColor = UIColor.white self.kernLabel.numberOfLines = 0 self.kernLabel.textAlignment = self.textAlignment self.kernLabel.kerningMode = self.kerningMode cell.contentView.addSubview(self.kernLabel) } fileprivate func prepareAlignmentSegmentedControl() { self.alignmentSegmentedControl = UISegmentedControl(items: [ "Left", "Center", "Right", "Justified" ]) self.alignmentSegmentedControl.addTarget( self, action: #selector(ViewController.handlerAlignmentSegmentedControl(_:)), for: .valueChanged) self.alignmentSegmentedControl.selectedSegmentIndex = 0 } fileprivate func prepareKerningModeSegmentedControl() { self.kerningModeSegmentedControl = UISegmentedControl(items: [ "None", "Minimum", "Normal", "All" ]) self.kerningModeSegmentedControl.addTarget( self, action: #selector(ViewController.handlerKerningModeSegmentedControl(_:)), for: .valueChanged) self.kerningModeSegmentedControl.selectedSegmentIndex = 2 } @objc fileprivate func handlerAlignmentSegmentedControl(_ segmentedControl: UISegmentedControl) { self.textAlignment = { switch segmentedControl.selectedSegmentIndex { case 0: return .left case 1: return .center case 2: return .right case 3: return .justified default: return .left } }() self.tableView.reloadData() } @objc fileprivate func handlerKerningModeSegmentedControl(_ segmentedControl: UISegmentedControl) { self.kerningMode = { switch segmentedControl.selectedSegmentIndex { case 0: return .none case 1: return .minimum case 2: return .normal case 3: return .all default: return .none } }() self.tableView.reloadData() } } // // MARK: - UITableViewDataSource // extension ViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "\(KernLabel.self)" case 1: return "\(UILabel.self)" case 2: return "Preferences" default: return "" } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 2 ? 2 : 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return (indexPath as NSIndexPath).section == 2 ? UITableViewAutomaticDimension : kLabelHeight } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "UITableViewCell") cell.bounds.size.width = tableView.bounds.width switch (indexPath as NSIndexPath).section { case 0: self.prepareKernLabel(with: cell) case 1: self.prepareUILabel(with: cell) case 2: switch (indexPath as NSIndexPath).row { case 0: cell.textLabel?.text = "Alignment" cell.accessoryView = self.alignmentSegmentedControl cell.accessoryView?.sizeToFit() case 1: cell.textLabel?.text = "Kerning parentheses" cell.detailTextLabel?.text = "Only KernLabel" cell.accessoryView = self.kerningModeSegmentedControl cell.accessoryView?.sizeToFit() default: break } cell.selectionStyle = .none default: break } return cell } }
db220ac3d68824230ace4c2b06d6b422
33
109
0.62054
false
false
false
false
Allow2CEO/browser-ios
refs/heads/development
Shared/Functions.swift
mpl-2.0
5
/* 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 SwiftyJSON // Pipelining. precedencegroup PipelinePrecedence { associativity: left } infix operator |> : PipelinePrecedence public func |> <T, U>(x: T, f: (T) -> U) -> U { return f(x) } // Basic currying. public func curry<A, B>(_ f: @escaping (A) -> B) -> (A) -> B { return { a in return f(a) } } public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C { return { a in return { b in return f(a, b) } } } public func curry<A, B, C, D>(_ f: @escaping (A, B, C) -> D) -> (A) -> (B) -> (C) -> D { return { a in return { b in return { c in return f(a, b, c) } } } } public func curry<A, B, C, D, E>(_ f: @escaping (A, B, C, D) -> E) -> (A, B, C) -> (D) -> E { return { (a, b, c) in return { d in return f(a, b, c, d) } } } // Function composition. infix operator • public func •<T, U, V>(f: @escaping (T) -> U, g: @escaping (U) -> V) -> (T) -> V { return { t in return g(f(t)) } } public func •<T, V>(f: @escaping (T) -> Void, g: @escaping () -> V) -> (T) -> V { return { t in f(t) return g() } } public func •<V>(f: @escaping () -> Void, g: @escaping () -> V) -> () -> V { return { f() return g() } } // Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse. // This is enough to catch arrays, which Swift will delegate to element-==. public func optArrayEqual<T: Equatable>(_ lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.none, _): return false case (_, .none): return false default: // This delegates to Swift's own array '==', which calls T's == on each element. return lhs! == rhs! } } /** * Given an array, return an array of slices of size `by` (possibly excepting the last slice). * * If `by` is longer than the input, returns a single chunk. * If `by` is less than 1, acts as if `by` is 1. * If the length of the array isn't a multiple of `by`, the final slice will * be smaller than `by`, but never empty. * * If the input array is empty, returns an empty array. */ public func chunk<T>(_ arr: [T], by: Int) -> [ArraySlice<T>] { var result = [ArraySlice<T>]() var chunk = -1 let size = max(1, by) for (index, elem) in arr.enumerated() { if index % size == 0 { result.append(ArraySlice<T>()) chunk += 1 } result[chunk].append(elem) } return result } public extension Sequence { // [T] -> (T -> K) -> [K: [T]] // As opposed to `groupWith` (to follow Haskell's naming), which would be // [T] -> (T -> K) -> [[T]] func groupBy<Key, Value>(_ selector: (Self.Iterator.Element) -> Key, transformer: (Self.Iterator.Element) -> Value) -> [Key: [Value]] { var acc: [Key: [Value]] = [:] for x in self { let k = selector(x) var a = acc[k] ?? [] a.append(transformer(x)) acc[k] = a } return acc } func zip<S: Sequence>(_ elems: S) -> [(Self.Iterator.Element, S.Iterator.Element)] { var rights = elems.makeIterator() return self.flatMap { lhs in guard let rhs = rights.next() else { return nil } return (lhs, rhs) } } } public func optDictionaryEqual<K: Equatable, V: Equatable>(_ lhs: [K: V]?, rhs: [K: V]?) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.none, _): return false case (_, .none): return false default: return lhs! == rhs! } } /** * Return members of `a` that aren't nil, changing the type of the sequence accordingly. */ public func optFilter<T>(_ a: [T?]) -> [T] { return a.flatMap { $0 } } /** * Return a new map with only key-value pairs that have a non-nil value. */ public func optFilter<K, V>(_ source: [K: V?]) -> [K: V] { var m = [K: V]() for (k, v) in source { if let v = v { m[k] = v } } return m } /** * Map a function over the values of a map. */ public func mapValues<K, T, U>(_ source: [K: T], f: ((T) -> U)) -> [K: U] { var m = [K: U]() for (k, v) in source { m[k] = f(v) } return m } public func findOneValue<K, V>(_ map: [K: V], f: (V) -> Bool) -> V? { for v in map.values { if f(v) { return v } } return nil } /** * Take a JSON array, returning the String elements as an array. * It's usually convenient for this to accept an optional. */ public func jsonsToStrings(_ arr: [JSON]?) -> [String]? { return arr?.flatMap { $0.stringValue } } // Encapsulate a callback in a way that we can use it with NSTimer. private class Callback { private let handler:() -> Void init(handler:@escaping () -> Void) { self.handler = handler } @objc func go() { handler() } } /** * Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call * Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires. **/ public func debounce(_ delay: TimeInterval, action:@escaping () -> Void) -> () -> Void { let callback = Callback(handler: action) var timer: Timer? return { // If calling again, invalidate the last timer. if let timer = timer { timer.invalidate() } timer = Timer(timeInterval: delay, target: callback, selector: #selector(Callback.go), userInfo: nil, repeats: false) RunLoop.current.add(timer!, forMode: RunLoopMode.defaultRunLoopMode) } }
31a85bfbbca39efca082522a77958d34
25.495614
139
0.536501
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/Analytics/Analytics+OptOut.swift
gpl-3.0
1
// // Wire // Copyright (C) 2020 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 WireDataModel extension Analytics { /// Opt the user out of sending analytics data var isOptedOut: Bool { get { guard let provider = provider else { return true } return provider.isOptedOut } set { if newValue && (provider?.isOptedOut ?? false) { return } if newValue { provider?.flush { self.provider?.isOptedOut = newValue self.provider = nil } } else { provider = AnalyticsProviderFactory.shared.analyticsProvider() selfUser = SelfUser.current } } } }
c035ee8aea2bfccc419decb2b020795e
29.425532
78
0.614685
false
false
false
false
malaonline/iOS
refs/heads/master
mala-ios/Tool/Refresher/ThemeRefreshFooterAnimator.swift
mit
1
// // ThemeRefreshFooterAnimator.swift // mala-ios // // Created by 王新宇 on 03/05/2017. // Copyright © 2017 Mala Online. All rights reserved. // import UIKit import ESPullToRefresh public class ThemeRefreshFooterAnimator: UIView, ESRefreshProtocol, ESRefreshAnimatorProtocol { open var loadingMoreDescription: String = "加载更多" open var noMoreDataDescription: String = "没有更多内容啦~" open var loadingDescription: String = "加载中..." // MARK: - Property public var view: UIView { return self } public var insets: UIEdgeInsets = UIEdgeInsets.zero public var trigger: CGFloat = 48.0 public var executeIncremental: CGFloat = 0.0 public var state: ESRefreshViewState = .pullToRefresh public var duration: TimeInterval = 0.3 // MARK: - Components private lazy var imageView: UIImageView = { let imageView = UIImageView(imageName: "nomoreContent") imageView.isHidden = true return imageView }() private let titleLabel: UILabel = { let label = UILabel() label.font = FontFamily.PingFangSC.Regular.font(14) label.textColor = UIColor(named: .protocolGary) label.textAlignment = .center return label }() private let indicatorView: UIActivityIndicatorView = { let indicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray) indicatorView.isHidden = true return indicatorView }() // MARK: - Instance Method override init(frame: CGRect) { super.init(frame: frame) titleLabel.text = loadingMoreDescription addSubview(titleLabel) addSubview(indicatorView) addSubview(imageView) titleLabel.snp.makeConstraints { (maker) in maker.centerX.equalTo(self) maker.height.equalTo(20) maker.top.equalTo(self).offset(12) } indicatorView.snp.makeConstraints { (maker) in maker.centerY.equalTo(titleLabel) maker.right.equalTo(titleLabel.snp.left).offset(-18) } imageView.snp.makeConstraints { (maker) in maker.top.equalTo(titleLabel.snp.bottom).offset(6) maker.centerX.equalTo(self) maker.height.equalTo(120) maker.width.equalTo(220) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - ESRefresh Protocol public func refreshAnimationBegin(view: ESRefreshComponent) { indicatorView.startAnimating() indicatorView.isHidden = false imageView.isHidden = true } public func refreshAnimationEnd(view: ESRefreshComponent) { indicatorView.stopAnimating() indicatorView.isHidden = true } public func refresh(view: ESRefreshComponent, progressDidChange progress: CGFloat) { } public func refresh(view: ESRefreshComponent, stateDidChange state: ESRefreshViewState) { guard self.state != state else { return } self.state = state switch state { case .refreshing, .autoRefreshing : titleLabel.text = loadingDescription break case .noMoreData: titleLabel.text = noMoreDataDescription imageView.isHidden = false break case .pullToRefresh: titleLabel.text = loadingMoreDescription break default: break } } }
1ee1d7e446642e35b81d595694e897b2
30.289474
95
0.630502
false
false
false
false
colourful987/My-Name-Is-Demo
refs/heads/master
DO_SliderTabBarController2/DO_SliderTabBarController2/PTAnimationController.swift
mit
1
// // PTAnimationController.swift // DO_SliderTabBarController // // Created by pmst on 15/12/4. // Copyright © 2015年 pmst. All rights reserved. // import UIKit class PTAnimationController: UIViewController { // MARK: - Properties weak var tbc : UITabBarController? var duration:NSTimeInterval = 0.4 var interacting:Bool = false var context : UIViewControllerContextTransitioning! var fvEndFrame:CGRect = CGRectZero var tvStartFrame:CGRect = CGRectZero // MARK: - Method override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - UITabBarControllerDelegate Protocol extension PTAnimationController:UITabBarControllerDelegate{ /// 页面切换调用该方法 告知哪个对象来进行动画设计 /// 这里是self func tabBarController(tabBarController: UITabBarController, animationControllerForTransitionFromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } /// 页面切换调用该方法 告知哪个对象来进行交互式的响应(多指手势) /// 本来这个方法调用之后 要调用startInteractiveTransition了 /// 但是percent driver 是直接转向调用animateTransition 但是不执行动画! /// 其实就是去要个起始状态,之后持续调用updateInteractiveTransition方法 func tabBarController(tabBarController: UITabBarController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return self.interacting ? self:nil } } // MARK: - UIViewControllerAnimatedTransitioning Protocol extension PTAnimationController:UIViewControllerAnimatedTransitioning{ // 动画执行的时间 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return self.duration } // 动画具体执行方案 func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fvc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let tvc = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let cv = transitionContext.containerView()! let fvStartFrame = transitionContext.initialFrameForViewController(fvc) let tvEndFrame = transitionContext.finalFrameForViewController(tvc) let fv = transitionContext.viewForKey(UITransitionContextFromViewKey)! let tv = transitionContext.viewForKey(UITransitionContextToViewKey)! let index1 = self.tbc!.viewControllers!.indexOf(fvc)! let index2 = self.tbc!.viewControllers!.indexOf(tvc)! let dir : CGFloat = index1 < index2 ? 1 : -1 // 设定From View 的结束位置,起始位置已知 var fvEndFrame = fvStartFrame fvEndFrame.origin.x -= fvEndFrame.size.width * dir // 设定To View 的起始位置,结束位置已知 var tvStartFrame = tvEndFrame tvStartFrame.origin.x += tvStartFrame.size.width * dir tv.frame = tvStartFrame cv.addSubview(tv) UIView.animateWithDuration(self.duration, animations: { fv.frame = fvEndFrame tv.frame = tvEndFrame },completion: { _ in let cancelled = transitionContext.transitionWasCancelled() transitionContext.completeTransition(!cancelled) }) } } extension PTAnimationController:UIViewControllerInteractiveTransitioning{ // 做好准备工作! func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) { // self.context = transitionContext let fvc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let tvc = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let cv = transitionContext.containerView()! let fvStartFrame = transitionContext.initialFrameForViewController(fvc) let tvEndFrame = transitionContext.finalFrameForViewController(tvc) let fv = transitionContext.viewForKey(UITransitionContextFromViewKey)! let tv = transitionContext.viewForKey(UITransitionContextToViewKey)! let index1 = self.tbc!.viewControllers!.indexOf(fvc)! let index2 = self.tbc!.viewControllers!.indexOf(tvc)! let dir : CGFloat = index1 < index2 ? 1 : -1 // 设定From View 的结束位置,起始位置已知 var fvEndFrame = fvStartFrame fvEndFrame.origin.x -= fvEndFrame.size.width * dir // 设定To View 的起始位置,结束位置已知 var tvStartFrame = tvEndFrame tvStartFrame.origin.x += tvStartFrame.size.width * dir tv.frame = tvStartFrame cv.addSubview(tv) // record initial conditions so the gesture recognizer can get at them self.fvEndFrame = fvEndFrame self.tvStartFrame = tvStartFrame } }
d8394a4b163f95b95fb04327bd8f01b0
32.814286
223
0.754753
false
false
false
false
kristopherjohnson/KJLunarLander
refs/heads/master
KJLunarLander/Color.swift
mit
1
// // Color.swift // KJLunarLander // // Copyright © 2016 Kristopher Johnson. All rights reserved. // import SpriteKit /// Constants for colors used by UI elements in the application. enum Color { /// Color of the lander's lower section. static let lander = SKColor.orange /// Color of the lander's ascent-stage section. static let ascentHull = SKColor.lightGray /// Color of onscreen controls when active. static let controlHighlight = SKColor.orange /// Color of onscreen controls when not active. static let controlNormal = SKColor.lightGray /// Color of HUD text. static let hud = SKColor.green /// Color of lunar surface. static let surface = SKColor(white: 0.125, alpha: 1.0) }
2d901e1d9b1e1b62ea8e58e57df4bcc7
24.724138
64
0.686327
false
false
false
false
kperryua/swift
refs/heads/master
test/type/protocol_composition.swift
apache-2.0
1
// RUN: %target-parse-verify-swift -swift-version 4 func canonical_empty_protocol() -> Any { return 1 } protocol P1 { func p1() func f(_: Int) -> Int } protocol P2 : P1 { func p2() } protocol P3 { func p3() } protocol P4 : P3 { func p4() func f(_: Double) -> Double } typealias Any1 = protocol<> // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}} typealias Any2 = protocol< > // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}} // Okay to inherit a typealias for Any type. protocol P5 : Any { } protocol P6 : protocol<> { } // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}} // expected-error@-1 {{protocol composition is neither allowed nor needed here}} typealias P7 = Any & Any1 extension Int : P5 { } typealias Bogus = P1 & Int // expected-error{{non-protocol type 'Int' cannot be used within a protocol composition}} func testEquality() { // Remove duplicates from protocol-conformance types. let x1 : (_ : P2 & P4) -> () let x2 : (_ : P3 & P4 & P2 & P1) -> () x1 = x2 _ = x1 // Singleton protocol-conformance types, after duplication, are the same as // simply naming the protocol type. let x3 : (_ : P2 & P1) -> () let x4 : (_ : P2) -> () x3 = x4 _ = x3 // Empty protocol-conformance types are empty. let x5 : (_ : Any) -> () let x6 : (_ : Any2) -> () x5 = x6 _ = x5 let x7 : (_ : P1 & P3) -> () let x8 : (_ : P2) -> () x7 = x8 // expected-error{{cannot assign value of type '(P2) -> ()' to type '(P1 & P3) -> ()'}} _ = x7 } // Name lookup into protocol-conformance types func testLookup() { let x1 : P2 & P1 & P4 x1.p1() x1.p2() x1.p3() x1.p4() var _ : Int = x1.f(1) var _ : Double = x1.f(1.0) } protocol REPLPrintable { func replPrint() } protocol SuperREPLPrintable : REPLPrintable { func superReplPrint() } protocol FooProtocol { func format(_ kind: UnicodeScalar, layout: String) -> String } struct SuperPrint : REPLPrintable, FooProtocol, SuperREPLPrintable { func replPrint() {} func superReplPrint() {} func format(_ kind: UnicodeScalar, layout: String) -> String {} } struct Struct1 {} extension Struct1 : REPLPrintable, FooProtocol { func replPrint() {} func format(_ kind: UnicodeScalar, layout: String) -> String {} } func accept_manyPrintable(_: REPLPrintable & FooProtocol) {} func return_superPrintable() -> FooProtocol & SuperREPLPrintable {} func testConversion() { // Conversions for literals. var x : REPLPrintable & FooProtocol = Struct1() accept_manyPrintable(Struct1()) // Conversions for nominal types that conform to a number of protocols. let sp : SuperPrint x = sp accept_manyPrintable(sp) // Conversions among existential types. var x2 : protocol<SuperREPLPrintable, FooProtocol> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{12-53=SuperREPLPrintable & FooProtocol}} x2 = x // expected-error{{value of type 'FooProtocol & REPLPrintable' does not conform to 'FooProtocol & SuperREPLPrintable' in assignment}} x = x2 // Subtyping var _ : () -> FooProtocol & SuperREPLPrintable = return_superPrintable // FIXME: closures make ABI conversions explicit. rdar://problem/19517003 var _ : () -> protocol<FooProtocol, REPLPrintable> = { return_superPrintable() } // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{17-53=FooProtocol & REPLPrintable}} } // Test the parser's splitting of >= into > and =. var x : protocol<P5>= 17 // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{9-22=P5=}} var y : protocol<P5, P7>= 17 // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{9-26=(P5 & P7)=}} typealias A1 = protocol<> // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}} {{16-26=Any}} typealias A2 = protocol<>? // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}} {{16-27=Any?}} typealias B1 = protocol<P1,P2> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{16-31=P1 & P2}} typealias B2 = protocol<P1, P2> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{16-32=P1 & P2}} typealias B3 = protocol<P1 ,P2> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{16-32=P1 & P2}} typealias B4 = protocol<P1 , P2> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{16-33=P1 & P2}} typealias C1 = protocol<Any, P1> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{16-33=P1}} typealias C2 = protocol<P1, Any> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{16-33=P1}} typealias D = protocol<P1> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{15-27=P1}} typealias E = protocol<Any> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{15-28=Any}} typealias F = protocol<Any, Any> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{15-33=Any}} typealias T01 = P1.Protocol & P2 // expected-error {{non-protocol type 'P1.Protocol' cannot be used within a protocol composition}} typealias T02 = P1.Type & P2 // expected-error {{non-protocol type 'P1.Type' cannot be used within a protocol composition}} typealias T03 = P1? & P2 // expected-error {{non-protocol type 'P1?' cannot be used within a protocol composition}} typealias T04 = P1 & P2! // expected-error {{non-protocol type 'P2!' cannot be used within a protocol composition}} expected-error {{implicitly unwrapped optionals}} {{24-25=?}} typealias T05 = P1 & P2 -> P3 // expected-error {{single argument function types require parentheses}} {{17-17=(}} {{24-24=)}} typealias T06 = P1 -> P2 & P3 // expected-error {{single argument function types require parentheses}} {{17-17=(}} {{19-19=)}} typealias T07 = P1 & protocol<P2, P3> // expected-warning {{protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{22-38=P2 & P3}} func fT07(x: T07) -> P1 & P2 & P3 { return x } // OK, 'P1 & protocol<P2, P3>' is parsed as 'P1 & P2 & P3'. let _: P1 & P2 & P3 -> P1 & P2 & P3 = fT07 // expected-error {{single argument function types require parentheses}} {{8-8=(}} {{20-20=)}} struct S01: P5 & P6 {} // expected-error {{protocol composition is neither allowed nor needed here}} {{none}} struct S02: P5? & P6 {} // expected-error {{inheritance from non-named type 'P5?'}} struct S03: Optional<P5> & P6 {} // expected-error {{inheritance from non-protocol type 'Optional<P5>'}} expected-error {{protocol composition is neither allowed nor needed here}} struct S04<T : P5 & (P6)> {} // expected-error {{inheritance from non-named type '(P6)'}} struct S05<T> where T : P5? & P6 {} // expected-error {{inheritance from non-named type 'P5?'}}
6ad1ad2b38a8d49f77b740099d238dd4
45.290323
223
0.66899
false
false
false
false
legendecas/Rocket.Chat.iOS
refs/heads/sdk
Rocket.Chat.SDK/Controllers/OfflineFormViewController.swift
mit
1
// // OfflineFormViewController.swift // Rocket.Chat // // Created by Lucas Woo on 7/16/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import UIKit class OfflineFormViewController: UITableViewController, LivechatManagerInjected { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var nameField: UITextField! @IBOutlet weak var messageTextView: UITextView! @IBOutlet var sectionHeader: UIView! @IBOutlet weak var offlineMessageLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = livechatManager.offlineTitle offlineMessageLabel.text = livechatManager.offlineMessage let messageLabelSize = offlineMessageLabel.sizeThatFits(CGSize(width: self.view.frame.width - 16, height: CGFloat.infinity)) offlineMessageLabel.heightAnchor.constraint(equalToConstant: messageLabelSize.height).isActive = true var frame = sectionHeader.frame frame.size = CGSize(width: self.view.frame.width, height: 8 + 16 + 4 + messageLabelSize.height + 8) sectionHeader.frame = frame } // MARK: - Actions @IBAction func didTouchCancelButton(_ sender: UIBarButtonItem) { dismissSelf() } func dismissSelf() { self.dismiss(animated: true, completion: nil) } @IBAction func didTouchSendButton(_ sender: UIBarButtonItem) { guard let email = emailField.text else { return } guard let name = nameField.text else { return } guard let message = messageTextView.text else { return } LoaderView.showLoader(for: self.view, preset: .white) livechatManager.sendOfflineMessage(email: email, name: name, message: message) { LoaderView.hideLoader(for: self.view) let alert = UIAlertController(title: self.livechatManager.title, message: self.livechatManager.offlineSuccessMessage, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in self.dismissSelf() }) self.present(alert, animated: true, completion: nil) } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch section { case 0: return sectionHeader?.frame.size.height ?? 0 default: return super.tableView(tableView, heightForHeaderInSection: section) } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case 0: return sectionHeader default: return super.tableView(tableView, viewForHeaderInSection: section) } } } extension OfflineFormViewController: UITextFieldDelegate { public func textFieldShouldReturn(_ textField: UITextField) -> Bool { let nextTag = textField.tag + 1 if let nextResponder = textField.superview?.viewWithTag(nextTag) { nextResponder.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } }
2e6f26c814ba046c8ceee333d1edd869
34.010989
159
0.667294
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/DelegatedSelfCustody/Sources/DelegatedSelfCustodyData/Network/Models/TransactionHistoryResponse.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. struct TransactionHistoryResponse: Decodable { enum Status: String, Decodable { case pending = "PENDING" case failed = "FAILED" case completed = "COMPLETED" case confirming = "CONFIRMING" } struct Movement: Decodable { let type: Direction? let address: String? let amount: String let identifier: String } enum Direction: String, Decodable { case sent = "SENT" case received = "RECEIVED" } struct Entry: Decodable { let txId: String let status: Status? let timestamp: Double? let fee: String let movements: [Movement] } let history: [Entry] }
8de3bb1372f1687bb0520806d4f8902b
22.9375
62
0.5953
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/URLComponents+Extensions.swift
mit
1
import Foundation extension URLComponents { static func with(host: String, scheme: String = "https", path: String = "/", queryParameters: [String: Any]? = nil) -> URLComponents { var components = URLComponents() components.host = host components.scheme = scheme components.path = path components.replacePercentEncodedQueryWithQueryParameters(queryParameters) return components } public static func percentEncodedQueryStringFrom(_ queryParameters: [String: Any]) -> String { var query = "" // sort query parameters by key, this allows for consistency when itemKeys are generated for the persistent cache. struct KeyValue { let key: String let value: Any } var unorderedKeyValues: [KeyValue] = [] for (name, value) in queryParameters { unorderedKeyValues.append(KeyValue(key: name, value: value)) } let orderedKeyValues = unorderedKeyValues.sorted { (lhs, rhs) -> Bool in return lhs.key < rhs.key } for keyValue in orderedKeyValues { guard let encodedName = keyValue.key.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryComponentAllowed), let encodedValue = String(describing: keyValue.value).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryComponentAllowed) else { continue } if query != "" { query.append("&") } query.append("\(encodedName)=\(encodedValue)") } return query } mutating func appendQueryParametersToPercentEncodedQuery(_ queryParameters: [String: Any]?) { guard let queryParameters = queryParameters else { return } var newPEQ = "" if let existing = percentEncodedQuery { newPEQ = existing + "&" } newPEQ = newPEQ + URLComponents.percentEncodedQueryStringFrom(queryParameters) percentEncodedQuery = newPEQ } mutating func replacePercentEncodedQueryWithQueryParameters(_ queryParameters: [String: Any]?) { guard let queryParameters = queryParameters else { percentEncodedQuery = nil return } percentEncodedQuery = URLComponents.percentEncodedQueryStringFrom(queryParameters) } mutating func replacePercentEncodedPathWithPathComponents(_ pathComponents: [String]?) { guard let pathComponents = pathComponents else { percentEncodedPath = "/" return } let fullComponents = [""] + pathComponents #if DEBUG for component in fullComponents { assert(!component.contains("/")) } #endif percentEncodedPath = fullComponents.joined(separator: "/") // NSString.path(with: components) removes the trailing slash that the reading list API needs } public func wmf_URLWithLanguageVariantCode(_ code: String?) -> URL? { return (self as NSURLComponents).wmf_URL(withLanguageVariantCode: code) } }
641f8a00ab09e2a733bab34103336a3a
36.229885
160
0.615931
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Lumia/Lumia/Component/QuartzDemo/Controllers/PDFController.swift
mit
2
// // PDFController.swift // QuartzDemo // // Created by 伯驹 黄 on 2017/4/8. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit class PDFController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let quartzPDFView = QuartzPDFView() view.addSubview(quartzPDFView) quartzPDFView.translatesAutoresizingMaskIntoConstraints = false quartzPDFView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true quartzPDFView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true quartzPDFView.topAnchor.constraint(equalTo: view.safeTopAnchor).isActive = true quartzPDFView.bottomAnchor.constraint(equalTo: view.safeBottomAnchor).isActive = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
5a005be4ef0c7cde305b2eb0cd91d04a
31.137931
93
0.719957
false
false
false
false
bananafish911/SmartReceiptsiOS
refs/heads/master
SmartReceiptsTests/Model/Receipt/ReceiptColumnExchangeRateTests.swift
agpl-3.0
1
// // ReceiptColumnExchangeRateTests.swift // SmartReceipts // // Created by Jaanus Siim on 30/05/16. // Copyright © 2016 Will Baumann. All rights reserved. // import XCTest @testable import SmartReceipts class ReceiptColumnExchangeRateTests: XCTestCase { fileprivate let trip = WBTrip() fileprivate var receipt: WBReceipt! fileprivate let column = ReceiptColumnExchangeRate() override func setUp() { super.setUp() trip.defaultCurrency = Currency.currency(forCode: "USD") receipt = WBReceipt() receipt.trip = trip } func testNoExchangeRateForSameCurrency() { receipt.setPrice(NSDecimalNumber(string: "12"), currency: "USD") XCTAssertEqual("1", column.value(from: receipt, forCSV: false)) XCTAssertEqual("1", column.value(from: receipt, forCSV: true)) } func testNegativeExchangeRate() { receipt.setPrice(NSDecimalNumber(string: "12"), currency: "EUR") receipt.exchangeRate = .minusOne() XCTAssertEqual("", column.value(from: receipt, forCSV: false)) XCTAssertEqual("", column.value(from: receipt, forCSV: true)) } func testProvidedExchangeRateForSameCurrency() { // Note: This represents a scenario in which something got f'ed up... We should fail fast before here receipt.setPrice(NSDecimalNumber(string: "12"), currency: "USD") receipt.exchangeRate = NSDecimalNumber(string: "0.123456") XCTAssertEqual("1", column.value(from: receipt, forCSV: false)) XCTAssertEqual("1", column.value(from: receipt, forCSV: true)) } func testExchangeRateForDifferentCurrency() { receipt.setPrice(NSDecimalNumber(string: "12"), currency: "EUR") receipt.exchangeRate = NSDecimalNumber(string: "0.123456") XCTAssertEqual("0.123456", column.value(from: receipt, forCSV: false)) XCTAssertEqual("0.123456", column.value(from: receipt, forCSV: true)) } }
f1bbdad142eb91110d44704541e119c0
35.722222
109
0.672718
false
true
false
false
kzaher/RxSwift
refs/heads/develop
RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift
mit
1
// // GitHubSearchRepositoriesViewController.swift // RxExample // // Created by Yoshinori Sano on 9/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit import RxSwift import RxCocoa extension UIScrollView { func isNearBottomEdge(edgeOffset: CGFloat = 20.0) -> Bool { self.contentOffset.y + self.frame.size.height + edgeOffset > self.contentSize.height } } class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegate { static let startLoadingOffset: CGFloat = 20.0 @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Repository>>( configureCell: { (_, tv, ip, repository: Repository) in let cell = tv.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = repository.name cell.detailTextLabel?.text = repository.url.absoluteString return cell }, titleForHeaderInSection: { dataSource, sectionIndex in let section = dataSource[sectionIndex] return section.items.count > 0 ? "Repositories (\(section.items.count))" : "No repositories found" } ) override func viewDidLoad() { super.viewDidLoad() let tableView: UITableView = self.tableView let loadNextPageTrigger: (Driver<GitHubSearchRepositoriesState>) -> Signal<()> = { state in tableView.rx.contentOffset.asDriver() .withLatestFrom(state) .flatMap { state in return tableView.isNearBottomEdge(edgeOffset: 20.0) && !state.shouldLoadNextPage ? Signal.just(()) : Signal.empty() } } let activityIndicator = ActivityIndicator() let searchBar: UISearchBar = self.searchBar let state = githubSearchRepositories( searchText: searchBar.rx.text.orEmpty.changed.asSignal().throttle(.milliseconds(300)), loadNextPageTrigger: loadNextPageTrigger, performSearch: { URL in GitHubSearchRepositoriesAPI.sharedAPI.loadSearchURL(URL) .trackActivity(activityIndicator) }) state .map { $0.isOffline } .drive(navigationController!.rx.isOffline) .disposed(by: disposeBag) state .map { $0.repositories } .distinctUntilChanged() .map { [SectionModel(model: "Repositories", items: $0.value)] } .drive(tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) tableView.rx.modelSelected(Repository.self) .subscribe(onNext: { repository in UIApplication.shared.openURL(repository.url) }) .disposed(by: disposeBag) state .map { $0.isLimitExceeded } .distinctUntilChanged() .filter { $0 } .drive(onNext: { [weak self] n in guard let self = self else { return } let message = "Exceeded limit of 10 non authenticated requests per minute for GitHub API. Please wait a minute. :(\nhttps://developer.github.com/v3/#rate-limiting" #if os(iOS) self.present(UIAlertController(title: "RxExample", message: message, preferredStyle: .alert), animated: true) #elseif os(macOS) let alert = NSAlert() alert.messageText = message alert.runModal() #endif }) .disposed(by: disposeBag) tableView.rx.contentOffset .subscribe { _ in if searchBar.isFirstResponder { _ = searchBar.resignFirstResponder() } } .disposed(by: disposeBag) // so normal delegate customization can also be used tableView.rx.setDelegate(self) .disposed(by: disposeBag) // activity indicator in status bar // { activityIndicator .drive(UIApplication.shared.rx.isNetworkActivityIndicatorVisible) .disposed(by: disposeBag) // } } // MARK: Table view delegate func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 30 } deinit { // I know, I know, this isn't a good place of truth, but it's no self.navigationController?.navigationBar.backgroundColor = nil } }
07f9484fc6a4de57236eb0c5033fd0a6
34.282443
179
0.599091
false
false
false
false
haoking/SwiftyUI
refs/heads/master
Sources/SwiftyToast.swift
mit
1
// // SwiftyToast.swift // WHCWSIFT // // Created by Haochen Wang on 10/17/17. // Copyright © 2017 Haochen Wang. All rights reserved. // import UIKit public final class SwiftyToast { private lazy var toastLabel: SwiftyLabel = { [unowned self] in var toastLabel = SwiftyLabel(nil, .white, .init(white: 0.0, alpha: 0.7)) toastLabel.layer.cornerRadius = 5 toastLabel.clipsToBounds = true toastLabel.padding = 5.0 toastLabel.font = .systemFont(ofSize: 12) return toastLabel }() public init(_ text: String) { layoutView(text: text) SwiftyToastCenter.default.add(self).fire() } // @discardableResult // public class func load(_ text: String) -> SwiftyToast // { // return .init(text: text) // } private func layoutView(text: String) { toastLabel.text = text let containerSize: CGSize = SwiftyGlobal.keyWindow.bounds.size let constraintSize: CGSize = CGSize(width: containerSize.width * (280.0 / 320.0), height: CGFloat.greatestFiniteMagnitude) let fitSize: CGSize = toastLabel.sizeThatFits(constraintSize) var x: CGFloat var y: CGFloat var width: CGFloat var height: CGFloat if UIApplication.shared.statusBarOrientation.isPortrait { width = containerSize.width height = containerSize.height y = 30.0 } else { width = containerSize.height height = containerSize.width y = 20.0 } let size: CGSize = .init(width: fitSize.width + 10 + 10, height: fitSize.height + 6 + 6) x = (width - size.width) * 0.5 y = height - (size.height + y) toastLabel.frame = CGRect(x: x, y: y, width: size.width, height: size.height) } fileprivate func show() { Promise<Void>.firstly(on: .main) { self.toastLabel.alpha = 0 SwiftyGlobal.keyWindow.addSubview(self.toastLabel) UIView.animate(withDuration: 0.5, delay: 0.0, options: .beginFromCurrentState, animations: { self.toastLabel.alpha = 1 }, completion: { completed in UIView.animate(withDuration: 2.5, animations: { self.toastLabel.alpha = 1.0001 }, completion: { completed in UIView.animate(withDuration: 0.5, animations: { self.toastLabel.alpha = 0 }, completion: { completed in self.toastLabel.removeFromSuperview() SwiftyToastCenter.default.finish() }) }) }) }.catch() } public class func cancel() { SwiftyToastCenter.default.cancelAll() } } private final class SwiftyToastCenter { private var queueArray: [SwiftyToast] = [] private var isFinished: Bool = true public static let `default` = { return SwiftyToastCenter() }() private init(){} @discardableResult public func add(_ toast: SwiftyToast) -> SwiftyToastCenter { queueArray.append(toast) return self } public func finish() { isFinished = true fire() } public func fire() { guard let toast = queueArray.first, isFinished else { return } queueArray.removeFirst() isFinished = false toast.show() } public func cancelAll() { queueArray.removeAll() } }
d81eac174e37772271e9ab8b359d6b9a
26.923664
130
0.556315
false
false
false
false
criticalmaps/criticalmaps-ios
refs/heads/main
CriticalMapsKit/Sources/AppFeature/RequestTimerCore.swift
mit
1
import ComposableArchitecture import Foundation public struct RequestTimer: ReducerProtocol { public init(timerInterval: Double = 12.0) { self.timerInterval = timerInterval } @Dependency(\.mainQueue) public var mainQueue let timerInterval: Double var interval: DispatchQueue.SchedulerTimeType.Stride { DispatchQueue.SchedulerTimeType.Stride(floatLiteral: timerInterval) } // MARK: State public struct State: Equatable { public init(isTimerActive: Bool = false) { self.isTimerActive = isTimerActive } public var isTimerActive = false } // MARK: Action public enum Action: Equatable { case timerTicked case startTimer } /// Reducer responsible for the poll timer handling. public func reduce(into state: inout State, action: Action) -> Effect<Action, Never> { switch action { case .timerTicked: return .none case .startTimer: state.isTimerActive = true return .run { [isTimerActive = state.isTimerActive] send in guard isTimerActive else { return } for await _ in mainQueue.timer(interval: interval) { await send(.timerTicked) } } .cancellable(id: TimerId.self, cancelInFlight: true) } } } private struct TimerId: Hashable {}
e6936ed42eedc2d7eba4d7e61a0f332d
23.596154
88
0.689601
false
false
false
false
baohuynh94/Genome
refs/heads/master
Genome.playground/Contents.swift
mit
2
//: Playground - noun: a place where people can play import UIKit let json_rover: JSON = [ "name" : "Rover", "nickname" : "RoRo", "type" : "dog" ] let json_jane: JSON = [ "name" : "jane", "birthday" : "12-10-85", "pet" : json_rover ] let json_snowflake: JSON = [ "name" : "Snowflake", "type" : "cat" ] let json_joe: JSON = [ "name" : "Joe", "birthday" : "12-15-84", "pet" : json_snowflake ] enum DateTransformationError : ErrorType { case UnableToConvertString } extension NSDate { class func dateWithBirthdayString(string: String) throws -> NSDate { let df = NSDateFormatter() df.dateFormat = "mm-d-yy" if let date = df.dateFromString(string) { return date } else { throw DateTransformationError.UnableToConvertString } } class func birthdayStringWithDate(date: NSDate?) -> String? { guard let date = date else { return nil } let df = NSDateFormatter() df.dateFormat = "mm-d-yy" return df.stringFromDate(date) } } enum PetType : String { case Dog = "dog" case Cat = "cat" } struct Pet { var name = "" var type: PetType! var nickname: String? } struct Person { let name: String let pet: Pet let birthday: NSDate let favoriteFood: String? } extension Pet : BasicMappable { mutating func sequence(map: Map) throws { try name <~> map["name"] try nickname <~> map["nickname"] try type <~> map["type"] .transformFromJson { return PetType(rawValue: $0) } .transformToJson { return $0.rawValue } } } extension Person : StandardMappable { init(map: Map) throws { try pet = <~map["pet"] try name = <~map["name"] try birthday = <~map["birthday"] .transformFromJson(NSDate.dateWithBirthdayString) try favoriteFood = <~?map["favorite_food"] } mutating func sequence(map: Map) throws { try name ~> map["name"] try pet ~> map["pet"] try birthday ~> map["birthday"] .transformToJson(NSDate.birthdayStringWithDate) try favoriteFood ~> map["favorite_food"] } } do { let rover = try Pet.mappedInstance(json_rover) print(rover) } catch { print(error) } let joe = try Person.mappedInstance(json_joe) joe.name joe.favoriteFood joe.pet.type joe.pet.name joe.birthday struct Book : CustomMappable { var title: String = "" var releaseYear: Int = 0 var id: String = "" static func newInstance(map: Map) throws -> Book { let id: String = try <~map["id"] return existingBookWithId(id) ?? Book() } mutating func sequence(map: Map) throws { try title <~> map["title"] try id <~> map["id"] try releaseYear <~> map["release_year"] .transformFromJson { (input: String) -> Int in return Int(input)! } .transformToJson { return "\($0)" } } } func existingBookWithId(id: String) -> Book? { return nil } let json_book: JSON = [ "title" : "Title", "release_year" : "2009", "id" : "asd9fj20m" ] let book = try! Book.mappedInstance(json_book) book.title book.releaseYear book.id // MARK: let map = Map(json: ["key" : "value"]) let mappedString1: String? = try <~map["key"] .transformFromJson { (input: String?) -> String? in return "Hello \(input)" } let mappedString2: String = try <~map["key"] .transformFromJson { (input: String) -> String in return "Hello NonOptional \(input)" }
f3b498ca6abee88bbd1a7515e09b5ef7
21.113095
72
0.568506
false
false
false
false
GoMino/Shopmium
refs/heads/master
Carthage/Checkouts/ReactiveCocoa/ReactiveCocoa/Swift/Action.swift
apache-2.0
5
/// Represents an action that will do some work when executed with a value of /// type `Input`, then return zero or more values of type `Output` and/or error /// out with an error of type `Error`. If no errors should be possible, NoError /// can be specified for the `Error` parameter. /// /// Actions enforce serial execution. Any attempt to execute an action multiple /// times concurrently will return an error. public final class Action<Input, Output, Error: ErrorType> { private let executeClosure: Input -> SignalProducer<Output, Error> private let eventsObserver: Signal<Event<Output, Error>, NoError>.Observer /// A signal of all events generated from applications of the Action. /// /// In other words, this will send every `Event` from every signal generated /// by each SignalProducer returned from apply(). public let events: Signal<Event<Output, Error>, NoError> /// A signal of all values generated from applications of the Action. /// /// In other words, this will send every value from every signal generated /// by each SignalProducer returned from apply(). public let values: Signal<Output, NoError> /// A signal of all errors generated from applications of the Action. /// /// In other words, this will send errors from every signal generated by /// each SignalProducer returned from apply(). public let errors: Signal<Error, NoError> /// Whether the action is currently executing. public var executing: PropertyOf<Bool> { return PropertyOf(_executing) } private let _executing: MutableProperty<Bool> = MutableProperty(false) /// Whether the action is currently enabled. public var enabled: PropertyOf<Bool> { return PropertyOf(_enabled) } private let _enabled: MutableProperty<Bool> = MutableProperty(false) /// Whether the instantiator of this action wants it to be enabled. private let userEnabled: PropertyOf<Bool> /// Lazy creation and storage of a UI bindable `CocoaAction``. The default behavior /// force casts the AnyObject? input to match the action's `Input` type. This makes /// it unsafe for use when the action is paramerterized for something like `Void` /// input. In those cases, explicitly assign a value to this property that transforms /// the input to suit your needs. public lazy var unsafeCocoaAction: CocoaAction = { _ in CocoaAction(self) { $0 as! Input } }() /// This queue is used for read-modify-write operations on the `_executing` /// property. private let executingQueue = dispatch_queue_create("org.reactivecocoa.ReactiveCocoa.Action.executingQueue", DISPATCH_QUEUE_SERIAL) /// Whether the action should be enabled for the given combination of user /// enabledness and executing status. private static func shouldBeEnabled(#userEnabled: Bool, executing: Bool) -> Bool { return userEnabled && !executing } /// Initializes an action that will be conditionally enabled, and create a /// SignalProducer for each input. public init<P: PropertyType where P.Value == Bool>(enabledIf: P, _ execute: Input -> SignalProducer<Output, Error>) { executeClosure = execute userEnabled = PropertyOf(enabledIf) (events, eventsObserver) = Signal<Event<Output, Error>, NoError>.pipe() values = events |> map { $0.value } |> ignoreNil errors = events |> map { $0.error } |> ignoreNil _enabled <~ enabledIf.producer |> combineLatestWith(executing.producer) |> map(Action.shouldBeEnabled) } /// Initializes an action that will be enabled by default, and create a /// SignalProducer for each input. public convenience init(_ execute: Input -> SignalProducer<Output, Error>) { self.init(enabledIf: ConstantProperty(true), execute) } deinit { sendCompleted(eventsObserver) } /// Creates a SignalProducer that, when started, will execute the action /// with the given input, then forward the results upon the produced Signal. /// /// If the action is disabled when the returned SignalProducer is started, /// the produced signal will send `ActionError.NotEnabled`, and nothing will /// be sent upon `values` or `errors` for that particular signal. public func apply(input: Input) -> SignalProducer<Output, ActionError<Error>> { return SignalProducer { observer, disposable in var startedExecuting = false dispatch_sync(self.executingQueue) { if self._enabled.value { self._executing.value = true startedExecuting = true } } if !startedExecuting { sendError(observer, .NotEnabled) return } self.executeClosure(input).startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observe(Signal.Observer { event in observer.put(event.mapError { .ProducerError($0) }) sendNext(self.eventsObserver, event) }) } disposable.addDisposable { self._executing.value = false } } } } /// Wraps an Action for use by a GUI control (such as `NSControl` or /// `UIControl`), with KVO, or with Cocoa Bindings. public final class CocoaAction: NSObject { /// The selector that a caller should invoke upon a CocoaAction in order to /// execute it. public static let selector: Selector = "execute:" /// Whether the action is enabled. /// /// This property will only change on the main thread, and will generate a /// KVO notification for every change. public var enabled: Bool { return _enabled } /// Whether the action is executing. /// /// This property will only change on the main thread, and will generate a /// KVO notification for every change. public var executing: Bool { return _executing } private var _enabled = false private var _executing = false private let _execute: AnyObject? -> () private let disposable = CompositeDisposable() /// Initializes a Cocoa action that will invoke the given Action by /// transforming the object given to execute(). public init<Input, Output, Error>(_ action: Action<Input, Output, Error>, _ inputTransform: AnyObject? -> Input) { _execute = { input in let producer = action.apply(inputTransform(input)) producer.start() } super.init() disposable += action.enabled.producer |> observeOn(UIScheduler()) |> start(next: { [weak self] value in self?.willChangeValueForKey("enabled") self?._enabled = value self?.didChangeValueForKey("enabled") }) disposable += action.executing.producer |> observeOn(UIScheduler()) |> start(next: { [weak self] value in self?.willChangeValueForKey("executing") self?._executing = value self?.didChangeValueForKey("executing") }) } /// Initializes a Cocoa action that will invoke the given Action by /// always providing the given input. public convenience init<Input, Output, Error>(_ action: Action<Input, Output, Error>, input: Input) { self.init(action, { _ in input }) } /// Initializes a Cocoa action that will invoke the given Action with the /// object given to execute(), if it can be downcast successfully, or nil /// otherwise. public convenience init<Input: AnyObject, Output, Error>(_ action: Action<Input?, Output, Error>) { self.init(action, { $0 as? Input }) } deinit { disposable.dispose() } /// Attempts to execute the underlying action with the given input, subject /// to the behavior described by the initializer that was used. @IBAction public func execute(input: AnyObject?) { _execute(input) } public override class func automaticallyNotifiesObserversForKey(key: String) -> Bool { return false } } /// The type of error that can occur from Action.apply, where `E` is the type of /// error that can be generated by the specific Action instance. public enum ActionError<E: ErrorType> { /// The producer returned from apply() was started while the Action was /// disabled. case NotEnabled /// The producer returned from apply() sent the given error. case ProducerError(E) } extension ActionError: ErrorType { public var nsError: NSError { switch self { case .NotEnabled: return NSError(domain: "org.reactivecocoa.ReactiveCocoa.Action", code: 1, userInfo: [ NSLocalizedDescriptionKey: self.description ]) case let .ProducerError(error): return error.nsError } } } extension ActionError: Printable { public var description: String { switch self { case .NotEnabled: return "Action executed while disabled" case let .ProducerError(error): return toString(error) } } } public func == <E: Equatable>(lhs: ActionError<E>, rhs: ActionError<E>) -> Bool { switch (lhs, rhs) { case (.NotEnabled, .NotEnabled): return true case let (.ProducerError(left), .ProducerError(right)): return left == right default: return false } }
219d5425c22c9d11b6b011d939174338
32.068966
131
0.72089
false
false
false
false
amieka/FlickStream
refs/heads/master
FlickStream/InterestingnessAPI.swift
mit
1
// // InterestingnessAPI.swift // FlickStream // // Created by Arunoday Sarkar on 6/4/16. // Copyright © 2016 Sark Software LLC. All rights reserved. // import Foundation class InterestingnessAPI: NSObject { let kAPI = FlickrAPIConstants.self func callAPI(completionHandler:([Interestingness]) -> (), errorHandler:(FlickrAPIError) -> () ) { let parametersPair = [ kAPI.FlickrAPIKeys.API_KEY : kAPI.FlickrAPIValues.API_VALUE, kAPI.FlickrAPIKeys.API_METHOD : kAPI.FlickrAPIValues.INTERESTINGNESS_METHOD, kAPI.FlickrAPIKeys.NOJSON : kAPI.FlickrAPIValues.NOJSON, kAPI.FlickrAPIKeys.PAGE: kAPI.FlickrAPIValues.PAGE_VALUE, kAPI.FlickrAPIKeys.PER_PAGE: kAPI.FlickrAPIValues.PER_PAGE_VALUE, kAPI.FlickrAPIKeys.PAYLOAD_FORMAT: kAPI.FlickrAPIValues.FORMAT, kAPI.FlickrAPIKeys.EXTRAS : "\(kAPI.FlickrAPIValues.EXTRAS_ICON_SERVER), \(kAPI.FlickrAPIValues.EXTRAS_URL_S)" ] print("API parameters, \(parametersPair)") let apiUrl = urlBuilder(parametersPair) let urlSession = NSURLSession.sharedSession() let request = NSURLRequest(URL: apiUrl) print("API request \(request)") let task = urlSession.dataTaskWithRequest(request) { (data, response, error) in // helper function for printing API errors func displayError(error: String) { print(error) } guard (error == nil) else { print("there was an error \(error.debugDescription)") return } guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else { displayError("Your request returned a status code other than 2xx!") return } let parsedResult: AnyObject! var photoObjects = [Interestingness]() let apiError = FlickrAPIError() do { parsedResult = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) let stat = parsedResult[FlickrAPIConstants.FlickrAPIKeys.RESPONSE_STAT] as! String! // API returned an error handle it if stat == FlickrAPIConstants.FlickrAPIValues.RESPONSE_MESSAGE_FAIL { apiError.stat = stat apiError.code = parsedResult[FlickrAPIConstants.FlickrAPIKeys.RESPONSE_CODE] as? NSNumber! apiError.message = parsedResult[FlickrAPIConstants.FlickrAPIKeys.RESPONSE_MESSAGE] as? String! errorHandler(apiError) return } // Process each photo object let photos = parsedResult["photos"] as! [String:AnyObject] for photo in photos["photo"] as! [[String:AnyObject]] { let interestingness = Interestingness() interestingness.setValuesForKeysWithDictionary(photo) let iconfarm = "\(interestingness.iconfarm as! NSNumber)" let profilePhotoUrl = staticProfilePhotoUrlFromParams(iconfarm, icon_server: interestingness.iconserver as! String, id: interestingness.owner as! String) interestingness.profilePhotoUrl = profilePhotoUrl photoObjects.append(interestingness) } completionHandler(photoObjects) } catch { displayError("Could not parse the data as JSON: '\(data)'") return } print("photos data \(photoObjects)") } task.resume() } }
beaae75ff2d857148ea62dbfa8282182
32.168421
158
0.715011
false
false
false
false
CodaFi/swift
refs/heads/master
test/DebugInfo/returnlocation.swift
apache-2.0
21
// RUN: %target-swift-frontend -g -emit-ir %s -o %t.ll // REQUIRES: objc_interop import Foundation // This file contains linetable testcases for all permutations // of simple/complex/empty return expressions, // cleanups/no cleanups, single / multiple return locations. // RUN: %FileCheck %s --check-prefix=CHECK_NONE < %t.ll // CHECK_NONE: define{{( protected)?}} {{.*}}void {{.*}}none public func none(_ a: inout Int64) { // CHECK_NONE: call void @llvm.dbg{{.*}}, !dbg // CHECK_NONE: store i64{{.*}}, !dbg ![[NONE_INIT:.*]] a -= 2 // CHECK_NONE: ret {{.*}}, !dbg ![[NONE_RET:.*]] // CHECK_NONE: ![[NONE_INIT]] = !DILocation(line: [[@LINE-2]], column: // CHECK_NONE: ![[NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_EMPTY < %t.ll // CHECK_EMPTY: define {{.*}}empty public func empty(_ a: inout Int64) { if a > 24 { // CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET1:.*]] // CHECK-DAG_EMPTY_RET1: ![[EMPTY_RET1]] = !DILocation(line: [[@LINE+1]], column: 6, return } a -= 2 // CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET2:.*]] // CHECK-DAG_EMPTY_RET2: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 3, return // CHECK-DAG_EMPTY: ret {{.*}}, !dbg ![[EMPTY_RET:.*]] // CHECK-DAG_EMPTY: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_EMPTY_NONE < %t.ll // CHECK_EMPTY_NONE: define {{.*}}empty_none public func empty_none(_ a: inout Int64) { if a > 24 { return } a -= 2 // CHECK_EMPTY_NONE: ret {{.*}}, !dbg ![[EMPTY_NONE_RET:.*]] // CHECK_EMPTY_NONE: ![[EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_RET < %t.ll // CHECK_SIMPLE_RET: define {{.*}}simple public func simple(_ a: Int64) -> Int64 { if a > 24 { return 0 } return 1 // CHECK_SIMPLE_RET: ret i{{.*}}, !dbg ![[SIMPLE_RET:.*]] // CHECK_SIMPLE_RET: ![[SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_RET < %t.ll // CHECK_COMPLEX_RET: define {{.*}}complex public func complex(_ a: Int64) -> Int64 { if a > 24 { return a*a } return a/2 // CHECK_COMPLEX_RET: ret i{{.*}}, !dbg ![[COMPLEX_RET:.*]] // CHECK_COMPLEX_RET: ![[COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_SIMPLE < %t.ll // CHECK_COMPLEX_SIMPLE: define {{.*}}complex_simple public func complex_simple(_ a: Int64) -> Int64 { if a > 24 { return a*a } return 2 // CHECK_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[COMPLEX_SIMPLE_RET:.*]] // CHECK_COMPLEX_SIMPLE: ![[COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_COMPLEX < %t.ll // CHECK_SIMPLE_COMPLEX: define {{.*}}simple_complex public func simple_complex(_ a: Int64) -> Int64 { if a > 24 { return a*a } return 2 // CHECK_SIMPLE_COMPLEX: ret {{.*}}, !dbg ![[SIMPLE_COMPLEX_RET:.*]] // CHECK_SIMPLE_COMPLEX: ![[SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // --------------------------------------------------------------------- // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_NONE < %t.ll // CHECK_CLEANUP_NONE: define {{.*}}cleanup_none public func cleanup_none(_ a: inout NSString) { a = "empty" // CHECK_CLEANUP_NONE: ret void, !dbg ![[CLEANUP_NONE_RET:.*]] // CHECK_CLEANUP_NONE: ![[CLEANUP_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY < %t.ll // CHECK_CLEANUP_EMPTY: define {{.*}}cleanup_empty public func cleanup_empty(_ a: inout NSString) { if a.length > 24 { return } a = "empty" return // CHECK_CLEANUP_EMPTY: ret void, !dbg ![[CLEANUP_EMPTY_RET:.*]] // CHECK_CLEANUP_EMPTY: ![[CLEANUP_EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY_NONE < %t.ll // CHECK_CLEANUP_EMPTY_NONE: define {{.*}}cleanup_empty_none public func cleanup_empty_none(_ a: inout NSString) { if a.length > 24 { return } a = "empty" // CHECK_CLEANUP_EMPTY_NONE: ret {{.*}}, !dbg ![[CLEANUP_EMPTY_NONE_RET:.*]] // CHECK_CLEANUP_EMPTY_NONE: ![[CLEANUP_EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_RET < %t.ll // CHECK_CLEANUP_SIMPLE_RET: define {{.*}}cleanup_simple public func cleanup_simple(_ a: NSString) -> Int64 { if a.length > 24 { return 0 } return 1 // CHECK_CLEANUP_SIMPLE_RET: ret {{.*}}, !dbg ![[CLEANUP_SIMPLE_RET:.*]] // CHECK_CLEANUP_SIMPLE_RET: ![[CLEANUP_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX < %t.ll // CHECK_CLEANUP_COMPLEX: define {{.*}}cleanup_complex public func cleanup_complex(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return Int64(a.length/2) // CHECK_CLEANUP_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_RET:.*]] // CHECK_CLEANUP_COMPLEX: ![[CLEANUP_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX_SIMPLE < %t.ll // CHECK_CLEANUP_COMPLEX_SIMPLE: define {{.*}}cleanup_complex_simple public func cleanup_complex_simple(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return 2 // CHECK_CLEANUP_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_SIMPLE_RET:.*]] // CHECK_CLEANUP_COMPLEX_SIMPLE: ![[CLEANUP_COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_COMPLEX < %t.ll // CHECK_CLEANUP_SIMPLE_COMPLEX: define {{.*}}cleanup_simple_complex public func cleanup_simple_complex(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return 2 // CHECK_CLEANUP_SIMPLE_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_SIMPLE_COMPLEX_RET:.*]] // CHECK_CLEANUP_SIMPLE_COMPLEX: ![[CLEANUP_SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // --------------------------------------------------------------------- // RUN: %FileCheck %s --check-prefix=CHECK_INIT < %t.ll // CHECK_INIT: define {{.*}}$s4main6Class1CACSgycfc public class Class1 { public required init?() { print("hello") // CHECK_INIT: call {{.*}}@"$ss5print_9separator10terminatoryypd_S2StF"{{.*}}, !dbg [[printLoc:![0-9]+]] // CHECK_INIT: ret i{{32|64}} 0, !dbg [[retnLoc:![0-9]+]] // CHECK_INIT: [[retnLoc]] = !DILocation(line: 0 // CHECK_INIT: [[printLoc]] = !DILocation(line: [[@LINE-5]] return nil } }
c659cb8ec5f6d2ab60c22c1117740c02
33.968912
110
0.599793
false
false
false
false
PeeJWeeJ/SwiftyHUD
refs/heads/master
SwiftyHUD/SwiftyHUD/SwiftyHUD/SwiftyHUDModule/SwiftyHUDView.swift
mit
1
// // PWHudView.swift // SVProgressHUD // // Created by Paul Fechner on 12/28/15. // Copyright © 2015 EmbeddedSources. All rights reserved. // import UIKit class SwiftyHUDView: UIView { @IBOutlet weak var blurVisualEffectView: UIVisualEffectView! @IBOutlet weak var mainHudView: UIView! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var progressIndicator: UIActivityIndicatorView! @IBOutlet weak var indicationImage: UIImageView! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var cancelButton: UIButton! var hudOptions: HudOptions; override init(frame: CGRect) { self.hudOptions = HudOptions() super.init(frame: frame) self.hidden = true } convenience init(frame: CGRect, hudOptions: HudOptions){ self.init(frame: frame) self.hudOptions = hudOptions update() } required init?(coder aDecoder: NSCoder) { self.hudOptions = HudOptions() super.init(coder: aDecoder) self.hidden = true } func setupForOptions(options: HudOptions){ self.hudOptions = options update() } private func update(){ setupForBlurEffect() setupProgressIndicator() setupIndicationImage() setupMessageLabel() setupCancelButton() setupBackground() mainHudView.layer.cornerRadius = 25 } private func setupForBlurEffect(){ if let blurStyle = hudOptions.hudStyle.getBlurStyle() { let effectsView = getBlurEffect(true, blurStyle: blurStyle) effectsView.addConstraints(blurVisualEffectView.constraints) blurVisualEffectView.removeFromSuperview() effectsView.frame = mainHudView.bounds self.blurVisualEffectView = effectsView mainHudView.insertSubview(self.blurVisualEffectView, atIndex: 0) } } private func setupProgressIndicator(){ if( hudOptions.hudAnimationType == .Native) { progressIndicator.startAnimating() progressIndicator.hidden = false if hudOptions.hudStyle == .Light { progressIndicator.color = UIColor.blackColor() } else{ progressIndicator.color = UIColor.whiteColor() } } else{ progressIndicator.hidden = true } } private func setupIndicationImage() { if let image = hudOptions.statusImageOption.getImage() { indicationImage.image = image indicationImage.hidden = false } else if let image = hudOptions.statusImage { indicationImage.image = image indicationImage.hidden = false } else{ indicationImage.hidden = true } } private func setupMessageLabel(){ if let labelText = hudOptions.message { messageLabel.text = labelText messageLabel.hidden = true } else{ messageLabel.hidden = false } if hudOptions.hudStyle == .Light { messageLabel.textColor = UIColor.blackColor() } else{ messageLabel.textColor = UIColor.whiteColor() } } private func setupCancelButton(){ if let buttonText = hudOptions.buttonMessage { cancelButton.titleLabel?.text = buttonText cancelButton.hidden = false } else { cancelButton.hidden = true } } private func setupBackground(){ hudOptions.hudMaskType.maskLayer(self.layer) } func show(){ show(0.4, delay: 0) } func show(duration: NSTimeInterval, delay: NSTimeInterval){ dispatch_async(dispatch_get_main_queue(), { UIView.animateWithDuration(duration, delay: delay, options: .CurveEaseOut, animations: { () -> Void in self.hidden = false }, completion: nil) }) } @IBAction func cancelButtonPressed(sender: AnyObject) { } class func addToScreen(){ let view: PWHUDView = UIView.fromNib() view.frame = UIScreen.mainScreen().bounds for window in UIApplication.sharedApplication().windows.reverse() { let windowOnMainScreen = window.screen == UIScreen.mainScreen() let windowIsVisible = !window.hidden && window.alpha > 0 let windowLevelNormal = window.windowLevel == UIWindowLevelNormal if(windowOnMainScreen && windowIsVisible && windowLevelNormal){ window.addSubview(view) break; } } if let superView = view.superview { superView.bringSubviewToFront(view) } view.update() view.show() } }
3795edc6013d1764ee7d8bbe2680c51e
20.891304
105
0.72567
false
false
false
false
JamieScanlon/AugmentKit
refs/heads/master
AugmentKit/AKCore/Primatives/AKAnimatable.swift
mit
1
// // AKAnimatable.swift // AugmentKit // // MIT License // // Copyright (c) 2018 JamieScanlon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation // MARK: - AKAnimatable /** Describes a animatable value. That is, a value that changes over time. */ public protocol AKAnimatable { associatedtype Value /** Retrieve a value. - Parameters: - forTime: The current `TimeInterval` - Returns: The value */ func value(forTime: TimeInterval) -> Value } // MARK: - AKPulsingAnimatable /** Describes an `AKAnimatable` that oscillates between a `minValue` and `maxValue` over a time `period` */ public protocol AKPulsingAnimatable: AKAnimatable { /** The minumum value. */ var minValue: Value { get } /** The maximum value. */ var maxValue: Value { get } /** The period. */ var period: TimeInterval { get } /** The offset to apply to the animation. */ var periodOffset: TimeInterval { get } } extension AKPulsingAnimatable where Value == Double { /** Retrieve a value. Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is a `Double` - Parameters: - forTime: The current `TimeInterval` - Returns: The value */ public func value(forTime time: TimeInterval) -> Value { let delta = maxValue - minValue let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period return minValue + delta * (0.5 + 0.5 * cos(2 * Double.pi * progress)) } } extension AKPulsingAnimatable where Value == Float { /** Retrieve a value. Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is a `Float` - Parameters: - forTime: The current `TimeInterval` - Returns: The value */ public func value(forTime time: TimeInterval) -> Value { let delta = Double(maxValue - minValue) let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period return minValue + Float(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress))) } } extension AKPulsingAnimatable where Value == Int { /** Retrieve a value. Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is an `Int` - Parameters: - forTime: The current `TimeInterval` - Returns: The value */ public func value(forTime time: TimeInterval) -> Value { let delta = Double(maxValue - minValue) let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period return minValue + Int(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress))) } } extension AKPulsingAnimatable where Value == UInt { /** Retrieve a value. Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is a `UInt` - Parameters: - forTime: The current `TimeInterval` - Returns: The value */ public func value(forTime time: TimeInterval) -> Value { let delta = Double(maxValue - minValue) let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period return minValue + UInt(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress))) } } extension AKPulsingAnimatable where Value == Any { /** Retrieve a value. Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is a `Any`. This implementation checks if `Any` can be downcast to `double`, `Float`, `Int`, or `UInt` and performs the calculations, returning `minValue` otherwise - Parameters: - forTime: The current `TimeInterval` - Returns: The value */ public func value(forTime time: TimeInterval) -> Value { if let aMinValue = minValue as? Double, let aMaxValue = maxValue as? Double { let delta = aMaxValue - aMinValue let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period return aMinValue + delta * (0.5 + 0.5 * cos(2 * Double.pi * progress)) } else if let aMinValue = minValue as? Float, let aMaxValue = maxValue as? Float { let delta = Double(aMaxValue - aMinValue) let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period return aMinValue + Float(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress))) } else if let aMinValue = minValue as? Int, let aMaxValue = maxValue as? Int { let delta = Double(aMaxValue - aMinValue) let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period return aMinValue + Int(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress))) } else if let aMinValue = minValue as? UInt, let aMaxValue = maxValue as? UInt { let delta = Double(aMaxValue - aMinValue) let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period return aMinValue + UInt(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress))) } else { return minValue } } }
4e3ff3447fd11e4a82a5df22915684d1
35.707602
157
0.645531
false
false
false
false
RevenueCat/purchases-ios
refs/heads/main
Tests/UnitTests/Mocks/MockETagManager.swift
mit
1
// // MockETagManager.swift // PurchasesTests // // Created by César de la Vega on 4/20/21. // Copyright © 2021 Purchases. All rights reserved. // import Foundation @testable import RevenueCat // swiftlint:disable type_name class MockETagManager: ETagManager { var invokedETagHeader = false var invokedETagHeaderCount = 0 var invokedETagHeaderParameters: (urlRequest: URLRequest, refreshETag: Bool)? var invokedETagHeaderParametersList = [(urlRequest: URLRequest, refreshETag: Bool)]() var stubbedETagHeaderResult: [String: String]! = [:] override func eTagHeader(for urlRequest: URLRequest, refreshETag: Bool = false) -> [String: String] { return lock.perform { invokedETagHeader = true invokedETagHeaderCount += 1 invokedETagHeaderParameters = (urlRequest, refreshETag) invokedETagHeaderParametersList.append((urlRequest, refreshETag)) return stubbedETagHeaderResult } } private struct InvokedHTTPResultFromCacheOrBackendParams { let response: HTTPURLResponse let body: Data? let request: URLRequest let retried: Bool } var invokedHTTPResultFromCacheOrBackend = false var invokedHTTPResultFromCacheOrBackendCount = 0 private var invokedHTTPResultFromCacheOrBackendParameters: InvokedHTTPResultFromCacheOrBackendParams? private var invokedHTTPResultFromCacheOrBackendParametersList = [InvokedHTTPResultFromCacheOrBackendParams]() var stubbedHTTPResultFromCacheOrBackendResult: HTTPResponse<Data>! var shouldReturnResultFromBackend = true override func httpResultFromCacheOrBackend(with response: HTTPURLResponse, data: Data?, request: URLRequest, retried: Bool) -> HTTPResponse<Data>? { return lock.perform { invokedHTTPResultFromCacheOrBackend = true invokedHTTPResultFromCacheOrBackendCount += 1 let params = InvokedHTTPResultFromCacheOrBackendParams( response: response, body: data, request: request, retried: retried ) invokedHTTPResultFromCacheOrBackendParameters = params invokedHTTPResultFromCacheOrBackendParametersList.append(params) if shouldReturnResultFromBackend { return HTTPResponse(statusCode: .init(rawValue: response.statusCode), body: data) .asOptionalResponse } return stubbedHTTPResultFromCacheOrBackendResult } } var invokedClearCaches = false var invokedClearCachesCount = 0 override func clearCaches() { lock.perform { invokedClearCaches = true invokedClearCachesCount += 1 } } private let lock = Lock() }
4d37a5d0fc5fcb7eb4c28cdec8b58b92
35.395062
113
0.658073
false
false
false
false
jkereako/InlinePicker
refs/heads/master
Tests/UnitTests/TableViewController/RowSelectionTests.swift
mit
1
// // RowSelectionTests.swift // InlinePicker // // Created by Jeffrey Kereakoglow on 4/28/16. // Copyright © 2016 Alexis Digital. All rights reserved. // import XCTest @testable import InlinePicker final class RowSelectionTests: TableViewControllerTestCase { /// A tap on the picker view cell ought to have no effect. This test simulates a tap on the picker /// view cell. func testSelectionOfSubtitleCellCreatesAPickerCellBelow() { let rowIndex = 3 // This code is identical to the test above it. Uncertain if it's bad practice. let subtitleCellIndexPath = NSIndexPath(forRow: rowIndex, inSection: 0) let subtitleCell = sut.tableView(sut.tableView, cellForRowAtIndexPath: subtitleCellIndexPath) XCTAssertNotNil(subtitleCell) XCTAssertTrue(subtitleCell is SubtitleCell) sut.tableView(sut.tableView, didSelectRowAtIndexPath: subtitleCellIndexPath) let pickerCellIndexPath = NSIndexPath(forRow: rowIndex + 1, inSection: 0) let pickerCell = sut.tableView(sut.tableView, cellForRowAtIndexPath: pickerCellIndexPath) XCTAssertNotNil(pickerCell) XCTAssertTrue(pickerCell is PickerCell) } /// A tap on the picker view cell ought to have no effect. This test simulates a tap on the picker /// view cell. func testSelectionOfSubtitleCellWithPickerCellBelowRemovesPickerCell() { let rowIndex = 1 // First, assert that we have a subtitle cell and a picker cell below it. let subtitleCellIndexPath = NSIndexPath(forRow: rowIndex, inSection: 0) let subtitleCell1 = sut.tableView(sut.tableView, cellForRowAtIndexPath: subtitleCellIndexPath) XCTAssertNotNil(subtitleCell1) XCTAssertTrue(subtitleCell1 is SubtitleCell) let pickerCellIndexPath = NSIndexPath(forRow: rowIndex + 1, inSection: 0) let pickerCell = sut.tableView(sut.tableView, cellForRowAtIndexPath: pickerCellIndexPath) XCTAssertNotNil(pickerCell) XCTAssertTrue(pickerCell is PickerCell) sut.tableView(sut.tableView, didSelectRowAtIndexPath: subtitleCellIndexPath) // Assert that the subtitle row did not change after selection let subtitleCell2 = sut.tableView(sut.tableView, cellForRowAtIndexPath: subtitleCellIndexPath) XCTAssertNotNil(subtitleCell2) XCTAssertTrue(subtitleCell2 is SubtitleCell) XCTAssertEqual(subtitleCell1.textLabel?.text, subtitleCell2.textLabel?.text) // Assert that the pickerview did change let subtitleCell3 = sut.tableView(sut.tableView, cellForRowAtIndexPath: pickerCellIndexPath) XCTAssertNotNil(subtitleCell3) XCTAssertTrue(subtitleCell3 is SubtitleCell) } /// A tap on the picker view cell ought to have no effect. This test simulates a tap on the picker /// view cell. func testSelectionOfPickerCellDoesNothing() { // This code is identical to the test above it. Uncertain if it's bad practice. let indexPath = NSIndexPath(forRow: 2, inSection: 0) let pickerCell = sut.tableView(sut.tableView, cellForRowAtIndexPath: indexPath) XCTAssertNotNil(pickerCell) XCTAssertTrue(pickerCell is PickerCell) sut.tableView(sut.tableView, didSelectRowAtIndexPath: indexPath) let subtitleCell = sut.tableView(sut.tableView, cellForRowAtIndexPath: indexPath) XCTAssertNotNil(subtitleCell) XCTAssertTrue(subtitleCell is PickerCell) } }
bab5528d6aedf7a4a4985aa137d28fe3
37.488372
100
0.770997
false
true
false
false
LedgerHQ/u2f-ble-test-ios
refs/heads/master
u2f-ble-test-ios/Utils/DataReader.swift
apache-2.0
1
// // DataReader.swift // ledger-wallet-ios // // Created by Nicolas Bigot on 11/02/2016. // Copyright © 2016 Ledger. All rights reserved. // import Foundation final class DataReader { private let internalData: NSMutableData var remainingBytesLength: Int { return internalData.length } // MARK: Read methods func readNextInt8() -> Int8? { return readNextInteger() } func readNextUInt8() -> UInt8? { return readNextInteger() } func readNextBigEndianUInt16() -> UInt16? { return readNextInteger(bigEndian: true) } func readNextLittleEndianUInt16() -> UInt16? { return readNextInteger(bigEndian: false) } func readNextBigEndianInt16() -> Int16? { return readNextInteger(bigEndian: true) } func readNextLittleEndianInt16() -> Int16? { return readNextInteger(bigEndian: false) } func readNextBigEndianUInt32() -> UInt32? { return readNextInteger(bigEndian: true) } func readNextLittleEndianUInt32() -> UInt32? { return readNextInteger(bigEndian: false) } func readNextBigEndianInt32() -> Int32? { return readNextInteger(bigEndian: true) } func readNextLittleEndianInt32() -> Int32? { return readNextInteger(bigEndian: false) } func readNextBigEndianUInt64() -> UInt64? { return readNextInteger(bigEndian: true) } func readNextLittleEndianUInt64() -> UInt64? { return readNextInteger(bigEndian: false) } func readNextBigEndianInt64() -> Int64? { return readNextInteger(bigEndian: true) } func readNextLittleEndianInt64() -> Int64? { return readNextInteger(bigEndian: false) } func readNextAvailableData() -> NSData? { return readNextDataOfLength(remainingBytesLength) } func readNextDataOfLength(length: Int) -> NSData? { guard length > 0 else { return nil } guard internalData.length >= length else { return nil } let data = internalData.subdataWithRange(NSMakeRange(0, length)) internalData.replaceBytesInRange(NSMakeRange(0, length), withBytes: nil, length: 0) return data } func readNextMutableDataOfLength(length: Int) -> NSMutableData? { if let data = readNextDataOfLength(length) { return NSMutableData(data: data) } return nil } // MARK: Internal methods private func readNextInteger<T: IntegerType>() -> T? { guard let data = readNextDataOfLength(sizeof(T)) else { return nil } var value: T = 0 data.getBytes(&value, length: sizeof(T)) return value } private func readNextInteger<T: EndianConvertible>(bigEndian bigEndian: Bool) -> T? { guard let data = readNextDataOfLength(sizeof(T)) else { return nil } var value: T = 0 data.getBytes(&value, length: sizeof(T)) return bigEndian ? value.bigEndian : value.littleEndian } // MARK: Initialization init(data: NSData) { self.internalData = NSMutableData(data: data) } }
1c5f25334992c95e78d8d0439a3cc873
25.669421
91
0.621823
false
false
false
false
phatblat/WatchKitCoreData
refs/heads/master
WatchKitCoreData WatchKit Extension/InterfaceController.swift
mit
1
// // InterfaceController.swift // WatchKitCoreData WatchKit Extension // // Created by Ben Chatelain on 5/14/15. // Copyright (c) 2015 Ben Chatelain. All rights reserved. // import CoreData import Foundation import WatchKit import WatchKitCoreDataFramework @objc class InterfaceController: WKInterfaceController, DataConsumer { @IBOutlet weak var counterLabel: WKInterfaceLabel? var dataController: DataController? var timer: Timer? let notificationController = NotificationController(send: .Watch) // MARK: - NSObject deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override init() { super.init() // NSNotificationCenter.defaultCenter().addObserver(self, // selector: Selector("contextChanged:"), // name: NSManagedObjectContextDidSaveNotification, // object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("contextChanged:"), name: "ContextChanged", object: nil) } // MARK: - WKInterfaceController override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) println(NSHomeDirectory()) counterLabel?.setText("-1") dataController = AppGroupDataController() { [unowned self] () -> Void in self.timer = Timer(context: self.dataController!.mainContext) if let objects = self.fetchedResultsController.fetchedObjects as? [Counter], let counter = objects.first { self.counterLabel?.setText("\(counter.count)") } } } /// This method is called when watch view controller is about to be visible to user override func willActivate() { super.willActivate() } /// This method is called when watch view controller is no longer visible override func didDeactivate() { super.didDeactivate() } // MARK: - Data private lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "Counter") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "count", ascending: false)] fetchRequest.fetchBatchSize = 1 let context = self.dataController?.mainContext let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context!, sectionNameKeyPath: nil, cacheName: nil) var error: NSError? if !controller.performFetch(&error) { println("Error fetching \(error)") } controller.delegate = self.fetchedResultsControllerDelegate return controller }() private lazy var fetchedResultsControllerDelegate: FetchedResultsControllerDelegate = { let delegate = FetchedResultsControllerDelegate() delegate.onUpdate = { [weak self] (object: AnyObject) in println("onUpdate") if let counter = object as? Counter { self?.counterLabel?.setText("\(counter.count)") } } return delegate }() // MARK: - Notification Handler @objc func contextChanged(notification: NSNotification) { println("contextChanged:") } // MARK: - IBActions @IBAction func start() { timer?.start() } @IBAction func stop() { timer?.stop() } @IBAction func reset() { timer?.reset() } }
b88421bf8a3253c22c25de0111d37b89
26.609375
91
0.636955
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios-demo
refs/heads/master
AwesomeAdsDemo/MainController.swift
apache-2.0
1
// // MainController.swift // AwesomeAdsDemo // // Created by Gabriel Coman on 29/06/2017. // Copyright © 2017 Gabriel Coman. All rights reserved. // import UIKit import QuartzCore import SuperAwesome import RxSwift import RxCocoa class MainController: SABaseViewController { @IBOutlet weak var changeCompButton: UIButton! @IBOutlet weak var appPlacementSearch: UISearchBar! @IBOutlet weak var headerView: UIView! @IBOutlet weak var tableView: UITableView! var viewModel: MainViewModel = MainViewModel () var dataSource: MainDataSource = MainDataSource () fileprivate var recogn: UITapGestureRecognizer! override func viewDidLoad() { super.viewDidLoad() changeCompButton.setTitle("page_main_change_company".localized, for: .normal) appPlacementSearch.placeholder = "page_main_search_placeholder".localized headerView.layer.masksToBounds = false headerView.layer.shadowOffset = CGSize(width: 0, height: 3.5) headerView.layer.shadowRadius = 1 headerView.layer.shadowOpacity = 0.125 recogn = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) dataSource.delegate = self tableView.delegate = dataSource tableView.dataSource = dataSource tableView.estimatedRowHeight = 180 tableView.rowHeight = UITableView.automaticDimension } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) store?.dispatch(Event.loadApps(forCompany: store.company.id!, andJwtToken: store.jwtToken)) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) self.appPlacementSearch.resignFirstResponder() self.appPlacementSearch.text = "" } override func handle(_ state: AppState) { changeCompButton.isHidden = !(state.profileState?.canImpersonate ?? true) viewModel.data = state.appState.filtered dataSource.sections = viewModel.sections tableView.reloadData() } } extension MainController: MainDataSourceDelegate { func didSelect(placementId placId: Int?) { store?.dispatch(Event.SelectPlacement(placementId: placId)) performSegue("MainToCreatives") } } extension MainController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { store?.dispatch(Event.FilterApps(withSearchTerm: searchText)) } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { self.view.addGestureRecognizer(recogn) } @objc func handleTap(_ sender: UITapGestureRecognizer) { self.appPlacementSearch.resignFirstResponder() self.view.removeGestureRecognizer(recogn) } }
6c8583b9de48a18a98b57d20f94cdc97
31.727273
99
0.693056
false
false
false
false
danielmartin/swift
refs/heads/master
stdlib/public/core/StringNormalization.swift
apache-2.0
1
//===--- StringNormalization.swift ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims internal enum _Normalization { // ICU's NFC unorm2 instance // // TODO(String performance): Should we cache one on TLS? Is this an expensive // call? internal static var _nfcNormalizer: OpaquePointer = { var err = __swift_stdlib_U_ZERO_ERROR let normalizer = __swift_stdlib_unorm2_getNFCInstance(&err) guard err.isSuccess else { // This shouldn't be possible unless some deep (unrecoverable) system // invariants are violated fatalError("Unable to talk to ICU") } return normalizer }() // When normalized in NFC, some segments may expand in size (e.g. some non-BMP // musical notes). This expansion is capped by the maximum expansion factor of // the normal form. For NFC, that is 3x. internal static let _maxNFCExpansionFactor = 3 } extension Unicode.Scalar { // Normalization boundary - a place in a string where everything left of the // boundary can be normalized independently from everything right of the // boundary. The concatenation of each result is the same as if the entire // string had been normalized as a whole. // // Normalization segment - a sequence of code units between two normalization // boundaries (without any boundaries in the middle). Note that normalization // segments can, as a process of normalization, expand, contract, and even // produce new sub-segments. // Whether this scalar value always has a normalization boundary before it. @inline(__always) // common fast-path internal var _hasNormalizationBoundaryBefore: Bool { // Fast-path: All scalars up through U+02FF are NFC and have boundaries // before them if self.value < 0x300 { return true } _internalInvariant(Int32(exactly: self.value) != nil, "top bit shouldn't be set") let value = Int32(bitPattern: self.value) return 0 != __swift_stdlib_unorm2_hasBoundaryBefore( _Normalization._nfcNormalizer, value) } @inline(__always) // common fast-path internal var _isNFCQCYes: Bool { // Fast-path: All scalars up through U+02FF are NFC and have boundaries // before them if self.value < 0x300 { return true } return __swift_stdlib_u_getIntPropertyValue( Builtin.reinterpretCast(value), __swift_stdlib_UCHAR_NFC_QUICK_CHECK ) == 1 } // Quick check if a scalar is NFC and a segment starter internal var _isNFCStarter: Bool { // Otherwise, consult the properties return self._hasNormalizationBoundaryBefore && self._isNFCQCYes } } internal func _tryNormalize( _ input: UnsafeBufferPointer<UInt16>, into outputBuffer: UnsafeMutablePointer<_Normalization._SegmentOutputBuffer> ) -> Int? { return _tryNormalize(input, into: _castOutputBuffer(outputBuffer)) } internal func _tryNormalize( _ input: UnsafeBufferPointer<UInt16>, into outputBuffer: UnsafeMutableBufferPointer<UInt16> ) -> Int? { var err = __swift_stdlib_U_ZERO_ERROR let count = __swift_stdlib_unorm2_normalize( _Normalization._nfcNormalizer, input.baseAddress._unsafelyUnwrappedUnchecked, numericCast(input.count), outputBuffer.baseAddress._unsafelyUnwrappedUnchecked, numericCast(outputBuffer.count), &err ) guard err.isSuccess else { // The output buffer needs to grow return nil } return numericCast(count) }
29337a3762cfb80a1560adb6892e62c2
35.75
85
0.695971
false
false
false
false
hi-hu/Hu-Tumbler
refs/heads/master
Hu-Tumbler/FadeTransition.swift
mit
1
// // FadeTransition.swift // transitionDemo // // Created by Timothy Lee on 11/4/14. // Copyright (c) 2014 Timothy Lee. All rights reserved. // import UIKit class FadeTransition: BaseTransition { override func presentTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) { var composeView = toViewController as ComposeViewController composeView.view.alpha = 0 composeView.doAnimate(true) UIView.animateWithDuration(duration, animations: { composeView.view.alpha = 1 }) { (finished: Bool) -> Void in self.finish() } } override func dismissTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) { var composeView = fromViewController as ComposeViewController composeView.view.alpha = 1 composeView.doAnimate(false) UIView.animateWithDuration(0.8, animations: { composeView.view.alpha = 0 }) { (finished: Bool) -> Void in self.finish() } } }
644a2262331586e37bc546b64c483994
28.425
134
0.636364
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/TableviewCells/InAppRewardCell.swift
gpl-3.0
1
// // InAppRewardCell.swift // Habitica // // Created by Phillip on 21.08.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit import Habitica_Models class InAppRewardCell: UICollectionViewCell { @IBOutlet weak var imageView: NetworkImageView! @IBOutlet weak var currencyView: HRPGCurrencyCountView! @IBOutlet weak var infoImageView: UIImageView! @IBOutlet weak var infoLabel: UILabel! @IBOutlet weak var pinnedIndicatorView: UIImageView! @IBOutlet weak var purchaseConfirmationView: UIImageView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var currencyBackgroundView: UIView! @IBOutlet weak var unlockLabel: UILabel! private var itemName = "" var itemsLeft = 0 { didSet { if itemsLeft > 0 { infoLabel.isHidden = false infoLabel.text = String(describing: itemsLeft) infoLabel.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor infoLabel.textColor = ThemeService.shared.theme.ternaryTextColor } else { infoImageView.isHidden = true infoLabel.isHidden = true } } } private var isLocked = false { didSet { if isLocked { if (ThemeService.shared.theme.isDark) { infoImageView.image = HabiticaIcons.imageOfItemIndicatorLockedDark() } else { infoImageView.image = HabiticaIcons.imageOfItemIndicatorLocked() } infoImageView.isHidden = false infoLabel.isHidden = true } else { infoImageView.isHidden = true infoLabel.isHidden = true } } } private var availableUntil: Date? = nil { didSet { if availableUntil != nil { infoImageView.image = HabiticaIcons.imageOfItemIndicatorLimited() infoImageView.isHidden = false infoLabel.isHidden = true } else if isLocked == false { infoImageView.isHidden = true infoLabel.isHidden = true } } } public var imageName = "" { didSet { if imageName.isEmpty { return } if imageName.contains(" ") { imageView.setImagewith(name: imageName.components(separatedBy: " ")[1]) } else { imageView.setImagewith(name: imageName) } } } public var isPinned = false { didSet { pinnedIndicatorView.isHidden = !isPinned if isPinned { pinnedIndicatorView.image = HabiticaIcons.imageOfPinnedItem } } } func configure(reward: InAppRewardProtocol, user: UserProtocol?) { var currency: Currency? let price = reward.value currencyView.amount = Int(reward.value) imageName = reward.imageName ?? "" itemName = reward.text ?? "" if let currencyString = reward.currency, let thisCurrency = Currency(rawValue: currencyString) { currencyView.currency = thisCurrency currency = thisCurrency } isLocked = reward.locked if let currency = currency { setCanAfford(price, currency: currency, user: user) } isPinned = false if let lastPurchased = reward.lastPurchased, wasRecentlyPurchased(lastPurchased) { showPurchaseConfirmation() } availableUntil = reward.availableUntil applyAccessibility() if let lockedReason = reward.shortLockedReason, reward.locked { unlockLabel.text = lockedReason unlockLabel.isHidden = false currencyView.isHidden = true } else { unlockLabel.isHidden = true currencyView.isHidden = false } let theme = ThemeService.shared.theme backgroundColor = theme.contentBackgroundColor containerView.backgroundColor = theme.windowBackgroundColor currencyBackgroundView.backgroundColor = theme.offsetBackgroundColor.withAlphaComponent(0.3) unlockLabel.textColor = theme.secondaryTextColor } func wasRecentlyPurchased(_ lastPurchase: Date) -> Bool { let now = Date().addingTimeInterval(-30) return now < lastPurchase } func showPurchaseConfirmation() { purchaseConfirmationView.image = HabiticaIcons.imageOfCheckmark(checkmarkColor: .white, percentage: 1.0) UIView.animate(withDuration: 0.25, animations: {[weak self] in self?.purchaseConfirmationView.alpha = 1 }, completion: {[weak self] (_) in UIView.animate(withDuration: 0.25, delay: 1.5, options: [], animations: { self?.purchaseConfirmationView.alpha = 0 }, completion: nil) }) } func setCanAfford(_ price: Float, currency: Currency, user: UserProtocol?) { var canAfford = false if let user = user { if currency == .gold { canAfford = price < user.stats?.gold ?? 0 } else { canAfford = true } } if canAfford && !isLocked { currencyView.state = .normal } else { currencyView.state = .locked } } private func applyAccessibility() { shouldGroupAccessibilityChildren = true currencyView.isAccessibilityElement = false isAccessibilityElement = true accessibilityLabel = "\(itemName), \(currencyView.accessibilityLabel ?? "")" } }
c9bda36b60a392ad5996ecf362552cfa
32.947368
112
0.585357
false
false
false
false
tonilopezmr/Learning-Swift
refs/heads/master
Learning-Swift/Learning-Swift/collections.swift
apache-2.0
1
// // collections.swift // Learning-Swift // // Created by Antonio López Marín on 21/11/17. // Copyright © 2017 Antonio López Marín. All rights reserved. // import Foundation func sayHello() -> String { return "Hello" } func collections() { print("** Arrays **") var array = [String]() array = ["Toni", "Sara"] print(array[0]) array += ["Uno más", "Otro", "Y otro"] print(array) array[2...4] = ["Todo en uno"] print(array) print("\n** Set **") let a: Set = [1, 2, 3, 4, 5, 6] print("A: \(a)") let b: Set = [4, 5, 6, 7, 8 , 9] print("B: \(b)" ) print("\nA intersect B: \(a.intersect(b).sort())") print("\nA union B: \(a.union(b).sort())") print("\nA subscract B: \(a.subtract(b).sort())") print("\nB subscract A: \(b.subtract(a).sort())") print("\nA union B substracting (A intersect B): \(a.union(b).subtract(a.intersect(b)).sort())") print("\n(A substract B) union (B substract A): \(a.subtract(b).union(b.subtract(a)).sort())") let oneTwo: Set = [1,2] print("[1, 2] is a subset of [1,2,3,4,5,6]: \(oneTwo.isSubsetOf(a))") print("\n ** Dictionary **") var dic = [Int: String]() //mutable dic[1] = "Toni" dic[2] = "Sara" dic = [:] print(dic) let inmu = [1: "Toni", 2: "Sara"] print(inmu[2]) }
7b6f8d6df9a9e4d429d35b5098d88ac9
22.982759
100
0.515827
false
false
false
false
proxpero/Flowchart
refs/heads/master
Flowchart/Flowchart/FlowChartViewController.swift
mit
1
// // FlowChartViewController.swift // Flowchart // // Created by Todd Olsen on 5/10/16. // Copyright © 2016 Todd Olsen. All rights reserved. // import UIKit class FlowChartViewController: UIViewController, SegueHandlerType { var flowchart = Flowchart( decision: Decision.IsEqualTo(5), yes: Process(transformation: { x in x - 1 }, title: "Decrement"), no: Process(transformation: { x in x + 1 }, title: "Increment") ) { didSet { evaluate() } } func evaluate() { outputField.text = "" if let s = inputField.text, n = Int(s) { let output = flowchart.transform(n) outputField.text = String(output) processTrueVC.isChosen = flowchart.decision.evaluate(n) == true processFalseVC.isChosen = flowchart.decision.evaluate(n) == false } } override func viewDidLoad() { super.viewDidLoad() for v in [nameField, inputField, outputField] { v.layer.cornerRadius = 5.0 v.layer.borderColor = UIColor.Steel.CGColor v.layer.borderWidth = 1.0 } } enum SegueIdentifier: String { case Decision = "DecisionViewControllerSegueIdentifier" case ProcessTrue = "ProcessTrueViewControllerSegueIdentifier" case ProcessFalse = "ProcessFalseViewControllerSegueIdentifier" case DecisionLibrary = "DecisionLibraryViewControllerSegueIdentifier" case ProcessLibrary = "ProcessLibraryViewControllerSegueIdentifier" } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch segueIdentifierForSegue(segue) { case .Decision: guard let vc = segue.destinationViewController as? DecisionViewController else { fatalError() } vc.decision = flowchart.decision vc.toggleDecisionLibrary = { self.decisionLibrary.hidden = !self.decisionLibrary.hidden self.activeProcess = nil } vc.updateCallback = { decision in self.flowchart = Flowchart( decision: decision, yes: self.flowchart.yes, no: self.flowchart.no, title: self.flowchart.title ) } decisionVC = vc case .ProcessTrue: guard let vc = segue.destinationViewController as? ProcessViewController else { fatalError() } vc.direction = .True vc.toggleProcessLibrary = { UIView.animateWithDuration(0.3) { if self.activeProcess == nil { self.activeProcess = .True } else { self.activeProcess = nil } } } vc.block = flowchart.yes processTrueVC = vc case .ProcessFalse: guard let vc = segue.destinationViewController as? ProcessViewController else { fatalError() } vc.direction = .False vc.toggleProcessLibrary = { if self.activeProcess == nil { self.activeProcess = .False } else { self.activeProcess = nil } } vc.block = flowchart.no processFalseVC = vc case .DecisionLibrary: guard let vc = segue.destinationViewController as? LibraryViewController else { fatalError() } vc.items = [("Decisions", Decision.store.map { $0 as LibraryCellConfigurator })] vc.didSelectItem = { cellConfig in guard let decision = cellConfig as? Decision else { fatalError() } self.decisionVC.decision = decision self.flowchart = Flowchart( decision: decision, yes: self.flowchart.yes, no: self.flowchart.no, title: self.flowchart.title ) } case .ProcessLibrary: guard let vc = segue.destinationViewController as? LibraryViewController else { fatalError() } vc.items = [ ("Processes", Process.store.map { $0 as LibraryCellConfigurator }), ("Flowchart", Flowchart.store.map { $0 as LibraryCellConfigurator }) ] vc.didSelectItem = { cellConfig in guard let flow = self.activeProcess else { return } guard let block = cellConfig as? Block else { return } switch flow { case .True: self.processTrueVC.block = block self.flowchart = Flowchart( decision: self.flowchart.decision, yes: block, no: self.flowchart.no, title: self.flowchart.title ) case .False: self.processFalseVC.block = block self.flowchart = Flowchart( decision: self.flowchart.decision, yes: self.flowchart.yes, no: block, title: self.flowchart.title ) } } processLibraryVC = vc } } var decisionVC: DecisionViewController! var processTrueVC: ProcessViewController! var processFalseVC: ProcessViewController! var processLibraryVC: LibraryViewController! override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) self.view.endEditing(true) } @IBAction func nameEditingDidEnd(sender: UITextField) { if let title = sender.text where !title.isEmpty { flowchart = Flowchart( decision: flowchart.decision, yes: flowchart.yes, no: flowchart.no, title: title) } } @IBAction func addFlowchartAction(sender: UIButton) { if Flowchart.store.filter({ $0.title == title }).count == 0 { Flowchart.store.append(flowchart) processLibraryVC.items[1].configurators = processLibraryVC.items[1].configurators + [flowchart] processLibraryVC.tableView.reloadData() } decisionVC.updateUI() processTrueVC.updateUI() processFalseVC.updateUI() nameField.text = "My New Flowchart" inputField.text = "0" decisionVC.decision = Decision.True processTrueVC.block = Process.init(transformation: { x in x }, title: "Identity") processFalseVC.block = Process.init(transformation: { x in x }, title: "Identity") self.flowchart = Flowchart( decision: Decision.True, yes: Process(transformation: { x in x }, title: "Identity"), no: Process(transformation: { x in x }, title: "Identity") ) } @IBAction func inputEditingDidEnd(sender: UITextField) { evaluate() } // OUTLETS @IBOutlet weak var nameField: UITextField! @IBOutlet weak var inputField: UITextField! @IBOutlet weak var outputField: UITextField! @IBOutlet weak var decisionLabel: UILabel! @IBOutlet weak var decisionInput: UITextField! @IBOutlet weak var processTrueView: UIView! @IBOutlet weak var processFalseView: UIView! @IBOutlet weak var decisionLibrary: UIView! @IBOutlet weak var processLibrary: UIView! private var activeProcess: ControlFlowDirection? { didSet { if activeProcess == nil { self.processLibrary.hidden = true self.processFalseView.layer.borderWidth = 0.0 self.processFalseView.layer.borderColor = nil self.processTrueView.layer.borderWidth = 0.0 self.processTrueView.layer.borderColor = nil } else if activeProcess! == .True { self.processLibrary.hidden = false self.processTrueView.layer.borderWidth = 3.0 self.processTrueView.layer.borderColor = UIColor.blueColor().CGColor self.processFalseView.layer.borderWidth = 0.0 self.processFalseView.layer.borderColor = nil } else { self.processLibrary.hidden = false self.processFalseView.layer.borderWidth = 3.0 self.processFalseView.layer.borderColor = UIColor.blueColor().CGColor self.processTrueView.layer.borderWidth = 0.0 self.processTrueView.layer.borderColor = nil } } } }
cda061416523e22274cd1e8d63d5b51f
33.830709
107
0.564259
false
false
false
false
SergeyPetrachkov/VIPERTemplates
refs/heads/master
Example/VIPERExample/VIPERExample/Welcome/WelcomeAssembly.swift
mit
1
// // WelcomeAssembly.swift // VIPERExample // // Created by Sergey Petrachkov on 20/09/2017. // Copyright (c) 2017 Sergey Petrachkov. All rights reserved. // // This file was generated by the SergeyPetrachkov VIPER Xcode Templates so // you can apply VIPER architecture to your iOS projects // import UIKit class WelcomeAssembly { // MARK: - Constants fileprivate static let storyboardId = "Main" fileprivate static let controllerStoryboardId = "WelcomeNav" // MARK: - Public methods static func createModule() -> UIViewController { if let navController = UIStoryboard(name: storyboardId, bundle: nil).instantiateViewController(withIdentifier: controllerStoryboardId) as? UINavigationController, let controller = navController.topViewController as? WelcomeViewController { let presenter = injectPresenter() presenter.output = controller presenter.view = controller controller.presenter = presenter return navController } else { fatalError("Could not create Welcome module!!! Check Welcome assembly") } } // MARK: - Private injections fileprivate static func injectPresenter() -> WelcomePresenterInput { let presenter = WelcomePresenter() let interactor = injectInteractor() interactor.output = presenter presenter.interactor = interactor let router = injectRouter() presenter.router = router return presenter } fileprivate static func injectInteractor() -> WelcomeInteractorInput { return WelcomeInteractor() } fileprivate static func injectRouter() -> WelcomeRoutingLogic { return WelcomeRouter() } }
913fe1ab1be03ffe86cbb56add6f2710
33.617021
166
0.735095
false
false
false
false
Daniel1of1/Venice
refs/heads/master
Modules/Venice/Sources/Venice/Select/Select.swift
mit
5
import CLibvenice protocol SelectCase { func register(_ clause: UnsafeMutableRawPointer, index: Int) func execute() } final class ChannelReceiveCase<T> : SelectCase { let channel: Channel<T> let closure: (T) -> Void init(channel: Channel<T>, closure: @escaping (T) -> Void) { self.channel = channel self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.registerReceive(clause, index: index) } func execute() { if let value = channel.getValueFromBuffer() { closure(value) } } } final class ReceivingChannelReceiveCase<T> : SelectCase { let channel: ReceivingChannel<T> let closure: (T) -> Void init(channel: ReceivingChannel<T>, closure: @escaping (T) -> Void) { self.channel = channel self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.registerReceive(clause, index: index) } func execute() { if let value = channel.getValueFromBuffer() { closure(value) } } } final class FallibleChannelReceiveCase<T> : SelectCase { let channel: FallibleChannel<T> var closure: (ChannelResult<T>) -> Void init(channel: FallibleChannel<T>, closure: @escaping (ChannelResult<T>) -> Void) { self.channel = channel self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.registerReceive(clause, index: index) } func execute() { if let result = channel.getResultFromBuffer() { closure(result) } } } final class FallibleReceivingChannelReceiveCase<T> : SelectCase { let channel: FallibleReceivingChannel<T> var closure: (ChannelResult<T>) -> Void init(channel: FallibleReceivingChannel<T>, closure: @escaping (ChannelResult<T>) -> Void) { self.channel = channel self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.registerReceive(clause, index: index) } func execute() { if let result = channel.getResultFromBuffer() { closure(result) } } } final class ChannelSendCase<T> : SelectCase { let channel: Channel<T> var value: T let closure: (Void) -> Void init(channel: Channel<T>, value: T, closure: @escaping (Void) -> Void) { self.channel = channel self.value = value self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.send(value, clause: clause, index: index) } func execute() { closure() } } final class SendingChannelSendCase<T> : SelectCase { let channel: SendingChannel<T> var value: T let closure: (Void) -> Void init(channel: SendingChannel<T>, value: T, closure: @escaping (Void) -> Void) { self.channel = channel self.value = value self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.send(value, clause: clause, index: index) } func execute() { closure() } } final class FallibleChannelSendCase<T> : SelectCase { let channel: FallibleChannel<T> let value: T let closure: (Void) -> Void init(channel: FallibleChannel<T>, value: T, closure: @escaping (Void) -> Void) { self.channel = channel self.value = value self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.send(value, clause: clause, index: index) } func execute() { closure() } } final class FallibleSendingChannelSendCase<T> : SelectCase { let channel: FallibleSendingChannel<T> let value: T let closure: (Void) -> Void init(channel: FallibleSendingChannel<T>, value: T, closure: @escaping (Void) -> Void) { self.channel = channel self.value = value self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.send(value, clause: clause, index: index) } func execute() { closure() } } final class FallibleChannelSendErrorCase<T> : SelectCase { let channel: FallibleChannel<T> let error: Error let closure: (Void) -> Void init(channel: FallibleChannel<T>, error: Error, closure: @escaping (Void) -> Void) { self.channel = channel self.error = error self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.send(error, clause: clause, index: index) } func execute() { closure() } } final class FallibleSendingChannelSendErrorCase<T> : SelectCase { let channel: FallibleSendingChannel<T> let error: Error let closure: (Void) -> Void init(channel: FallibleSendingChannel<T>, error: Error, closure: @escaping (Void) -> Void) { self.channel = channel self.error = error self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.send(error, clause: clause, index: index) } func execute() { closure() } } final class TimeoutCase<T> : SelectCase { let channel: Channel<T> let closure: (Void) -> Void init(channel: Channel<T>, closure: @escaping (Void) -> Void) { self.channel = channel self.closure = closure } func register(_ clause: UnsafeMutableRawPointer, index: Int) { channel.registerReceive(clause, index: index) } func execute() { closure() } } public class SelectCaseBuilder { var cases: [SelectCase] = [] var otherwise: ((Void) -> Void)? public func receive<T>(from channel: Channel<T>?, closure: @escaping (T) -> Void) { if let channel = channel { let selectCase = ChannelReceiveCase(channel: channel, closure: closure) cases.append(selectCase) } } public func receive<T>(from channel: ReceivingChannel<T>?, closure: @escaping (T) -> Void) { if let channel = channel { let selectCase = ReceivingChannelReceiveCase(channel: channel, closure: closure) cases.append(selectCase) } } public func receive<T>(from channel: FallibleChannel<T>?, closure: @escaping (ChannelResult<T>) -> Void) { if let channel = channel { let selectCase = FallibleChannelReceiveCase(channel: channel, closure: closure) cases.append(selectCase) } } public func receive<T>(from channel: FallibleReceivingChannel<T>?, closure: @escaping (ChannelResult<T>) -> Void) { if let channel = channel { let selectCase = FallibleReceivingChannelReceiveCase(channel: channel, closure: closure) cases.append(selectCase) } } public func send<T>(_ value: T, to channel: Channel<T>?, closure: @escaping (Void) -> Void) { if let channel = channel, !channel.closed { let selectCase = ChannelSendCase(channel: channel, value: value, closure: closure) cases.append(selectCase) } } public func send<T>(_ value: T, to channel: SendingChannel<T>?, closure: @escaping (Void) -> Void) { if let channel = channel, !channel.closed { let selectCase = SendingChannelSendCase(channel: channel, value: value, closure: closure) cases.append(selectCase) } } public func send<T>(_ value: T, to channel: FallibleChannel<T>?, closure: @escaping (Void) -> Void) { if let channel = channel, !channel.closed { let selectCase = FallibleChannelSendCase(channel: channel, value: value, closure: closure) cases.append(selectCase) } } public func send<T>(_ value: T, to channel: FallibleSendingChannel<T>?, closure: @escaping (Void) -> Void) { if let channel = channel, !channel.closed { let selectCase = FallibleSendingChannelSendCase(channel: channel, value: value, closure: closure) cases.append(selectCase) } } public func send<T>(_ error: Error, to channel: FallibleChannel<T>?, closure: @escaping (Void) -> Void) { if let channel = channel, !channel.closed { let selectCase = FallibleChannelSendErrorCase(channel: channel, error: error, closure: closure) cases.append(selectCase) } } public func send<T>(_ error: Error, to channel: FallibleSendingChannel<T>?, closure: @escaping (Void) -> Void) { if let channel = channel, !channel.closed { let selectCase = FallibleSendingChannelSendErrorCase(channel: channel, error: error, closure: closure) cases.append(selectCase) } } public func timeout(_ deadline: Double, closure: @escaping (Void) -> Void) { let done = Channel<Bool>() co { wake(at: deadline) done.send(true) } let selectCase = TimeoutCase<Bool>(channel: done, closure: closure) cases.append(selectCase) } public func otherwise(_ closure: @escaping (Void) -> Void) { self.otherwise = closure } } private func select(_ builder: SelectCaseBuilder) { mill_choose_init("select") var clauses: [UnsafeMutableRawPointer] = [] for (index, selectCase) in builder.cases.enumerated() { let clause = malloc(mill_clauselen())! clauses.append(clause) selectCase.register(clause, index: index) } if builder.otherwise != nil { mill_choose_otherwise() } let index = mill_choose_wait() if index == -1 { builder.otherwise?() } else { builder.cases[Int(index)].execute() } clauses.forEach(free) } public func select(_ build: (_ when: SelectCaseBuilder) -> Void) { let builder = SelectCaseBuilder() build(builder) select(builder) } public func sel(_ build: (_ when: SelectCaseBuilder) -> Void) { select(build) } public func forSelect(_ build: (_ when: SelectCaseBuilder, _ done: @escaping (Void) -> Void) -> Void) { let builder = SelectCaseBuilder() var keepRunning = true func done() { keepRunning = false } while keepRunning { let builder = SelectCaseBuilder() build(builder, done) select(builder) } } public func forSel(build: (_ when: SelectCaseBuilder, _ done: @escaping (Void) -> Void) -> Void) { forSelect(build) }
542957d125c1b698b703bd1bace4a0b1
27.912568
119
0.621811
false
false
false
false
klone1127/yuan
refs/heads/master
yuan/YPopularUserListViewController.swift
mit
1
// // 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. } */ }
bd6775438e872314ae46b22453f9285f
31.155172
123
0.685791
false
false
false
false
TMTBO/TTAImagePickerController
refs/heads/master
TTAImagePickerController/Classes/Views/TTACameraCell.swift
mit
1
// // TTACameraCell.swift // Pods-TTAImagePickerController_Example // // Created by TobyoTenma on 18/08/2017. // import UIKit class TTACameraCell: UICollectionViewCell { fileprivate let cameraLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() cameraLabel.frame = contentView.bounds } } extension TTACameraCell { func setupUI() { cameraLabel.font = UIFont.iconfont(size: UIFont.IconFontSize.cameraMark) cameraLabel.text = UIFont.IconFont.cameraMark.rawValue cameraLabel.textColor = .gray cameraLabel.textAlignment = .center cameraLabel.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) contentView.addSubview(cameraLabel) } }
a8095528555d5228d6b89c72bb3134a5
24.578947
80
0.669753
false
false
false
false
dklinzh/NodeExtension
refs/heads/master
NodeExtension/Classes/Node/DLBadgeNode.swift
mit
1
// // DLBadgeNode.swift // NodeExtension // // Created by Daniel Lin on 21/08/2017. // Copyright (c) 2017 Daniel Lin. All rights reserved. // import AsyncDisplayKit /// The Node object of badge view open class DLBadgeNode: ASControlNode { public var number: UInt = 0 { didSet { if number == 0 { self.isHidden = true } else { self.isHidden = false if number > 99 { _numberTextNode!.attributedText = NSAttributedString.dl_attributedString(string:"99+", fontSize: 12, color: _textColor) self.style.minWidth = ASDimensionMake(30) } else { _numberTextNode!.attributedText = NSAttributedString.dl_attributedString(string:"\(number)", fontSize: 12, color: _textColor) if number > 9 { self.style.minWidth = ASDimensionMake(24) } else { self.style.minWidth = ASDimensionMake(16) } } } } } private var _numberTextNode: ASTextNode? private var _badgeImageNode: ASImageNode? private let _textColor: UIColor public init(textColor: UIColor = .white, badgeColor: UIColor = .red) { _textColor = textColor super.init() self.automaticallyManagesSubnodes = true let numberTextNode = ASTextNode() numberTextNode.isLayerBacked = true _numberTextNode = numberTextNode let badgeImageNode = ASImageNode() badgeImageNode.image = UIImage.as_resizableRoundedImage(withCornerRadius: 8, cornerColor: .clear, fill: badgeColor, traitCollection: ASPrimitiveTraitCollectionMakeDefault()) badgeImageNode.isLayerBacked = true _badgeImageNode = badgeImageNode } open override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let insetSpec = ASInsetLayoutSpec(insets: UIEdgeInsets(top: CGFloat.infinity, left: CGFloat.infinity, bottom: CGFloat.infinity, right: CGFloat.infinity), child: _numberTextNode!) return ASOverlayLayoutSpec(child: _badgeImageNode!, overlay: insetSpec) } }
689e089a4476b6620f13654a97e086bd
36.65
186
0.610004
false
false
false
false
exponent/exponent
refs/heads/master
packages/expo-modules-core/ios/Swift/Views/ViewModuleWrapper.swift
bsd-3-clause
2
import UIKit import ObjectiveC /** A protocol that helps in identifying whether the instance of `ViewModuleWrapper` is of a dynamically created class. */ @objc protocol DynamicModuleWrapperProtocol { @objc optional func wrappedModule() -> ViewModuleWrapper } /** Each module that has a view manager definition needs to be wrapped by `RCTViewManager`. Unfortunately, we can't use just one class because React Native checks for duplicated classes. We're generating its subclasses in runtime as a workaround. */ @objc public final class ViewModuleWrapper: RCTViewManager, DynamicModuleWrapperProtocol { /** A reference to the module holder that stores the module definition. Enforced unwrapping is required since it can be set right after the object is initialized. */ var wrappedModuleHolder: ModuleHolder! /** The designated initializer. At first, we use this base class to hide `ModuleHolder` from Objective-C runtime. */ public init(_ wrappedModuleHolder: ModuleHolder) { self.wrappedModuleHolder = wrappedModuleHolder } /** The designated initializer that is used by React Native to create module instances. Must be called on a dynamic class to get access to underlying wrapped module. Throws fatal exception otherwise. */ @objc public override init() { super.init() guard let module = (self as DynamicModuleWrapperProtocol).wrappedModule?() else { fatalError("Something unexpected has happened. Only dynamically created `ViewModuleWrapper` can be initialized without params.") } self.wrappedModuleHolder = module.wrappedModuleHolder } /** Dummy initializer, for use only in `EXModuleRegistryAdapter.extraModulesForModuleRegistry:`. */ @objc public init(dummy: Any?) { super.init() } /** Returns the original name of the wrapped module. */ @objc public func name() -> String { return wrappedModuleHolder.name } /** Static function that returns the class name, but keep in mind that dynamic wrappers have custom class name (see `objc_allocateClassPair` invocation in `createViewModuleWrapperClass`). */ @objc public override class func moduleName() -> String { return NSStringFromClass(Self.self) } /** The view manager wrapper doesn't require main queue setup — it doesn't call any UI-related stuff on `init`. Also, lazy-loaded modules must return false here. */ @objc public override class func requiresMainQueueSetup() -> Bool { return false } /** Creates a view from the wrapped module. */ @objc public override func view() -> UIView! { guard let view = wrappedModuleHolder.definition.viewManager?.createView() else { fatalError("Module `\(wrappedModuleHolder.name)` doesn't define the view manager nor view factory.") } return view } /** The config for `proxiedProperties` prop. In Objective-C style, this function is generated by `RCT_CUSTOM_VIEW_PROPERTY` macro. */ @objc public class func propConfig_proxiedProperties() -> [String] { return ["NSDictionary", "__custom__"] } /** The setter for `proxiedProperties` prop. In Objective-C style, this function is generated by `RCT_CUSTOM_VIEW_PROPERTY` macro. */ @objc public func set_proxiedProperties(_ json: Any, forView view: UIView, withDefaultView defaultView: UIView) { guard let json = json as? [String: Any], let props = wrappedModuleHolder.definition.viewManager?.propsDict() else { return } for (key, value) in json { if let prop = props[key] { let value = Conversions.fromNSObject(value) // TODO: @tsapeta: Figure out better way to rethrow errors from here. // Adding `throws` keyword to the function results in different // method signature in Objective-C. Maybe just call `RCTLogError`? try? prop.set(value: value, onView: view) } } } /** Creates a subclass of `ViewModuleWrapper` in runtime. The new class overrides `moduleName` stub. */ @objc public static func createViewModuleWrapperClass(module: ViewModuleWrapper) -> ViewModuleWrapper.Type? { // We're namespacing the view name so we know it uses our architecture. let prefixedViewName = "ViewManagerAdapter_\(module.name())" return prefixedViewName.withCString { viewNamePtr in // Create a new class that inherits from `ViewModuleWrapper`. The class name passed here, doesn't work for Swift classes, // so we also have to override `moduleName` class method. let wrapperClass: AnyClass? = objc_allocateClassPair(ViewModuleWrapper.self, viewNamePtr, 0) // Dynamically add instance method returning wrapped module to the dynamic wrapper class. // React Native initializes modules with `init` without params, // so there is no other way to pass it to the instances. let wrappedModuleBlock: @convention(block) () -> ViewModuleWrapper = { module } let wrappedModuleImp: IMP = imp_implementationWithBlock(wrappedModuleBlock) class_addMethod(wrapperClass, Selector("wrappedModule"), wrappedModuleImp, "@@:") return wrapperClass as? ViewModuleWrapper.Type } } } // The direct event implementation can be cached and lazy-loaded (global and static variables are lazy by default in Swift). let directEventBlockImplementation = imp_implementationWithBlock({ ["RCTDirectEventBlock"] } as @convention(block) () -> [String])
3c313442813c6d1510b68c164344015e
36.294521
134
0.718825
false
false
false
false
urdnot-ios/ShepardAppearanceConverter
refs/heads/master
ShepardAppearanceConverter/ShepardAppearanceConverter/Views/Common/Popover/PopoverBackgroundView.swift
mit
1
// // PopoverBackgroundView.swift // ShepardAppearanceConverter // // Created by Emily Ivie on 8/18/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import UIKit class PopoverBackgroundView : UIPopoverBackgroundView { static var CustomBackgroundColor: UIColor? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() drawOverlay() drawPopoverBackground() drawPopoverShadow() } var overlay: CAShapeLayer? func drawOverlay() { clipsToBounds = false if overlay == nil { overlay = CAShapeLayer() overlay?.frame = CGRectMake( -10000, -10000, 20000, 20000) overlay?.backgroundColor = PopoverValues.OverlayColor.CGColor layer.insertSublayer(overlay!, atIndex: 0) } } var backgroundLayers: [CAShapeLayer] = [] func drawPopoverBackground() { let colors: [UIColor] = [PopoverValues.BorderColor, PopoverBackgroundView.CustomBackgroundColor ?? PopoverValues.DefaultBackgroundColor] let offset: [CGFloat] = [0.0, PopoverValues.BorderWidth] assert(colors.count == offset.count) for index in 0..<colors.count { if index >= backgroundLayers.count { let backgroundLayer = CAShapeLayer() layer.addSublayer(backgroundLayer) backgroundLayers.append(backgroundLayer) backgroundLayer.backgroundColor = colors[index].CGColor } backgroundLayers[index].frame = CGRectMake(offset[index], offset[index], bounds.width - (2 * offset[index]), bounds.height - (2 * offset[index])) } } override class func contentViewInsets() -> UIEdgeInsets { return UIEdgeInsetsMake(PopoverValues.BorderWidth, PopoverValues.BorderWidth, PopoverValues.BorderWidth, PopoverValues.BorderWidth) } var shadow: CAShapeLayer? func removeDefaultShadow() { layer.shadowOpacity = 0 layer.shadowColor = UIColor.clearColor().CGColor // (mostly) removes iOS ugly shadow that refuses to be customized } func drawPopoverShadow() { // a nice, narrow, subtle shadow if shadow == nil { removeDefaultShadow() shadow = CAShapeLayer() layer.insertSublayer(shadow!, atIndex: 1) shadow?.shadowOffset = CGSizeZero shadow?.shadowRadius = 10.0 shadow?.shadowColor = UIColor.blackColor().CGColor shadow?.shadowOpacity = 0.2 } let shadowWidth = CGFloat(5.0) let shadowFrame = CGRectMake(-1 * shadowWidth, -1 * shadowWidth, bounds.width + (shadowWidth * 2), bounds.height + (shadowWidth * 2)) shadow?.shadowPath = UIBezierPath(rect: shadowFrame).CGPath } // other required stuff: override var arrowOffset: CGFloat { get { return 0.0 } set {} } override var arrowDirection : UIPopoverArrowDirection { get { return UIPopoverArrowDirection.Unknown } set {} } override class func arrowBase() -> CGFloat { return 0.0 } override class func arrowHeight() -> CGFloat { return 0.0 } override class func wantsDefaultContentAppearance() -> Bool { return false } }
02b1da1b6daad4df46ad67b086a3f9b0
31.305556
157
0.625
false
false
false
false
narner/AudioKit
refs/heads/master
AudioKit/iOS/AudioKit/User Interface/AKADSRView.swift
mit
1
// // AKADSRView.swift // AudioKit for iOS // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // import UIKit /// A click and draggable view of an ADSR Envelope (Atttack, Decay, Sustain, Release) @IBDesignable open class AKADSRView: UIView { /// Type of function to call when values of the ADSR have changed public typealias ADSRCallback = (Double, Double, Double, Double) -> Void /// Attack time in seconds, Default: 0.1 @IBInspectable open var attackDuration: Double = 0.100 /// Decay time in seconds, Default: 0.1 @IBInspectable open var decayDuration: Double = 0.100 /// Sustain Level (0-1), Default: 0.5 @IBInspectable open var sustainLevel: Double = 0.50 /// Release time in seconds, Default: 0.1 @IBInspectable open var releaseDuration: Double = 0.100 /// Attack time in milliseconds var attackTime: CGFloat { get { return CGFloat(attackDuration * 1_000.0) } set { attackDuration = Double(newValue / 1_000.0) } } /// Decay time in milliseconds var decayTime: CGFloat { get { return CGFloat(decayDuration * 1_000.0) } set { decayDuration = Double(newValue / 1_000.0) } } /// Sustain level as a percentage 0% - 100% var sustainPercent: CGFloat { get { return CGFloat(sustainLevel * 100.0) } set { sustainLevel = Double(newValue / 100.0) } } /// Release time in milliseconds var releaseTime: CGFloat { get { return CGFloat(releaseDuration * 1_000.0) } set { releaseDuration = Double(newValue / 1_000.0) } } private var decaySustainTouchAreaPath = UIBezierPath() private var attackTouchAreaPath = UIBezierPath() private var releaseTouchAreaPath = UIBezierPath() /// Function to call when the values of the ADSR changes open var callback: ADSRCallback? private var currentDragArea = "" //// Color Declarations /// Color in the attack portion of the UI element @IBInspectable open var attackColor: UIColor = #colorLiteral(red: 0.767, green: 0.000, blue: 0.000, alpha: 1.000) /// Color in the decay portion of the UI element @IBInspectable open var decayColor: UIColor = #colorLiteral(red: 0.942, green: 0.648, blue: 0.000, alpha: 1.000) /// Color in the sustain portion of the UI element @IBInspectable open var sustainColor: UIColor = #colorLiteral(red: 0.320, green: 0.800, blue: 0.616, alpha: 1.000) /// Color in the release portion of the UI element @IBInspectable open var releaseColor: UIColor = #colorLiteral(red: 0.720, green: 0.519, blue: 0.888, alpha: 1.000) /// Background color @IBInspectable open var bgColor = AKStylist.sharedInstance.bgColor /// Width of the envelope curve @IBInspectable open var curveStrokeWidth: CGFloat = 1 /// Color of the envelope curve @IBInspectable open var curveColor: UIColor = .black var lastPoint = CGPoint.zero // MARK: - Initialization /// Initialize the view, usually with a callback @objc public init(callback: ADSRCallback? = nil) { self.callback = callback super.init(frame: CGRect(x: 0, y: 0, width: 440, height: 150)) backgroundColor = .clear } /// Initialization of the view from within interface builder required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Storyboard Rendering /// Perform necessary operation to allow the view to be rendered in interface builder override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() contentMode = .scaleAspectFill clipsToBounds = true } /// Size of the view override open var intrinsicContentSize: CGSize { return CGSize(width: 440, height: 150) } /// Requeire a constraint based layout with interface builder open class override var requiresConstraintBasedLayout: Bool { return true } // MARK: - Touch Handling /// Handle new touches override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let touchLocation = touch.location(in: self) if decaySustainTouchAreaPath.contains(touchLocation) { currentDragArea = "ds" } if attackTouchAreaPath.contains(touchLocation) { currentDragArea = "a" } if releaseTouchAreaPath.contains(touchLocation) { currentDragArea = "r" } lastPoint = touchLocation } setNeedsDisplay() } /// Handle moving touches override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let touchLocation = touch.location(in: self) if currentDragArea != "" { if currentDragArea == "ds" { sustainPercent -= (touchLocation.y - lastPoint.y) / 10.0 decayTime += touchLocation.x - lastPoint.x } if currentDragArea == "a" { attackTime += touchLocation.x - lastPoint.x attackTime -= touchLocation.y - lastPoint.y } if currentDragArea == "r" { releaseTime += touchLocation.x - lastPoint.x releaseTime -= touchLocation.y - lastPoint.y } } attackTime = max(attackTime, 0) decayTime = max(decayTime, 0) releaseTime = max(releaseTime, 0) sustainPercent = min(max(sustainPercent, 0), 100) if let realCallback = self.callback { realCallback(Double(attackTime / 1_000.0), Double(decayTime / 1_000.0), Double(sustainPercent / 100.0), Double(releaseTime / 1_000.0)) } lastPoint = touchLocation } setNeedsDisplay() } // MARK: - Drawing /// Draw the ADSR envelope func drawCurveCanvas(size: CGSize = CGSize(width: 440, height: 151), attackDurationMS: CGFloat = 449, decayDurationMS: CGFloat = 262, releaseDurationMS: CGFloat = 448, sustainLevel: CGFloat = 0.583, maxADFraction: CGFloat = 0.75) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Variable Declarations let attackClickRoom = CGFloat(30) // to allow the attack to be clicked even if is zero let oneSecond: CGFloat = 0.65 * size.width let initialPoint = CGPoint(x: attackClickRoom, y: size.height) let buffer = CGFloat(10)//curveStrokeWidth / 2.0 // make a little room for drwing the stroke let endAxes = CGPoint(x: size.width, y: size.height) let releasePoint = CGPoint(x: attackClickRoom + oneSecond, y: sustainLevel * (size.height - buffer) + buffer) let endPoint = CGPoint(x: releasePoint.x + releaseDurationMS / 1_000.0 * oneSecond, y: size.height) let endMax = CGPoint(x: min(endPoint.x, size.width), y: buffer) let releaseAxis = CGPoint(x: releasePoint.x, y: endPoint.y) let releaseMax = CGPoint(x: releasePoint.x, y: buffer) let highPoint = CGPoint(x: attackClickRoom + min(oneSecond * maxADFraction, attackDurationMS / 1_000.0 * oneSecond), y: buffer) let highPointAxis = CGPoint(x: highPoint.x, y: size.height) let highMax = CGPoint(x: highPoint.x, y: buffer) let minthing = min(oneSecond * maxADFraction, (attackDurationMS + decayDurationMS) / 1_000.0 * oneSecond) let sustainPoint = CGPoint(x: max(highPoint.x, attackClickRoom + minthing), y: sustainLevel * (size.height - buffer) + buffer) let sustainAxis = CGPoint(x: sustainPoint.x, y: size.height) let initialMax = CGPoint(x: 0, y: buffer) let initialToHighControlPoint = CGPoint(x: initialPoint.x, y: highPoint.y) let highToSustainControlPoint = CGPoint(x: highPoint.x, y: sustainPoint.y) let releaseToEndControlPoint = CGPoint(x: releasePoint.x, y: endPoint.y) //// attackTouchArea Drawing context?.saveGState() attackTouchAreaPath = UIBezierPath() attackTouchAreaPath.move(to: CGPoint(x: 0, y: size.height)) attackTouchAreaPath.addLine(to: highPointAxis) attackTouchAreaPath.addLine(to: highMax) attackTouchAreaPath.addLine(to: initialMax) attackTouchAreaPath.addLine(to: CGPoint(x: 0, y: size.height)) attackTouchAreaPath.close() bgColor.setFill() attackTouchAreaPath.fill() context?.restoreGState() //// decaySustainTouchArea Drawing context?.saveGState() decaySustainTouchAreaPath = UIBezierPath() decaySustainTouchAreaPath.move(to: highPointAxis) decaySustainTouchAreaPath.addLine(to: releaseAxis) decaySustainTouchAreaPath.addLine(to: releaseMax) decaySustainTouchAreaPath.addLine(to: highMax) decaySustainTouchAreaPath.addLine(to: highPointAxis) decaySustainTouchAreaPath.close() bgColor.setFill() decaySustainTouchAreaPath.fill() context?.restoreGState() //// releaseTouchArea Drawing context?.saveGState() releaseTouchAreaPath = UIBezierPath() releaseTouchAreaPath.move(to: releaseAxis) releaseTouchAreaPath.addLine(to: endAxes) releaseTouchAreaPath.addLine(to: endMax) releaseTouchAreaPath.addLine(to: releaseMax) releaseTouchAreaPath.addLine(to: releaseAxis) releaseTouchAreaPath.close() bgColor.setFill() releaseTouchAreaPath.fill() context?.restoreGState() //// releaseArea Drawing context?.saveGState() let releaseAreaPath = UIBezierPath() releaseAreaPath.move(to: releaseAxis) releaseAreaPath.addCurve(to: endPoint, controlPoint1: releaseAxis, controlPoint2: endPoint) releaseAreaPath.addCurve(to: releasePoint, controlPoint1: releaseToEndControlPoint, controlPoint2: releasePoint) releaseAreaPath.addLine(to: releaseAxis) releaseAreaPath.close() releaseColor.setFill() releaseAreaPath.fill() context?.restoreGState() //// sustainArea Drawing context?.saveGState() let sustainAreaPath = UIBezierPath() sustainAreaPath.move(to: sustainAxis) sustainAreaPath.addLine(to: releaseAxis) sustainAreaPath.addLine(to: releasePoint) sustainAreaPath.addLine(to: sustainPoint) sustainAreaPath.addLine(to: sustainAxis) sustainAreaPath.close() sustainColor.setFill() sustainAreaPath.fill() context?.restoreGState() //// decayArea Drawing context?.saveGState() let decayAreaPath = UIBezierPath() decayAreaPath.move(to: highPointAxis) decayAreaPath.addLine(to: sustainAxis) decayAreaPath.addCurve(to: sustainPoint, controlPoint1: sustainAxis, controlPoint2: sustainPoint) decayAreaPath.addCurve(to: highPoint, controlPoint1: highToSustainControlPoint, controlPoint2: highPoint) decayAreaPath.addLine(to: highPoint) decayAreaPath.close() decayColor.setFill() decayAreaPath.fill() context?.restoreGState() //// attackArea Drawing context?.saveGState() let attackAreaPath = UIBezierPath() attackAreaPath.move(to: initialPoint) attackAreaPath.addLine(to: highPointAxis) attackAreaPath.addLine(to: highPoint) attackAreaPath.addCurve(to: initialPoint, controlPoint1: initialToHighControlPoint, controlPoint2: initialPoint) attackAreaPath.close() attackColor.setFill() attackAreaPath.fill() context?.restoreGState() //// Curve Drawing context?.saveGState() let curvePath = UIBezierPath() curvePath.move(to: initialPoint) curvePath.addCurve(to: highPoint, controlPoint1: initialPoint, controlPoint2: initialToHighControlPoint) curvePath.addCurve(to: sustainPoint, controlPoint1: highPoint, controlPoint2: highToSustainControlPoint) curvePath.addLine(to: releasePoint) curvePath.addCurve(to: endPoint, controlPoint1: releasePoint, controlPoint2: releaseToEndControlPoint) curveColor.setStroke() curvePath.lineWidth = curveStrokeWidth curvePath.stroke() context?.restoreGState() } /// Draw the view override open func draw(_ rect: CGRect) { drawCurveCanvas(size: rect.size, attackDurationMS: attackTime, decayDurationMS: decayTime, releaseDurationMS: releaseTime, sustainLevel: 1.0 - sustainPercent / 100.0) } }
fe3cc63b12cd1d1050a6f025e8068266
36.365591
118
0.604604
false
false
false
false
danielrhodes/Swift-ActionCableClient
refs/heads/master
Example/ActionCableClient/ChatView.swift
mit
1
// // Copyright (c) 2016 Daniel Rhodes <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation import UIKit import SnapKit class ChatView : UIView { var tableView: UITableView var textField: UITextField var bottomLayoutConstraint: Constraint? = nil required override init(frame: CGRect) { self.tableView = UITableView() self.textField = UITextField() super.init(frame: frame) self.tableView.frame = CGRect.zero self.tableView.contentInset = UIEdgeInsetsMake(0, -5, 0, 0); self.addSubview(self.tableView) self.textField.frame = CGRect.zero self.textField.borderStyle = UITextBorderStyle.bezel self.textField.returnKeyType = UIReturnKeyType.send self.textField.placeholder = "Say something..." self.addSubview(self.textField) self.backgroundColor = UIColor.white NotificationCenter.default.addObserver(self, selector: #selector(ChatView.keyboardWillShowNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ChatView.keyboardWillHideNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { super.updateConstraints() tableView.snp.remakeConstraints { (make) -> Void in make.top.left.right.equalTo(self) make.bottom.equalTo(textField.snp.top) } textField.snp.remakeConstraints { (make) -> Void in make.left.right.equalTo(self) make.top.equalTo(tableView.snp.bottom) make.height.equalTo(50.0) self.bottomLayoutConstraint = make.bottom.equalTo(self).constraint } } func requiresConstraintBasedLayout() -> Bool { return true } } //MARK: Notifications extension ChatView { @objc func keyboardWillHideNotification(_ notification: Notification) { let userInfo = (notification as NSNotification).userInfo! let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let rawAnimationCurve = ((notification as NSNotification).userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).uint32Value << 16 let animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve)) UIView.animate(withDuration: animationDuration, delay: 0.0, options: [.beginFromCurrentState, animationCurve], animations: { self.bottomLayoutConstraint?.update(offset: 0) self.updateConstraintsIfNeeded() }, completion: nil) } @objc func keyboardWillShowNotification(_ notification: Notification) { let userInfo = (notification as NSNotification).userInfo! let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let convertedKeyboardEndFrame = self.convert(keyboardEndFrame, from: self.window) let rawAnimationCurve = ((notification as NSNotification).userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).uint32Value << 16 let animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve)) UIView.animate(withDuration: animationDuration, delay: 0.0, options: [.beginFromCurrentState, animationCurve], animations: { self.bottomLayoutConstraint?.update(offset: -convertedKeyboardEndFrame.height) self.updateConstraintsIfNeeded() }, completion: nil) } }
ab2869af80e0e129a0d70c2fc13d050e
45.080357
175
0.709746
false
false
false
false
lbkchen/heis
refs/heads/master
iOS/heis/heis/heis/ViewControllerTraitorPlay.swift
mit
1
// // ViewControllerTraitorPlay.swift // heis // // Created by l00p on 9/4/16. // Copyright © 2016 heis. All rights reserved. // import UIKit import GoogleMaps import MultipeerConnectivity class ViewControllerTraitorPlay: UIViewController, CLLocationManagerDelegate, MCSessionDelegate, MCBrowserViewControllerDelegate { let locationManager = CLLocationManager() @IBOutlet weak var mapView: GMSMapView! var gameZoomLevel: Double! var gameLatitude: Double! var gameLongitude: Double! var gameRole: Bool! let startSessionButton = UIButton(frame: CGRect(x: 150, y: 200, width: 200, height: 40)) let sendDataButton = UIButton(frame: CGRect(x: 150, y: 400, width: 200, height: 40)) var peerID: MCPeerID! var mcSession: MCSession! var mcAdvertiserAssistant: MCAdvertiserAssistant! var MCTestlabel = UILabel(frame: CGRect(x: 150, y: 600, width: 300, height: 40)) override func viewDidLoad() { super.viewDidLoad() // Get authorization to get user's location locationManager.delegate = self locationManager.requestWhenInUseAuthorization() // Sets map let coord = CLLocationCoordinate2D(latitude: gameLatitude, longitude: gameLongitude) mapView.camera = GMSCameraPosition(target: coord, zoom: Float(gameZoomLevel), bearing: 0, viewingAngle: 0) // Start of MC stuff startSessionButton.backgroundColor = UIColor.green startSessionButton.setTitle("Start Sesh", for: UIControlState()) startSessionButton.addTarget(self, action: #selector(showConnectionPrompt), for: .touchUpInside) self.view.addSubview(startSessionButton) sendDataButton.backgroundColor = UIColor.green sendDataButton.setTitle("Send Data", for: UIControlState()) sendDataButton.addTarget(self, action: #selector(sendData), for: .touchUpInside) self.view.addSubview(sendDataButton) MCTestlabel.textAlignment = NSTextAlignment.center MCTestlabel.adjustsFontSizeToFitWidth = true MCTestlabel.text = "tor" self.view.addSubview(MCTestlabel) title = "heis" peerID = MCPeerID(displayName: UIDevice.current.name) mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required) mcSession.delegate = self //sendImage(data1: 4) } func showConnectionPrompt() { let ac = UIAlertController(title: "Connect to others", message: nil, preferredStyle: .actionSheet) ac.addAction(UIAlertAction(title: "Host a session", style: .default, handler: startHosting)) ac.addAction(UIAlertAction(title: "Join a session", style: .default, handler: joinSession)) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel)) present(ac, animated: true) } func sendData() { if mcSession.connectedPeers.count > 0 { var numVal: NSInteger = 6 let data = NSData(bytes: &numVal, length: MemoryLayout<NSInteger>.size) do { try mcSession.send(data as Data, toPeers: mcSession.connectedPeers, with: .reliable) MCTestlabel.text?.append("1") } catch { let ac = UIAlertController(title: "Send error", message: error.localizedDescription, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(ac, animated: true) MCTestlabel.text?.append("2") } } } func startHosting(action: UIAlertAction!) { mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "experimentation", discoveryInfo: nil, session: mcSession) mcAdvertiserAssistant.start() } func joinSession(action: UIAlertAction!) { let mcBrowser = MCBrowserViewController(serviceType: "experimentation", session: mcSession) mcBrowser.delegate = self present(mcBrowser, animated: true) } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL, withError error: Error?) { } func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) { dismiss(animated: true) } func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) { dismiss(animated: true) } func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { switch state { case MCSessionState.connected: print("Connected: \(peerID.displayName)") case MCSessionState.connecting: print("Connecting: \(peerID.displayName)") case MCSessionState.notConnected: print("Not Connected: \(peerID.displayName)") } } // CANT SEND WHEN NO CONNECTED PEERS!! func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { var val: NSInteger = 0 //var data1 = NSData(bytes: &src, length: MemoryLayout<NSInteger>.size) var data1 = data as NSData data1.getBytes(&val, length: MemoryLayout<NSInteger>.size) // sent val should be 6, received val should be 5 MCTestlabel.text?.append("from5CER\(val)") } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if (status == .authorizedWhenInUse) { locationManager.startUpdatingLocation() mapView.isMyLocationEnabled = true } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { //mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
77dbbe2ee00f9cf05318d857df12fe87
37.89881
167
0.658761
false
false
false
false
dunkelstern/FastString
refs/heads/master
src/replace.swift
apache-2.0
1
// Copyright (c) 2016 Johannes Schriewer. // // 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. /// String replacement functions public extension FastString { /// Return new string with `range` replaced by `replacement` /// /// - parameter range: range to replace /// - parameter replacement: replacement /// - returns: new string with substituted range public func replacing(range: Range<Int>, replacement: FastString) -> FastString { let before = self.subString(range: 0..<range.lowerBound) let after = self.subString(range: range.upperBound..<self.byteCount) return FastString.join(parts: [before, after], delimiter: replacement) } public func replacing(range: Range<Int>, replacement: String) -> FastString { return self.replacing(range: range, replacement: FastString(replacement)) } /// Search for a substring and replace with other string /// /// - parameter searchTerm: substring to search /// - parameter replacement: replacement to substitute /// - returns: new string with applied substitutions public func replacing(searchTerm: FastString, replacement: FastString) -> FastString { if searchTerm.byteCount == 0 { return self } let comps = self.split(string: searchTerm) let replaced = FastString.join(parts: comps, delimiter: replacement) return replaced } public func replacing(searchTerm: String, replacement: String) -> FastString { return self.replacing(searchTerm: FastString(searchTerm), replacement: FastString(replacement)) } /// Replace `range` in string with substitute, modifies self /// /// - parameter range: range to replace /// - parameter replacement: substitute public func replace(range: Range<Int>, replacement: FastString) { let capacity = self.byteCount - (range.upperBound - range.lowerBound) + replacement.byteCount let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: capacity + 1) memory[capacity] = 0 var memIndex = 0 for i in 0..<range.lowerBound { memory[memIndex] = self.buffer[i] memIndex += 1 } for i in 0..<replacement.byteCount { memory[memIndex] = replacement.buffer[i] memIndex += 1 } for i in range.upperBound..<self.byteCount { memory[memIndex] = self.buffer[i] memIndex += 1 } self.buffer.baseAddress!.deallocateCapacity(self.buffer.count + 1) self.buffer = UnsafeMutableBufferPointer(start: memory, count: capacity) } public func replace(range: Range<Int>, replacement: String) { self.replace(range: range, replacement: FastString(replacement)) } /// Replace substring in string, modifies self /// /// - parameter searchTerm: string to replace /// - parameter replacement: substitute public func replace(searchTerm: FastString, replacement: FastString) { if searchTerm.byteCount == 0 { return } let parts = self.split(string: searchTerm) let capacity = self.byteCount - (searchTerm.byteCount * (parts.count - 1)) + (replacement.byteCount * (parts.count - 1)) let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: capacity + 1) memory[capacity] = 0 var index = 0 for part in parts { for c in part.buffer { memory[index] = c index += 1 } if part !== parts.last! { for c in replacement.buffer { memory[index] = c index += 1 } } } self.buffer.baseAddress!.deallocateCapacity(self.buffer.count + 1) self.buffer = UnsafeMutableBufferPointer(start: memory, count: capacity) } public func replace(searchTerm: String, replacement: String) { self.replace(searchTerm: FastString(searchTerm), replacement: FastString(replacement)) } }
017654277d17e3480a532449353527c5
38.37069
128
0.643671
false
false
false
false
muneebm/AsterockX
refs/heads/master
Pod/Classes/NeoWs-Constants.swift
mit
2
// // NeoWs-Constants.swift // AsterockX // // Created by Muneeb Rahim Abdul Majeed on 1/10/16. // Copyright © 2016 beenum. All rights reserved. // import UIKit extension NeoWs { struct Constants { static let BaseUrl = "https://api.nasa.gov/neo/rest/v1/" static let Browse = "browse" static let Feed = "feed" static let Neo = "neo/" static let ErrorDomain = "NEOWS_ERROR" static let CloseApproachDateFormat = "yyyy-MM-dd" static let OrbitDeterminationDateFormat = "yyyy-MM-DD hh:mm:ss" } struct Parameters { static let ApiKey = "api_key" static let StartDate = "start_date" static let EndDate = "end_date" static let Page = "page" static let Size = "size" } struct JSONResponseKeys { static let Links = "links" static let Previous = "prev" static let Current = "self" static let Next = "next" static let Page = "page" static let Size = "size" static let TotalElements = "total_elements" static let TotalPages = "total_pages" static let Number = "number" static let NearEarthObjects = "near_earth_objects" static let NeoReferenceId = "neo_reference_id" static let Name = "name" static let NasaJplUrl = "nasa_jpl_url" static let AbsoluteMagnitudeH = "absolute_magnitude_h" static let EstimatedDiameter = "estimated_diameter" static let EstimatedDiameterMin = "estimated_diameter_min" static let EstimatedDiameterMax = "estimated_diameter_max" static let Kilometers = "kilometers" static let Meters = "meters" static let Miles = "miles" static let Feet = "feet" static let IsPotentiallyHazardous = "is_potentially_hazardous_asteroid" static let CloseApproachData = "close_approach_data" static let CloseApproachDate = "close_approach_date" static let EpochDate = "epoch_date_close_approach" static let RelativeVelocity = "relative_velocity" static let KilometersPerSecond = "kilometers_per_second" static let KilometersPerHours = "kilometers_per_hour" static let MilesPerHour = "miles_per_hour" static let MissDistance = "miss_distance" static let Astronomical = "astronomical" static let Lunar = "lunar" static let OrbitingBody = "orbiting_body" static let OrbitalData = "orbital_data" static let OrbitId = "orbit_id" static let OrbitDetetminationDate = "orbit_determination_date" static let OrbitUncertainty = "orbit_uncertainty" static let MinimumOrbitIntersection = "minimum_orbit_intersection" static let JupiterTisserandInvariant = "jupiter_tisserand_invariant" static let EpochOsculation = "epoch_osculation" static let Eccentricity = "eccentricity" static let SemiMajorAxis = "semi_major_axis" static let Inclination = "inclination" static let AscendingNodeLongitude = "ascending_node_longitude" static let OrbitalPeriod = "orbital_period" static let PerihelionDistance = "perihelion_distance" static let PerihelionArgument = "perihelion_argument" static let AphelionDistance = "aphelion_distance" static let PerihelionTime = "perihelion_time" static let MeanAnomaly = "mean_anomaly" static let MeanMotion = "mean_motion" static let Equinox = "equinox" static let ErrorMessage = "error_message" static let Error = "error" static let Message = "message" } }
6ddead15724a725d95940e9e9258d0cb
39.32967
79
0.647684
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/Locale.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import CoreFoundation internal func __NSLocaleIsAutoupdating(_ locale: NSLocale) -> Bool { return false // Auto-updating is only on Darwin } internal func __NSLocaleCurrent() -> NSLocale { return CFLocaleCopyCurrent()._nsObject } /** `Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted. Locales are typically used to provide, format, and interpret information about and according to the user’s customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user. */ public struct Locale : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible { public typealias ReferenceType = NSLocale public typealias LanguageDirection = NSLocale.LanguageDirection internal var _wrapped : NSLocale internal var _autoupdating : Bool /// Returns the user's current locale. public static var current : Locale { return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: false) } /// Returns a locale which tracks the user's current preferences. /// /// If mutated, this Locale will no longer track the user's preferences. /// /// - note: The autoupdating Locale will only compare equal to another autoupdating Locale. public static var autoupdatingCurrent : Locale { // swift-corelibs-foundation does not yet support autoupdating, but we can return the current locale (which will not change). return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: true) } @available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case") public static var system : Locale { fatalError() } // MARK: - // /// Return a locale with the specified identifier. public init(identifier: String) { _wrapped = NSLocale(localeIdentifier: identifier) _autoupdating = false } internal init(reference: NSLocale) { _wrapped = reference.copy() as! NSLocale if __NSLocaleIsAutoupdating(reference) { _autoupdating = true } else { _autoupdating = false } } private init(adoptingReference reference: NSLocale, autoupdating: Bool) { _wrapped = reference _autoupdating = autoupdating } // MARK: - // /// Returns a localized string for a specified identifier. /// /// For example, in the "en" locale, the result for `"es"` is `"Spanish"`. public func localizedString(forIdentifier identifier: String) -> String? { return _wrapped.displayName(forKey: .identifier, value: identifier) } /// Returns a localized string for a specified language code. /// /// For example, in the "en" locale, the result for `"es"` is `"Spanish"`. public func localizedString(forLanguageCode languageCode: String) -> String? { return _wrapped.displayName(forKey: .languageCode, value: languageCode) } /// Returns a localized string for a specified region code. /// /// For example, in the "en" locale, the result for `"fr"` is `"France"`. public func localizedString(forRegionCode regionCode: String) -> String? { return _wrapped.displayName(forKey: .countryCode, value: regionCode) } /// Returns a localized string for a specified script code. /// /// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`. public func localizedString(forScriptCode scriptCode: String) -> String? { return _wrapped.displayName(forKey: .scriptCode, value: scriptCode) } /// Returns a localized string for a specified variant code. /// /// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`. public func localizedString(forVariantCode variantCode: String) -> String? { return _wrapped.displayName(forKey: .variantCode, value: variantCode) } /// Returns a localized string for a specified `Calendar.Identifier`. /// /// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`. public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? { // NSLocale doesn't export a constant for this let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), kCFLocaleCalendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue._cfObject)._swiftObject return result } /// Returns a localized string for a specified ISO 4217 currency code. /// /// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`. /// - seealso: `Locale.isoCurrencyCodes` public func localizedString(forCurrencyCode currencyCode: String) -> String? { return _wrapped.displayName(forKey: .currencyCode, value: currencyCode) } /// Returns a localized string for a specified ICU collation identifier. /// /// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`. public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? { return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier) } /// Returns a localized string for a specified ICU collator identifier. public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? { return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier) } // MARK: - // /// Returns the identifier of the locale. public var identifier: String { return _wrapped.localeIdentifier } /// Returns the language code of the locale, or nil if has none. /// /// For example, for the locale "zh-Hant-HK", returns "zh". public var languageCode: String? { return _wrapped.object(forKey: .languageCode) as? String } /// Returns the region code of the locale, or nil if it has none. /// /// For example, for the locale "zh-Hant-HK", returns "HK". public var regionCode: String? { // n.b. this is called countryCode in ObjC if let result = _wrapped.object(forKey: .countryCode) as? String { if result.isEmpty { return nil } else { return result } } else { return nil } } /// Returns the script code of the locale, or nil if has none. /// /// For example, for the locale "zh-Hant-HK", returns "Hant". public var scriptCode: String? { return _wrapped.object(forKey: .scriptCode) as? String } /// Returns the variant code for the locale, or nil if it has none. /// /// For example, for the locale "en_POSIX", returns "POSIX". public var variantCode: String? { if let result = _wrapped.object(forKey: .variantCode) as? String { if result.isEmpty { return nil } else { return result } } else { return nil } } /// Returns the exemplar character set for the locale, or nil if has none. public var exemplarCharacterSet: CharacterSet? { return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet } /// Returns the calendar for the locale, or the Gregorian calendar as a fallback. public var calendar: Calendar { // NSLocale should not return nil here if let result = _wrapped.object(forKey: .calendar) as? Calendar { return result } else { return Calendar(identifier: .gregorian) } } /// Returns the collation identifier for the locale, or nil if it has none. /// /// For example, for the locale "en_US@collation=phonebook", returns "phonebook". public var collationIdentifier: String? { return _wrapped.object(forKey: .collationIdentifier) as? String } /// Returns true if the locale uses the metric system. /// /// -seealso: MeasurementFormatter public var usesMetricSystem: Bool { // NSLocale should not return nil here, but just in case if let result = _wrapped.object(forKey: .usesMetricSystem) as? Bool { return result } else { return false } } /// Returns the decimal separator of the locale. /// /// For example, for "en_US", returns ".". public var decimalSeparator: String? { return _wrapped.object(forKey: .decimalSeparator) as? String } /// Returns the grouping separator of the locale. /// /// For example, for "en_US", returns ",". public var groupingSeparator: String? { return _wrapped.object(forKey: .groupingSeparator) as? String } /// Returns the currency symbol of the locale. /// /// For example, for "zh-Hant-HK", returns "HK$". public var currencySymbol: String? { return _wrapped.object(forKey: .currencySymbol) as? String } /// Returns the currency code of the locale. /// /// For example, for "zh-Hant-HK", returns "HKD". public var currencyCode: String? { return _wrapped.object(forKey: .currencyCode) as? String } /// Returns the collator identifier of the locale. public var collatorIdentifier: String? { return _wrapped.object(forKey: .collatorIdentifier) as? String } /// Returns the quotation begin delimiter of the locale. /// /// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK". public var quotationBeginDelimiter: String? { return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String } /// Returns the quotation end delimiter of the locale. /// /// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK". public var quotationEndDelimiter: String? { return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String } /// Returns the alternate quotation begin delimiter of the locale. /// /// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK". public var alternateQuotationBeginDelimiter: String? { return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String } /// Returns the alternate quotation end delimiter of the locale. /// /// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK". public var alternateQuotationEndDelimiter: String? { return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String } // MARK: - // /// Returns a list of available `Locale` identifiers. public static var availableIdentifiers: [String] { return NSLocale.availableLocaleIdentifiers } /// Returns a list of available `Locale` language codes. public static var isoLanguageCodes: [String] { return NSLocale.isoLanguageCodes } /// Returns a list of available `Locale` region codes. public static var isoRegionCodes: [String] { // This was renamed from Obj-C return NSLocale.isoCountryCodes } /// Returns a list of available `Locale` currency codes. public static var isoCurrencyCodes: [String] { return NSLocale.isoCurrencyCodes } /// Returns a list of common `Locale` currency codes. public static var commonISOCurrencyCodes: [String] { return NSLocale.commonISOCurrencyCodes } /// Returns a list of the user's preferred languages. /// /// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports. /// - seealso: `Bundle.preferredLocalizations(from:)` /// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)` public static var preferredLanguages: [String] { return NSLocale.preferredLanguages } /// Returns a dictionary that splits an identifier into its component pieces. public static func components(fromIdentifier string: String) -> [String : String] { return NSLocale.components(fromLocaleIdentifier: string) } /// Constructs an identifier from a dictionary of components. public static func identifier(fromComponents components: [String : String]) -> String { return NSLocale.localeIdentifier(fromComponents: components) } /// Returns a canonical identifier from the given string. public static func canonicalIdentifier(from string: String) -> String { return NSLocale.canonicalLocaleIdentifier(from: string) } /// Returns a canonical language identifier from the given string. public static func canonicalLanguageIdentifier(from string: String) -> String { return NSLocale.canonicalLanguageIdentifier(from: string) } /// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted. public static func identifier(fromWindowsLocaleCode code: Int) -> String? { return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code)) } /// Returns the Windows locale code from a given identifier, or nil if it could not be converted. public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? { let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier) if result == 0 { return nil } else { return Int(result) } } /// Returns the character direction for a specified language code. public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection { return NSLocale.characterDirection(forLanguage: isoLangCode) } /// Returns the line direction for a specified language code. public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection { return NSLocale.lineDirection(forLanguage: isoLangCode) } // MARK: - @available(*, unavailable, renamed: "init(identifier:)") public init(localeIdentifier: String) { fatalError() } @available(*, unavailable, renamed: "identifier") public var localeIdentifier: String { fatalError() } @available(*, unavailable, renamed: "localizedString(forIdentifier:)") public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() } @available(*, unavailable, renamed: "availableIdentifiers") public static var availableLocaleIdentifiers: [String] { fatalError() } @available(*, unavailable, renamed: "components(fromIdentifier:)") public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() } @available(*, unavailable, renamed: "identifier(fromComponents:)") public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() } @available(*, unavailable, renamed: "canonicalIdentifier(from:)") public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() } @available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)") public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() } @available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)") public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() } @available(*, unavailable, message: "use regionCode instead") public var countryCode: String { fatalError() } @available(*, unavailable, message: "use localizedString(forRegionCode:) instead") public func localizedString(forCountryCode countryCode: String) -> String { fatalError() } @available(*, unavailable, renamed: "isoRegionCodes") public static var isoCountryCodes: [String] { fatalError() } // MARK: - // public var description: String { return _wrapped.description } public var debugDescription : String { return _wrapped.debugDescription } public var hashValue : Int { if _autoupdating { return 1 } else { return _wrapped.hash } } public static func ==(lhs: Locale, rhs: Locale) -> Bool { if lhs._autoupdating || rhs._autoupdating { return lhs._autoupdating == rhs._autoupdating } else { return lhs._wrapped.isEqual(rhs._wrapped) } } } extension Locale : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSLocale { return _wrapped } public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(NSLocale.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool { result = Locale(reference: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale { var result: Locale? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension Locale : Codable { private enum CodingKeys : Int, CodingKey { case identifier } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let identifier = try container.decode(String.self, forKey: .identifier) self.init(identifier: identifier) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.identifier, forKey: .identifier) } }
d122c95a27f33f1dcea9c749e39c4729
38.331959
282
0.65585
false
false
false
false
PoissonBallon/EasyRealm
refs/heads/master
Example/Tests/TestSave.swift
mit
1
// // Test_Save.swift // EasyRealm // // Created by Allan Vialatte on 10/03/2017. // import XCTest import RealmSwift import EasyRealm class TestSave: XCTestCase { let testPokemon = ["Bulbasaur", "Ivysaur", "Venusaur","Charmander","Charmeleon","Charizard"] override func setUp() { super.setUp() Realm.Configuration.defaultConfiguration.inMemoryIdentifier = self.name } override func tearDown() { super.tearDown() let realm = try! Realm() try! realm.write { realm.deleteAll() } } func testSaveUnmanaged() { HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) } HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) } try! Pokeball.create().er.save() try! Pokeball.create().er.save() let numberOfPokemon = try! Pokemon.er.all() let numberOfPokeball = try! Pokeball.er.all() XCTAssertEqual(self.testPokemon.count, numberOfPokemon.count) XCTAssertEqual(2, numberOfPokeball.count) } func testSaveManaged() { HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) } let managedPokemon = testPokemon.compactMap { try! Pokemon.er.fromRealm(with: $0) } managedPokemon.forEach { try! $0.er.save(update: true) } } func testMeasureSaveUnmanaged() { self.measure { try! Pokeball.create().er.save() } } func testMeasureSaveManaged() { let pokemon = HelpPokemon.pokemons(with: [self.testPokemon[0]]).first! try! pokemon.er.save(update: true) self.measure { try! pokemon.er.save(update: true) } } func testSaveLotOfComplexObject() { for _ in 0...10000 { try! HelpPokemon.generateCapturedRandomPokemon().er.save(update: true) } } }
9afdb717f38991e5cf01b6fab72e839a
26.369231
94
0.676223
false
true
false
false
mcgarrett007/AES
refs/heads/v2.0
Pods/Kanna/Sources/Kanna/libxmlHTMLDocument.swift
mit
1
/**@file libxmlHTMLDocument.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 CoreFoundation #if SWIFT_PACKAGE import SwiftClibxml2 #else import libxmlKanna #endif extension String.Encoding { var IANACharSetName: String? { #if os(Linux) && swift(>=4) switch self { case .ascii: return "us-ascii" case .iso2022JP: return "iso-2022-jp" case .isoLatin1: return "iso-8859-1" case .isoLatin2: return "iso-8859-2" case .japaneseEUC: return "euc-jp" case .macOSRoman: return "macintosh" case .nextstep: return "x-nextstep" case .nonLossyASCII: return nil case .shiftJIS: return "cp932" case .symbol: return "x-mac-symbol" case .unicode: return "utf-16" case .utf16: return "utf-16" case .utf16BigEndian: return "utf-16be" case .utf32: return "utf-32" case .utf32BigEndian: return "utf-32be" case .utf32LittleEndian: return "utf-32le" case .utf8: return "utf-8" case .windowsCP1250: return "windows-1250" case .windowsCP1251: return "windows-1251" case .windowsCP1252: return "windows-1252" case .windowsCP1253: return "windows-1253" case .windowsCP1254: return "windows-1254" default: return nil } #elseif os(Linux) && swift(>=3) switch self { case String.Encoding.ascii: return "us-ascii" case String.Encoding.iso2022JP: return "iso-2022-jp" case String.Encoding.isoLatin1: return "iso-8859-1" case String.Encoding.isoLatin2: return "iso-8859-2" case String.Encoding.japaneseEUC: return "euc-jp" case String.Encoding.macOSRoman: return "macintosh" case String.Encoding.nextstep: return "x-nextstep" case String.Encoding.nonLossyASCII: return nil case String.Encoding.shiftJIS: return "cp932" case String.Encoding.symbol: return "x-mac-symbol" case String.Encoding.unicode: return "utf-16" case String.Encoding.utf16: return "utf-16" case String.Encoding.utf16BigEndian: return "utf-16be" case String.Encoding.utf32: return "utf-32" case String.Encoding.utf32BigEndian: return "utf-32be" case String.Encoding.utf32LittleEndian: return "utf-32le" case String.Encoding.utf8: return "utf-8" case String.Encoding.windowsCP1250: return "windows-1250" case String.Encoding.windowsCP1251: return "windows-1251" case String.Encoding.windowsCP1252: return "windows-1252" case String.Encoding.windowsCP1253: return "windows-1253" case String.Encoding.windowsCP1254: return "windows-1254" default: return nil } #else let cfenc = CFStringConvertNSStringEncodingToEncoding(self.rawValue) guard let cfencstr = CFStringConvertEncodingToIANACharSetName(cfenc) else { return nil } return String(describing: cfencstr) #endif } } /* libxmlHTMLDocument */ internal final class libxmlHTMLDocument: HTMLDocument { fileprivate var docPtr: htmlDocPtr? = nil fileprivate var rootNode: XMLElement? fileprivate var html: String fileprivate var url: String? fileprivate var encoding: String.Encoding var text: String? { return rootNode?.text } var toHTML: String? { let buf = xmlBufferCreate() let outputBuf = xmlOutputBufferCreateBuffer(buf, nil) defer { xmlOutputBufferClose(outputBuf) xmlBufferFree(buf) } htmlDocContentDumpOutput(outputBuf, docPtr, nil) let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf))) return html } var toXML: String? { var buf: UnsafeMutablePointer<xmlChar>? = nil let size: UnsafeMutablePointer<Int32>? = nil defer { xmlFree(buf) } xmlDocDumpMemory(docPtr, &buf, size) let html = String(cString: UnsafePointer(buf!)) return html } var innerHTML: String? { return rootNode?.innerHTML } var className: String? { return nil } var tagName: String? { get { return nil } set { } } var content: String? { get { return text } set { rootNode?.content = newValue } } init(html: String, url: String?, encoding: String.Encoding, option: UInt) throws { self.html = html self.url = url self.encoding = encoding guard html.lengthOfBytes(using: encoding) > 0 else { throw ParseError.Empty } guard let charsetName = encoding.IANACharSetName, let cur = html.cString(using: encoding) else { throw ParseError.EncodingMismatch } let url : String = "" docPtr = htmlReadDoc(UnsafeRawPointer(cur).assumingMemoryBound(to: xmlChar.self), url, charsetName, CInt(option)) guard let docPtr = docPtr else { throw ParseError.EncodingMismatch } rootNode = libxmlHTMLNode(document: self, docPtr: docPtr) } deinit { xmlFreeDoc(self.docPtr) } var title: String? { return at_xpath("//title")?.text } var head: XMLElement? { return at_xpath("//head") } var body: XMLElement? { return at_xpath("//body") } func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject { return rootNode?.xpath(xpath, namespaces: namespaces) ?? XPathObject.none } func xpath(_ xpath: String) -> XPathObject { return self.xpath(xpath, namespaces: nil) } func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? { return rootNode?.at_xpath(xpath, namespaces: namespaces) } func at_xpath(_ xpath: String) -> XMLElement? { return self.at_xpath(xpath, namespaces: nil) } func css(_ selector: String, namespaces: [String:String]?) -> XPathObject { return rootNode?.css(selector, namespaces: namespaces) ?? XPathObject.none } func css(_ selector: String) -> XPathObject { return self.css(selector, namespaces: nil) } func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? { return rootNode?.at_css(selector, namespaces: namespaces) } func at_css(_ selector: String) -> XMLElement? { return self.at_css(selector, namespaces: nil) } } /* libxmlXMLDocument */ internal final class libxmlXMLDocument: XMLDocument { fileprivate var docPtr: xmlDocPtr? = nil fileprivate var rootNode: XMLElement? fileprivate var xml: String fileprivate var url: String? fileprivate var encoding: String.Encoding var text: String? { return rootNode?.text } var toHTML: String? { let buf = xmlBufferCreate() let outputBuf = xmlOutputBufferCreateBuffer(buf, nil) defer { xmlOutputBufferClose(outputBuf) xmlBufferFree(buf) } htmlDocContentDumpOutput(outputBuf, docPtr, nil) let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf))) return html } var toXML: String? { var buf: UnsafeMutablePointer<xmlChar>? = nil let size: UnsafeMutablePointer<Int32>? = nil defer { xmlFree(buf) } xmlDocDumpMemory(docPtr, &buf, size) let html = String(cString: UnsafePointer(buf!)) return html } var innerHTML: String? { return rootNode?.innerHTML } var className: String? { return nil } var tagName: String? { get { return nil } set { } } var content: String? { get { return text } set { rootNode?.content = newValue } } init(xml: String, url: String?, encoding: String.Encoding, option: UInt) throws { self.xml = xml self.url = url self.encoding = encoding if xml.isEmpty { throw ParseError.Empty } guard let charsetName = encoding.IANACharSetName, let cur = xml.cString(using: encoding) else { throw ParseError.EncodingMismatch } let url : String = "" docPtr = xmlReadDoc(UnsafeRawPointer(cur).assumingMemoryBound(to: xmlChar.self), url, charsetName, CInt(option)) rootNode = libxmlHTMLNode(document: self, docPtr: docPtr!) } deinit { xmlFreeDoc(self.docPtr) } func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject { return rootNode?.xpath(xpath, namespaces: namespaces) ?? XPathObject.none } func xpath(_ xpath: String) -> XPathObject { return self.xpath(xpath, namespaces: nil) } func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? { return rootNode?.at_xpath(xpath, namespaces: namespaces) } func at_xpath(_ xpath: String) -> XMLElement? { return self.at_xpath(xpath, namespaces: nil) } func css(_ selector: String, namespaces: [String:String]?) -> XPathObject { return rootNode?.css(selector, namespaces: namespaces) ?? XPathObject.none } func css(_ selector: String) -> XPathObject { return self.css(selector, namespaces: nil) } func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? { return rootNode?.at_css(selector, namespaces: namespaces) } func at_css(_ selector: String) -> XMLElement? { return self.at_css(selector, namespaces: nil) } }
3825dc8675db890644840dabf281fc50
27.997481
121
0.595987
false
false
false
false
sajeel/AutoScout
refs/heads/master
AutoScout/View & Controllers/Cell/CarTableViewCell.swift
gpl-3.0
1
// // MovieCell.swift // TrivagoTracktSerachSwift // // Created by Sajjeel Khilji on 8/24/16. // Copyright © 2016 Saj. All rights reserved. // import UIKit import AlamofireImage import RealmSwift class CarTableViewCell: UITableViewCell { static let minimalHeight = CGFloat(124) //MARK: - Properties @IBOutlet var vehicleImageView: UIImageView! @IBOutlet var make: UILabel! @IBOutlet var price: UILabel! @IBOutlet var mileage: UILabel! @IBOutlet var fuelType: UILabel! @IBOutlet var favSwitch: UISwitch! @IBOutlet var stackView: UIStackView! @IBOutlet var delButton: UIButton! @IBOutlet var contentViewHolder: UIView! var carCellViewModel : CellViewModel? override func awakeFromNib() { favSwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged) } func switchChanged(mySwitch: UISwitch) { let value = mySwitch.isOn if value { self.carCellViewModel?.saveFav() }else{ self.carCellViewModel?.deleteFav() } } //MARK: - Cell configuration func configureWithCar( cellViewModel: CellViewModel) { self.carCellViewModel = nil self.carCellViewModel = cellViewModel self.favSwitch.isOn = cellViewModel.shouldFavSwitchOn //s price.text = cellViewModel.price make.text = cellViewModel.make mileage.text = cellViewModel.milage fuelType.text = cellViewModel.fuel self.contentViewHolder.backgroundColor = carCellViewModel?.backgroundColor self.delButton.isHidden = !(carCellViewModel?.shouldShowDel)! if((carCellViewModel?.shouldShowDel)!){ self.stackView.isHidden = true }else{ self.stackView.isHidden = (carCellViewModel?.shouldShowAddToFav)! } if (carCellViewModel?.url != nil) { self.vehicleImageView.af_setImage(withURL: (carCellViewModel?.url)!) }else{ self.vehicleImageView.image=carCellViewModel?.defaultImage } cellViewModel.calculatePrice(completion: { [weak self] (price: String) in self?.price.text = price }) } @IBAction func deleteFromFav(sender: UIButton){ self.carCellViewModel?.deleteFav() } }
bddc9b2e00e34a70583d0cd26cd83d0d
26.701149
102
0.636515
false
false
false
false
tkester/swift-algorithm-club
refs/heads/master
Hash Table/HashTable.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play #if swift(>=4.0) print("Hello, Swift 4!") #endif // Playing with hash values "firstName".hashValue abs("firstName".hashValue) % 5 "lastName".hashValue abs("lastName".hashValue) % 5 "hobbies".hashValue abs("hobbies".hashValue) % 5 // Playing with the hash table var hashTable = HashTable<String, String>(capacity: 5) hashTable["firstName"] = "Steve" hashTable["lastName"] = "Jobs" hashTable["hobbies"] = "Programming Swift" print(hashTable) print(hashTable.debugDescription) let x = hashTable["firstName"] hashTable["firstName"] = "Tim" let y = hashTable["firstName"] hashTable["firstName"] = nil let z = hashTable["firstName"] print(hashTable) print(hashTable.debugDescription)
6f929762febae8714bda6bfec9d912f4
19.081081
54
0.726783
false
false
false
false
prebid/prebid-mobile-ios
refs/heads/master
EventHandlers/PrebidMobileGAMEventHandlers/Sources/GAMRewardedEventHandler.swift
apache-2.0
1
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import GoogleMobileAds import PrebidMobile @objcMembers public class GAMRewardedAdEventHandler : NSObject, RewardedEventHandlerProtocol, GADFullScreenContentDelegate, GADAdMetadataDelegate { // MARK: - Internal Properties var requestRewarded : GADRewardedAdWrapper? var proxyRewarded : GADRewardedAdWrapper? var embeddedRewarded: GADRewardedAdWrapper? var isExpectingAppEvent = false var appEventTimer: Timer? // MARK: - Public Properties public let adUnitID: String // MARK: - Public Methods public init(adUnitID: String) { self.adUnitID = adUnitID } // MARK: - GADAdMetadataDelegate public func adMetadataDidChange(_ ad: GADAdMetadataProvider) { let metadata = ad.adMetadata?[GADAdMetadataKey(rawValue: "AdTitle")] as? String if requestRewarded?.rewardedAd === ad && metadata == Constants.appEventValue { appEventDetected() } } // MARK: - RewardedEventHandlerProtocol // This is a very dirty hack based on dynamic properties of Objc Object. // Need to rewrite Interstitial ad loader to swift and find out how to pass the reward public weak var loadingDelegate: RewardedEventLoadingDelegate? public weak var interactionDelegate: RewardedEventInteractionDelegate? // MARK: - Public Methods public var isReady: Bool { if requestRewarded != nil { return false } if let _ = embeddedRewarded ?? proxyRewarded { return true } return false } public func show(from controller: UIViewController?) { if let ad = embeddedRewarded, let controller = controller { ad.present(from: controller, userDidEarnRewardHandler: { // Do nothing } ) } } public func requestAd(with bidResponse: BidResponse?) { guard let currentRequestRewarded = GADRewardedAdWrapper(adUnitID: adUnitID), let request = GAMRequestWrapper() else { let error = GAMEventHandlerError.gamClassesNotFound GAMUtils.log(error: error) loadingDelegate?.failedWithError(error) return } if let _ = requestRewarded { // request to primaryAdServer in progress return; } if proxyRewarded != nil || embeddedRewarded != nil { // rewarded already loaded return; } requestRewarded = currentRequestRewarded if let bidResponse = bidResponse { isExpectingAppEvent = (bidResponse.winningBid != nil) var targeting = [String : String]() if let requestTargeting = request.customTargeting { targeting.merge(requestTargeting) { $1 } } if let responseTargeting = bidResponse.targetingInfo { targeting.merge(responseTargeting) { $1 } } if !targeting.isEmpty { request.customTargeting = targeting } currentRequestRewarded.load(request: request) { [weak self] (prebidGADRewardedAd, error) in if let error = error { self?.rewardedAdDidFail(currentRequestRewarded, error: error) } if let ad = prebidGADRewardedAd { self?.requestRewarded?.adMetadataDelegate = self self?.rewardedAd(didReceive: ad) } } } } // MARK: - PBMGADRewardedAd loading callbacks func rewardedAd(didReceive ad: GADRewardedAdWrapper) { if requestRewarded === ad { primaryAdReceived() } } func rewardedAdDidFail(_ ad: GADRewardedAdWrapper, error: Error) { if requestRewarded === ad { requestRewarded = nil forgetCurrentRewarded() loadingDelegate?.failedWithError(error) } } func primaryAdReceived() { if isExpectingAppEvent { if appEventTimer != nil { return } appEventTimer = Timer.scheduledTimer(timeInterval: Constants.appEventTimeout, target: self, selector: #selector(appEventTimedOut), userInfo: nil, repeats: false) } else { let rewarded = requestRewarded requestRewarded = nil forgetCurrentRewarded() embeddedRewarded = rewarded loadingDelegate?.reward = rewarded?.reward loadingDelegate?.adServerDidWin() } } func forgetCurrentRewarded() { if embeddedRewarded != nil { embeddedRewarded = nil; } else if proxyRewarded != nil { proxyRewarded = nil; } } @objc func appEventTimedOut() { let rewarded = requestRewarded requestRewarded = nil forgetCurrentRewarded() embeddedRewarded = rewarded isExpectingAppEvent = false appEventTimer?.invalidate() appEventTimer = nil; loadingDelegate?.reward = rewarded?.reward loadingDelegate?.adServerDidWin() } func appEventDetected() { let rewarded = requestRewarded requestRewarded = nil if isExpectingAppEvent { if let _ = appEventTimer { appEventTimer?.invalidate() appEventTimer = nil } isExpectingAppEvent = false forgetCurrentRewarded() proxyRewarded = rewarded loadingDelegate?.reward = rewarded?.reward loadingDelegate?.prebidDidWin() } } }
a43d8f05dcdc72f94744b390b3366561
29.931193
103
0.571259
false
false
false
false
scamps88/ASCalendar
refs/heads/master
Example/Calendar/ASBodyV.swift
mit
1
// // ASBodyV.swift // Example // // Created by alberto.scampini on 18/05/2016. // Copyright © 2016 Alberto Scampini. All rights reserved. // // Recursive collectionview to show the month days // each cell is a month import UIKit class ASBodyV: UIView, UIScrollViewDelegate, ASCalendarNamesM { var scrollView : UIScrollView! var monthsV = Array<ASMonthV>() var headerV : UIView! var headerSeparatorV : UIView! var headerLabels = Array<UILabel>() var viewModel: ASBodyVM? { didSet { self.viewModel?.settingsM.selectedMonth.bindAndFire{ [unowned self] in _ = $0 self.reloadData() } self.viewModel?.settingsM.startByMonday.bindAndFire{ [unowned self] in _ = $0 self.reloadData() } self.viewModel?.settingsM.selectionStyle.bindAndFire{ [unowned self] in _ = $0 self.reloadData() } self.viewModel?.settingsM.selectedDay.bind { [unowned self] in _ = $0 self.reloadData() } self.viewModel?.settingsM.startByMonday.bindAndFire { [unowned self] in if ($0 == false) { let weekNames = self.getWeekNamesFromSunday() for i in 0...6 { self.headerLabels[i].text = weekNames[i] } } else { let weekNames = self.getWeekNamesFromMonday() for i in 0...6 { self.headerLabels[i].text = weekNames[i] } } } } } var theme : ASThemeVM! { didSet { theme.bodyBackgroundColor.bindAndFire { [unowned self] in self.backgroundColor = $0 } theme.bodyHeaderColor.bindAndFire { [unowned self] in self.headerV.backgroundColor = $0 } theme.bodyHeaderTextColor.bindAndFire { [unowned self] (color) in self.headerLabels.forEach({ (label) in label.textColor = color }) } theme.bodyHeaderSeparatorColor.bindAndFire { [unowned self] in self.headerSeparatorV.backgroundColor = $0 } theme.bodyHeaderTextFont.bindAndFire { [unowned self] (font) in self.headerLabels.forEach({ (label) in label.font = font }) } //set theme vm to month views monthsV.forEach { (monthV) in monthV.theme = theme } } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.whiteColor() //add scrollview ans calendar scrollView = UIScrollView(frame: self.bounds) scrollView.delegate = self scrollView.setContentOffset(CGPointMake(0, frame.height), animated: false) scrollView.showsVerticalScrollIndicator = false scrollView.pagingEnabled = true self.addSubview(scrollView) self.createMonthBoxes(frame.width, height: frame.height) //add header headerV = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 30)) headerV.backgroundColor = UIColor.grayColor() self.addSubview(headerV) //show day names label to header let dayLabelW = frame.width / 7 for i in 0...6 { let dayLabel = UILabel(frame: CGRect(x: CGFloat(i) * dayLabelW, y: 0, width: dayLabelW, height: 30)) dayLabel.textAlignment = .Center headerLabels.append(dayLabel) headerV.addSubview(dayLabel) } //add separator to header headerSeparatorV = UIView(frame: CGRect(x: 0, y: 29, width: frame.width, height: 1)) headerV.addSubview(headerSeparatorV) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: scrollView delegate func scrollViewDidScroll(scrollView: UIScrollView) { if (scrollView.contentOffset.y <= 0) { self.viewModel?.switchMonth(false) scrollView.setContentOffset(CGPointMake(0, self.frame.height), animated: false) } else if (scrollView.contentOffset.y >= self.frame.height * 2) { self.viewModel?.switchMonth(true) scrollView.setContentOffset(CGPointMake(0, self.frame.height), animated: false) } } //MARK: private methods internal func reloadCell(index : Int) { if (self.viewModel != nil) { let cell = self.monthsV[index] if (cell.viewModel == nil) { let viewModel = self.viewModel!.getViewModelForRow(index, currentViewModel: nil) cell.viewModel = viewModel } else { self.viewModel!.getViewModelForRow(index, currentViewModel: cell.viewModel) } } } internal func createMonthBoxes(width : CGFloat, height : CGFloat) { for i in 0..<3 { let monthV = ASMonthV.init(frame: CGRectMake(0, height * CGFloat(i), width, height)) scrollView.addSubview(monthV) monthsV.append(monthV) } self.scrollView.contentSize = CGSize(width: width, height: height * 3) } func reloadData() { self.reloadCell(0) self.reloadCell(1) self.reloadCell(2) } }
7a94b5c20a43d7e6d6a4566d4c4ad9eb
32.34104
112
0.538835
false
false
false
false
ktakayama/SimpleRSSReader
refs/heads/master
Classes/models/Feed.swift
mit
1
// // Feed.swift // SimpleRSSReader // // Created by Kyosuke Takayama on 2016/03/07. // Copyright © 2016年 aill inc. All rights reserved. // import Foundation import RealmSwift class Feed: Object, XMLFeedTransformable { dynamic var identifier: String = "" dynamic var title: String = "" dynamic var feedURL: String = "" dynamic var updatedAt: NSDate = NSDate() var entries = List<Entry>() var unreadCount: Int { if self.realm == nil { return entries.filter { $0.invalidated == false && $0.unread == true }.count } else { return entries.filter("unread == true").count } } override static func primaryKey() -> String? { return "identifier" } static func mapping(feedInfo: XMLFeedInfo, feedItems: [ XMLFeedItem ]) -> Feed { let feed = Feed() feed.identifier = feedInfo.identifier feed.title = feedInfo.title feed.updatedAt = NSDate() feedItems.forEach { item in let entry = Entry() entry.identifier = feed.identifier + "/" + item.identifier entry.title = item.title entry.summary = item.summary entry.publicAt = item.publicAt entry.thumbnailURL = item.thumbnailURL entry.linkURL = item.linkURL feed.entries.append(entry) } return feed } func insertRecentEntries(recentEntries: List<Entry>) { var newEntries = List<Entry>() if let realm = self.realm { newEntries.appendContentsOf(recentEntries.filter { self.entries.filter("identifier == %@", $0.identifier).count == 0 }) realm.addNotified(newEntries, update:true) } else { newEntries = recentEntries } self.entries.appendContentsOf(newEntries) } }
b3b580bf39f205daf904dfbf711a37e3
29.032787
131
0.603712
false
false
false
false
mhaslett/getthegist
refs/heads/master
CocoaPods-master/examples/Alamofire Example/Example/DetailViewController.swift
gpl-3.0
1
// DetailViewController.swift // // Copyright (c) 2014 Alamofire (http://alamofire.org) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Alamofire class DetailViewController: UITableViewController { enum Sections: Int { case Headers, Body } var request: Alamofire.Request? { didSet { oldValue?.cancel() self.title = self.request?.description self.refreshControl?.endRefreshing() self.headers.removeAll() self.body = nil self.elapsedTime = nil } } var headers: [String: String] = [:] var body: String? var elapsedTime: NSTimeInterval? override func awakeFromNib() { super.awakeFromNib() self.refreshControl?.addTarget(self, action: #selector(DetailViewController.refresh), forControlEvents: .ValueChanged) } // MARK: - UIViewController override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.refresh() } // MARK: - IBAction @IBAction func refresh() { if self.request == nil { return } self.refreshControl?.beginRefreshing() let start = CACurrentMediaTime() self.request?.response self.request?.responseString { response in let end = CACurrentMediaTime() self.elapsedTime = end - start response.response?.allHeaderFields.forEach { field, value in self.headers["\(field)"] = "\(value)" } switch response.result { case let .Success(body): self.body = body default: break } self.tableView.reloadData() self.refreshControl?.endRefreshing() } } // MARK: UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Sections(rawValue: section)! { case .Headers: return self.headers.count case .Body: return self.body == nil ? 0 : 1 default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch Sections(rawValue: indexPath.section)! { case .Headers: let cell = self.tableView.dequeueReusableCellWithIdentifier("Header")! as UITableViewCell let field = Array(self.headers.keys).sort(<)[indexPath.row] let value = self.headers[field] cell.textLabel!.text = field cell.detailTextLabel!.text = value return cell case .Body: let cell = self.tableView.dequeueReusableCellWithIdentifier("Body")! as UITableViewCell cell.textLabel!.text = self.body return cell } } // MARK: UITableViewDelegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String { if self.tableView(tableView, numberOfRowsInSection: section) == 0 { return "" } switch Sections(rawValue: section)! { case .Headers: return "Headers" case .Body: return "Body" } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch Sections(rawValue: indexPath.section)! { case .Body: return 300 default: return tableView.rowHeight } } override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String { if Sections(rawValue: section)! == .Body && self.elapsedTime != nil { let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .DecimalStyle return "Elapsed Time: \(numberFormatter.stringFromNumber(self.elapsedTime!)) sec" } return "" } }
082dcbbbd98d35a5de10a141676dfcfc
30.284848
126
0.633088
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/OSX/AudioKit/AudioKit for OSX.playground/Pages/Band Pass Butterworth Filter.xcplaygroundpage/Contents.swift
mit
2
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Band Pass Butterworth Filter //: ### Band-pass filters allow audio above a specified frequency range and bandwidth to pass through to an output. The center frequency is the starting point from where the frequency limit is set. Adjusting the bandwidth sets how far out above and below the center frequency the frequency band should be. Anything above that band should pass through. import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("mixloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true //: Next, we'll connect the audio sources to a band pass filter var filter = AKBandPassButterworthFilter(player) //: Set the parameters of the band pass filter here filter.centerFrequency = 5000 // Hz filter.bandwidth = 600 // Cents filter.rampTime = 1.0 AudioKit.output = filter AudioKit.start() //: User Interface Set up class PlaygroundView: AKPlaygroundView { //: UI Elements we'll need to be able to access var centerFrequencyLabel: Label? var bandwidthLabel: Label? override func setup() { addTitle("Band Pass Butterworth Filter") addLabel("Audio Player") addButton("Start", action: #selector(start)) addButton("Stop", action: #selector(stop)) addLabel("Band Pass Filter Parameters") addButton("Process", action: #selector(process)) addButton("Bypass", action: #selector(bypass)) centerFrequencyLabel = addLabel("Center Frequency: \(filter.centerFrequency) Hz") addSlider(#selector(setCenterFrequency), value: filter.centerFrequency, minimum: 20, maximum: 22050) bandwidthLabel = addLabel("Bandwidth \(filter.bandwidth) Cents") addSlider(#selector(setBandwidth), value: filter.bandwidth, minimum: 100, maximum: 12000) } //: Handle UI Events func start() { player.play() } func stop() { player.stop() } func process() { filter.play() } func bypass() { filter.bypass() } func setCenterFrequency(slider: Slider) { filter.centerFrequency = Double(slider.value) let frequency = String(format: "%0.1f", filter.centerFrequency) centerFrequencyLabel!.text = "Center Frequency: \(frequency) Hz" } func setBandwidth(slider: Slider) { filter.bandwidth = Double(slider.value) let bandwidth = String(format: "%0.1f", filter.bandwidth) bandwidthLabel!.text = "Bandwidth: \(bandwidth) Cents" } } let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 550)) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = view //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
d1d61bfcd939b3e1273984ff46590540
32.488636
351
0.668816
false
false
false
false
groovelab/SwiftBBS
refs/heads/master
SwiftBBS/SwiftBBS Server/BbsCommentRepository.swift
mit
1
// // BbsCommentRepository.swift // SwiftBBS // // Created by Takeo Namba on 2016/01/09. // Copyright GrooveLab // import PerfectLib // MARK: entity struct BbsCommentEntity { var id: UInt? var bbsId: UInt var comment: String var userId: UInt var createdAt: String? var updatedAt: String? } struct BbsCommentWithUserEntity { var id: UInt var bbsId: UInt var comment: String var userId: UInt var userName: String var createdAt: String var updatedAt: String func toDictionary() -> [String: Any] { return [ "id": id, "bbsId": bbsId, "comment": comment, "userId": userId, "userName": userName, "createdAt": createdAt, "updatedAt": updatedAt, ] } } // MARK: - repository class BbsCommentRepository : Repository { func insert(entity: BbsCommentEntity) throws -> UInt { let sql = "INSERT INTO bbs_comment (bbs_id, comment, user_id, created_at, updated_at) VALUES (?, ?, ?, \(nowSql), \(nowSql))" let params: Params = [ entity.bbsId, entity.comment, entity.userId ] return try executeInsertSql(sql, params: params) } func selectByBbsId(bbsId: UInt) throws -> [BbsCommentWithUserEntity] { let sql = "SELECT b.id, b.bbs_id, b.comment, b.user_id, u.name, b.created_at, b.updated_at FROM bbs_comment AS b " + "INNER JOIN user AS u ON u.id = b.user_id WHERE b.bbs_id = ? " + "ORDER BY b.id" let rows = try executeSelectSql(sql, params: [ bbsId ]) return rows.map { row in return createEntityFromRow(row) } } // row contains b.id, b.bbs_id, b.comment, b.user_id, u.name, b.created_at, b.updated_at private func createEntityFromRow(row: Row) -> BbsCommentWithUserEntity { return BbsCommentWithUserEntity( id: UInt(row[0] as! UInt32), bbsId: UInt(row[1] as! UInt32), comment: stringFromMySQLText(row[2] as? [UInt8]) ?? "", userId: UInt(row[3] as! UInt32), userName: row[4] as! String, createdAt: row[5] as! String, updatedAt: row[6] as! String ) } }
477a8c99673f9d9b819c366a9a89b2eb
29.671233
133
0.585529
false
false
false
false
kickstarter/ios-oss
refs/heads/main
KsApi/models/Money.swift
apache-2.0
1
import Foundation import Prelude public struct Money: Decodable, Equatable { public var amount: Double public var currency: CurrencyCode? public var symbol: String? public enum CurrencyCode: String, CaseIterable, Decodable, Equatable { case aud = "AUD" case cad = "CAD" case chf = "CHF" case dkk = "DKK" case eur = "EUR" case gbp = "GBP" case hkd = "HKD" case jpy = "JPY" case mxn = "MXN" case nok = "NOK" case nzd = "NZD" case pln = "PLN" case sek = "SEK" case sgd = "SGD" case usd = "USD" } } extension Money { private enum CodingKeys: CodingKey { case amount case currency case symbol } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let amount = (try values.decode(String?.self, forKey: .amount)).flatMap(Double.init) else { throw DecodingError.dataCorruptedError( forKey: .amount, in: values, debugDescription: "Not a valid double" ) } self.amount = amount self.currency = try values.decodeIfPresent(CurrencyCode.self, forKey: .currency) self.symbol = try values.decodeIfPresent(String.self, forKey: .symbol) } }
57a07a1829832672c1e7de7ecda3e9e1
24.458333
101
0.653846
false
false
false
false
zarghol/documentation-provider
refs/heads/master
Sources/DocumentationProvider/EmptyTag.swift
mit
1
// // EmptyTag.swift // Checkout // // Created by Clément Nonn on 15/12/2016. // // import Foundation import Vapor import Leaf class Empty: BasicTag { public enum Error: Swift.Error { case expected1Argument } let name = "empty" public func run(arguments: ArgumentList) throws -> Node? { guard arguments.count == 1 else { throw Error.expected1Argument } return nil } public func shouldRender( tagTemplate: TagTemplate, arguments: ArgumentList, value: Node? ) -> Bool { guard let arg = arguments.first else { return true } if let array = arg.array, array.count == 0 { return true } if let dico = arg.object, dico.count == 0 { return true } return arg.isNull } } // //class NamedIndex: BasicTag { // let name = "namedIndex" // // func run(arguments: [Argument]) throws -> Node? { // guard // arguments.count == 3, // let array = arguments[0].value?.nodeArray, // let index = arguments[1].value?.int, // let name = arguments[2].value?.string, // index < array.count // else { return nil } // return .object([name: array[index]]) // } // // public func render( // stem: Stem, // context: LeafContext, // value: Node?, // leaf: Leaf // ) throws -> Bytes { // guard let value = value else { fatalError("Value must not be nil") } // context.push(value) // let rendered = try stem.render(leaf, with: context) // context.pop() // // return rendered + [.newLine] // } //} // //class CountEqual: BasicTag { // let name = "countEqual" // // func run(arguments: [Argument]) throws -> Node? { // guard arguments.count == 2, // let array = arguments[0].value?.nodeArray, // let expectedCount = arguments[1].value?.int, // array.count == expectedCount else { // return nil // } // // return Node("ok") // } //}
856eed6c99fc009381c79ee39d74fb69
23.101124
78
0.524009
false
false
false
false
Constructor-io/constructorio-client-swift
refs/heads/master
UserApplicationTests/Delegate/AutocompleteDelegateTests.swift
mit
1
// // AutocompleteDelegateTests.swift // UserApplicationTests // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import XCTest import ConstructorAutocomplete class AutocompleteDelegateTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test_viewDidLoad_callsDelegateMethod() { let expectation = self.expectation(description: "searchControllerDidLoad delegate method should get called.") let viewController = CIOAutocompleteViewController.instantiate() let delegate = AutocompleteDelegateWrapper() viewController.delegate = delegate delegate.onLoad = { expectation.fulfill() } viewController.showInNewWindow() self.waitForExpectationWithDefaultHandler() } func test_viewWillAppear_callsDelegateMethod() { let expectation = self.expectation(description: "searchControllerWillAppear delegate method should get called.") let viewController = CIOAutocompleteViewController.instantiate() let delegate = AutocompleteDelegateWrapper() viewController.delegate = delegate delegate.onWillAppear = { expectation.fulfill() } viewController.showInNewWindow() self.waitForExpectationWithDefaultHandler() } func test_searching_callsDelegateMethod() { let expectation = self.expectation(description: "searchControllerWillAppear delegate method should get called.") let viewController = CIOAutocompleteViewController.instantiate() let searchTerm = "term" let delegate = AutocompleteDelegateWrapper() viewController.delegate = delegate delegate.onSearchPerformed = { term in XCTAssertEqual(searchTerm, term, "Delegate method should return exactly the same search term that the user typed") expectation.fulfill() } viewController.showInNewWindow() viewController.searchController.searchBar.text = searchTerm self.waitForExpectationWithDefaultHandler() } }
14341b42fd39fa2fae52de3449e418fe
30.813333
126
0.699497
false
true
false
false
donald-pinckney/SwiftNum
refs/heads/master
Sources/SignalProcessing/FFT.swift
mit
1
// // FFT.swift // SwiftNum // // Created by Donald Pinckney on 12/27/16. // // import Foundation import Accelerate private var fft_setup: vDSP_DFT_SetupD! = nil private var fft_currentLength: Int = 0 func fft_set_length(_ length: Int) { fft_currentLength = length fft_setup = vDSP_DFT_zrop_CreateSetupD(nil, vDSP_Length(2 * length), vDSP_DFT_Direction.FORWARD)! } func fft(_ inputArray: [Double]) -> [(magnitude: Double, phase: Double)] { let length = inputArray.count precondition(length.isPowerOfTwo) if length != fft_currentLength { vDSP_DFT_DestroySetupD(fft_setup) fft_set_length(length) } let zeroArray = [Double](repeating:0.0, count:length) var outputReal = [Double](repeating:0.0, count: length) var outputImag = [Double](repeating:0.0, count: length) vDSP_DFT_ExecuteD(fft_setup, inputArray, zeroArray, &outputReal, &outputImag) var outputCombined = [Double](repeating: 0.0, count: length) cblas_dcopy(Int32(length / 2), outputReal, 1, &outputCombined, 2) cblas_dcopy(Int32(length / 2), outputImag, 1, &outputCombined + 1, 2) var normFactor = 1.0 / Double(length) vDSP_vsmulD(outputCombined, vDSP_Stride(1), &normFactor, &outputCombined, vDSP_Stride(1), vDSP_Length(length)) var polarCombined = [Double](repeating: 0.0, count: length) vDSP_polarD(outputCombined, 2, &polarCombined, 2, vDSP_Length(length / 2)) let polarPtr = UnsafeRawPointer(polarCombined) let polarTuplePtr = polarPtr.assumingMemoryBound(to: (magnitude: Double, phase: Double).self) let polarTupleBufferPtr = UnsafeBufferPointer<(magnitude: Double, phase: Double)>(start: polarTuplePtr, count: length / 2) return Array(polarTupleBufferPtr) }
b7f6d7e490d8aaddd6e2fbcd1af34a84
30.1
126
0.652733
false
false
false
false
zefferus/BidirectionalMap
refs/heads/master
Sources/BidirectionalMap.swift
mit
1
// // BidirectionalMap.swift // Wing // // Created by Tom Wilkinson on 3/31/16. // Copyright © 2016 Sparo, Inc. All rights reserved. // import Foundation private extension Dictionary { /** Returns the element at the given optional index if index is not optional - parameter index: Index? - returns: Element? */ subscript (safe key: Key?) -> Value? { get { guard let key = key else { return nil } return self[key] } set { guard let key = key else { return } self[key] = newValue } } } public struct BidirectionalMap<Key: Hashable, Value: Hashable>: CollectionType, DictionaryLiteralConvertible { public typealias Element = (Key, Value) public typealias Index = BidirectionalMapIndex<Key, Value> private var leftDictionary: [Key: Value] private var rightDictionary: [Value: Key] /** Create an empty bidirectional map. */ public init() { leftDictionary = [:] rightDictionary = [:] } /** Create a bidirectional map with a minimum capacity. The true capacity will be the smallest power of 2 greater than `minimumCapacity`. - parameter minimumCapacity: */ public init(minimumCapacity: Int) { leftDictionary = [Key: Value](minimumCapacity: minimumCapacity) rightDictionary = [Value: Key](minimumCapacity: minimumCapacity) } /** Create a bidirectional map with the sequence. If more than one key exists for a value, one of them will be nondeterministically chosen - parameter sequence: */ public init<S: SequenceType where S.Generator.Element == (Key, Value)>(_ sequence: S) { self.init(minimumCapacity: sequence.underestimateCount()) for (key, value) in sequence { self[key] = value } } /** The position of the first element in a non-empty bidirectional map Identical to `endIndex` in an empty bidirectional map - Complexity: Amortized O(1) if `self` does not wrap a bridged `NSDictionary`, O(N) otherwise - returns: BidirectionalMapIndex */ public var startIndex: BidirectionalMapIndex<Key, Value> { return BidirectionalMapIndex(dictionaryIndex: leftDictionary.startIndex) } /** The position of the last element in a non-empty bidirectional map. Identical to `endIndex` in an empty bidirectional map. - Complexity: Amortized O(1) if `self` does not wrap a bridged `NSDictionary`, O(N) otherwise - returns: BidirectionalMapIndex */ public var endIndex: BidirectionalMapIndex<Key, Value> { return BidirectionalMapIndex(dictionaryIndex: leftDictionary.endIndex) } /** - parameter key: - returns: `Index` for the given key, or `nil` if the key is not present in the bidirectional map */ @warn_unused_result public func indexForKey(key: Key) -> BidirectionalMapIndex<Key, Value>? { return BidirectionalMapIndex(dictionaryIndex: leftDictionary.indexForKey(key)) } /** - parameter value: - returns: `Index` for the given value, or `nil` if the value is not present in the bidirectional map */ @warn_unused_result public func indexForValue(value: Value) -> BidirectionalMapIndex<Key, Value>? { guard let key = rightDictionary[value] else { return nil } return BidirectionalMapIndex(dictionaryIndex: leftDictionary.indexForKey(key)) } /** - parameter position: - returns: `(Key, Value)` pair for the `Index` */ public subscript (position: BidirectionalMapIndex<Key, Value>) -> (Key, Value) { return leftDictionary[position.dictionaryIndex] } /** This behaves exactly as does the normal `Dictionary` subscript, except that here key is also an Optional, and if nil will always return nil (and won't do anything for a set) - parameter key: - returns: Value? */ public subscript (key: Key?) -> Value? { get { guard let key = key else { return nil } return leftDictionary[key] } set { guard let key = key else { return } setKeyAndValue(key, value: newValue) } } /** This will behave the same as subscript with key, except it uses the value to do the lookup - parameter value: Optional value of the bidirectional map - returns: Key? */ public subscript (value value: Value?) -> Key? { get { guard let value = value else { return nil } return rightDictionary[value] } set(newKey) { guard let value = value else { return } setKeyAndValue(newKey, value: value) } } /** Private helper to set both the key and the value. - parameter key: - parameter value: */ private mutating func setKeyAndValue(key: Key?, value: Value?) { leftDictionary[safe: rightDictionary[safe: value]] = nil rightDictionary[safe: leftDictionary[safe: key]] = nil leftDictionary[safe: key] = value rightDictionary[safe: value] = key } /** Update the value stored in the dicationary for the given key, or, if the key does not exist, add a new key-value pair to the bidirectional map. - parameter value: - parameter forKey: - returns: The value that was replaced, or `nil` if a new key-value pair was added. */ public mutating func updateValue(value: Value, forKey key: Key) -> Value? { let oldValue = self[key] self[key] = value return oldValue } /** Update the key stored in the dicationary for the given value, or, if the value does not exist, add a new key-value pair to the bidirectional map. - parameter key: - parameter forValue: - returns: The value that was replaced, or `nil` if a new key-value pair was added. */ public mutating func updateKey(key: Key, forValue value: Value) -> Key? { let oldKey = self[value: value] self[value: value] = key return oldKey } /** Remove the key-value pair at `index` Invalidates all indices with respect to `self`. - Complexity: O(`self.count`) - returns: The removed `Element` */ public mutating func removeAtIndex(index: BidirectionalMapIndex<Key, Value>) -> (Key, Value) { let pair = leftDictionary.removeAtIndex(index.dictionaryIndex) rightDictionary.removeValueForKey(pair.1) return pair } /** Removes a given key and its value from the bidirectional map. - parameter key: - returns: The value that was removed, or `nil` if the key was not present in the bidirectional map */ public mutating func removeValueForKey(key: Key) -> Value? { guard let value = leftDictionary.removeValueForKey(key) else { return nil } rightDictionary.removeValueForKey(value) return value } /** Removes a given value and its key from the bidirectional map. - parameter value: - returns: The key that was removed, or `nil` if the value was not present in the bidirectional map */ public mutating func removeKeyForValue(value: Value) -> Key? { guard let key = rightDictionary.removeValueForKey(value) else { return nil } leftDictionary.removeValueForKey(key) return key } /** Removes all elements. - Postcondition: `capacity == 0` if `keepCapacity` is `false`, othwerise the capacity will not be decreased. Invalidates all indices with respect to `self`. - parameter keepCapacty: If `true`, the operation preserves the storage capacity that the collection has, otherwise the underlying storage is released. The default is `false`. - Complexity: O(`self.count`). */ public mutating func removeAll(keepCapacity keepCapacity: Bool = false) { leftDictionary.removeAll(keepCapacity: keepCapacity) rightDictionary.removeAll(keepCapacity: keepCapacity) } /** The number of entries in the dictionary. - Complexity: O(1) */ public var count: Int { return leftDictionary.count } /** - returns: A generator over the (key, value) pairs. - Complexity: O(1). */ public func generate() -> BidirectionalMapGenerator<Key, Value> { return BidirectionalMapGenerator(dictionaryGenerator: leftDictionary.generate()) } /** Create an instance initialized with `elements`. - parameter elements: */ public init(dictionaryLiteral elements: (Key, Value)...) { self.init(minimumCapacity: elements.count) for (key, value) in elements { leftDictionary[key] = value rightDictionary[value] = key } } /** A collection containing just the keys of `self`. Keys appear in the same order as they occur in the `.0` member of key-value pairs in `self`. Each key in the result has a unique value. */ public var keys: LazyMapCollection<BidirectionalMap<Key, Value>, Key> { return self.lazy.map { $0.0 } } /** A collection containing just the values of `self`. Values appear in the same order as they occur in the `.1` member of key-value pairs in `self`. Each vaue in the result has a unique value. */ public var values: LazyMapCollection<BidirectionalMap<Key, Value>, Value> { return self.lazy.map { $0.1 } } /// `true` iff `count == 0`. public var isEmpty: Bool { return leftDictionary.isEmpty } } extension BidirectionalMap : CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of `self`. public var description: String { return leftDictionary.description } /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return leftDictionary.description } } extension BidirectionalMap { /** If `!self.isEmpty`, return the first key-value pair in the sequence of elements, otherwise return `nil`. - Complexity: Amortized O(1) */ public mutating func popFirst() -> (Key, Value)? { guard !isEmpty else { return nil } return removeAtIndex(startIndex) } } /// A generator over the members of a `BidirectionalMap<Key, Value>`. public struct BidirectionalMapGenerator<Key: Hashable, Value: Hashable> : GeneratorType { private var dictionaryGenerator: DictionaryGenerator<Key, Value> /** Create a new bidirectional map generate wrapper over the dictionary generator - parameter dictionaryGenerator: */ private init?(dictionaryGenerator: DictionaryGenerator<Key, Value>?) { guard let dictionaryGenerator = dictionaryGenerator else { return nil } self.dictionaryGenerator = dictionaryGenerator } /** Create a new bidirectional map generate wrapper over the dictionary generator - parameter dictionaryGenerator: */ private init(dictionaryGenerator: DictionaryGenerator<Key, Value>) { self.dictionaryGenerator = dictionaryGenerator } /** Advance to the next element and return in, or `nil` if no next element exists. - Requires: No preceding call to `self.next()` has returned `nil`. */ public mutating func next() -> (Key, Value)? { return dictionaryGenerator.next() } } /** Less than operator for bidirectional map index - parameter lhs: - parameter rhs: - returns: Bool */ public func < <Key: Hashable, Value: Hashable>( lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool { return lhs.dictionaryIndex < rhs.dictionaryIndex } /** Less than or equal to operator for bidirectional map index - parameter lhs: - parameter rhs: - returns: Bool */ public func <= <Key: Hashable, Value: Hashable>( lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool { return lhs.dictionaryIndex <= rhs.dictionaryIndex } /** Greater than operator for bidirectional map index - parameter lhs: - parameter rhs: - returns: Bool */ public func > <Key: Hashable, Value: Hashable>( lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool { return lhs.dictionaryIndex > rhs.dictionaryIndex } /** Greater than or equal operator for bidirectional map index - parameter lhs: - parameter rhs: - returns: Bool */ public func >= <Key: Hashable, Value: Hashable>( lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool { return lhs.dictionaryIndex >= rhs.dictionaryIndex } /** Equal operator for bidirectional map index - parameter lhs: - parameter rhs: - returns: Bool */ public func == <Key: Hashable, Value: Hashable>( lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool { return lhs.dictionaryIndex == rhs.dictionaryIndex } /** Used to access the key-value pairs in an instance of `BidirectionalMap<Key, Value>`. Bidirectional map has three subscripting interfaces: 1. Subscripting with an optional key, yielding an optional value: v = d[k]! 2. Subscripting with an optional value, yielding an optional key: k = d[k]! 3. Subscripting with an index, yielding a key-value pair: (k, v) = d[i] */ public struct BidirectionalMapIndex<Key: Hashable, Value: Hashable> : ForwardIndexType, Comparable { private let dictionaryIndex: DictionaryIndex<Key, Value> /** Create a new bidirectional map index from the underlying dictionary index - parameter dictionaryIndex: */ private init?(dictionaryIndex: DictionaryIndex<Key, Value>?) { guard let dictionaryIndex = dictionaryIndex else { return nil } self.dictionaryIndex = dictionaryIndex } /** Create a new bidirectional map index from the underlying dictionary index - parameter dictionaryIndex: */ private init(dictionaryIndex: DictionaryIndex<Key, Value>) { self.dictionaryIndex = dictionaryIndex } /** - Requires: The next value is representable. - returns: The next consecutive value after `self`. */ public func successor() -> BidirectionalMapIndex<Key, Value> { return BidirectionalMapIndex(dictionaryIndex: dictionaryIndex.successor()) } }
00431a530326ffc1b4e5676cb82f3236
27.926214
100
0.64174
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
refs/heads/master
iOS/Venue/Controllers/PlaceInviteViewController.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /// ViewController to show who has been inivited to a place class PlaceInviteViewController: VenueUIViewController { var viewModel: PlaceInviteViewModel! @IBOutlet weak var avatarCollectionView: UICollectionView! @IBOutlet weak var bottomBar: UIView! @IBOutlet weak var containerViewBottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() bottomBar.hidden = true } override func viewWillAppear(animated: Bool) { // set navigation bar to be light blue setupNavigationBar() } /** Style native navigationBar to avoid any UI issues */ func setupNavigationBar() { navigationController?.setNavigationBarHidden(false, animated: true) navigationController?.navigationBar.barTintColor = UIColor.venueLightBlue() navigationController?.navigationBar.translucent = false // Setup back button as just an arrow let backButton = UIBarButtonItem(image: UIImage(named: "back"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("popVC")) self.navigationItem.leftBarButtonItem = nil self.navigationItem.leftBarButtonItem = backButton // Remove 1px shadow under nav bar navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navigationController?.navigationBar.shadowImage = UIImage() } func popVC() { self.navigationController?.popViewControllerAnimated(true) } func showBottomBar() { bottomBar.hidden = false // move container up so bottom bar does not block table containerViewBottomConstraint.constant = bottomBar.frame.height } func hideBottomBar() { bottomBar.hidden = true // move container back down containerViewBottomConstraint.constant = 0 } /** Segue preparation for selection of date picker and embedment of the peopleListViewController */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // sends the selected user and the poi to the date picker if let datePickerViewController = segue.destinationViewController as? DatePickerViewController { datePickerViewController.selectedUsers = viewModel.selectedUsers datePickerViewController.location = viewModel.location } else if let storyboardViewController = segue.destinationViewController as? RBStoryboardLink { // segeue triggered in embeded if let peopleListViewController = storyboardViewController.scene as? PeopleListViewController { // sets people list delegate to self so PeopleListDelegate methods get called peopleListViewController.delegate = self } } } } // MARK: - PeopleListDelegate Implementation extension PlaceInviteViewController: PeopleListDelegate { /** Handles selection of row by toggling selction icon and mananging the avatar collection on the bottom bar */ func didSelectRow(tableView: UITableView, indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! PeopleTableViewCell if !cell.isSelectedForInvite { viewModel.markSelectedAndUpdateCollection(cell, indexPath: indexPath, avatarCollectionView: avatarCollectionView) } else { viewModel.markDeselectedAndUpdateCollection(cell, indexPath: indexPath, avatarCollectionView: avatarCollectionView) } if viewModel.selectedUsers.count > 0 && bottomBar.hidden == true { showBottomBar() } else if viewModel.selectedUsers.count == 0 && bottomBar.hidden == false { hideBottomBar() } tableView.deselectRowAtIndexPath(indexPath, animated: false) } /** Makes sure that peopleTableViewCell is properly marked if selected */ func additionalSetupForCell(cell: PeopleTableViewCell) { viewModel.setupPeopleTableViewCell(cell) } } // MARK: - UICollectionView Methods extension PlaceInviteViewController : UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.selectedUsers.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("avatarCell", forIndexPath: indexPath) as! AvatarImageCollectionViewCell return viewModel.setupAvatarImageCollectionCell(cell, row: indexPath.row) } }
a18d765aeb93511ee0930fe49c89ad15
37.207692
146
0.698611
false
false
false
false
opfeffer/swift-sodium
refs/heads/master
Sodium/Sign.swift
isc
1
// // Sign.swift // Sodium // // Created by Frank Denis on 12/28/14. // Copyright (c) 2014 Frank Denis. All rights reserved. // import Foundation import libsodium public class Sign { public let SeedBytes = Int(crypto_sign_seedbytes()) public let PublicKeyBytes = Int(crypto_sign_publickeybytes()) public let SecretKeyBytes = Int(crypto_sign_secretkeybytes()) public let Bytes = Int(crypto_sign_bytes()) public let Primitive = String(validatingUTF8: crypto_sign_primitive()) public typealias PublicKey = Data public typealias SecretKey = Data public struct KeyPair { public let publicKey: PublicKey public let secretKey: SecretKey public init(publicKey: PublicKey, secretKey: SecretKey) { self.publicKey = publicKey self.secretKey = secretKey } } /** Generates a signing secret key and a corresponding public key. - Returns: A key pair containing the secret key and public key. */ public func keyPair() -> KeyPair? { var pk = Data(count: PublicKeyBytes) var sk = Data(count: SecretKeyBytes) let result = pk.withUnsafeMutableBytes { pkPtr in return sk.withUnsafeMutableBytes { skPtr in return crypto_sign_keypair(pkPtr, skPtr) } } if result != 0 { return nil } return KeyPair(publicKey: pk, secretKey: sk) } /** Generates a signing secret key and a corresponding public key derived from a seed. - Parameter seed: The value from which to derive the secret and public key. - Returns: A key pair containing the secret key and public key. */ public func keyPair(seed: Data) -> KeyPair? { if seed.count != SeedBytes { return nil } var pk = Data(count: PublicKeyBytes) var sk = Data(count: SecretKeyBytes) let result = pk.withUnsafeMutableBytes { pkPtr in return sk.withUnsafeMutableBytes { skPtr in return seed.withUnsafeBytes { seedPtr in return crypto_sign_seed_keypair(pkPtr, skPtr, seedPtr) } } } if result != 0 { return nil } return KeyPair(publicKey: pk, secretKey: sk) } /** Signs a message with the sender's secret key - Parameter message: The message to encrypt. - Parameter secretKey: The sender's secret key. - Returns: The signed message. */ public func sign(message: Data, secretKey: SecretKey) -> Data? { if secretKey.count != SecretKeyBytes { return nil } var signedMessage = Data(count: message.count + Bytes) let result = signedMessage.withUnsafeMutableBytes { signedMessagePtr in return message.withUnsafeBytes { messagePtr in return secretKey.withUnsafeBytes { secretKeyPtr in return crypto_sign( signedMessagePtr, nil, messagePtr, CUnsignedLongLong(message.count), secretKeyPtr) } } } if result != 0 { return nil } return signedMessage } /** Computes a detached signature for a message with the sender's secret key. - Parameter message: The message to encrypt. - Parameter secretKey: The sender's secret key. - Returns: The computed signature. */ public func signature(message: Data, secretKey: SecretKey) -> Data? { if secretKey.count != SecretKeyBytes { return nil } var signature = Data(count: Bytes) let result = signature.withUnsafeMutableBytes { signaturePtr in return message.withUnsafeBytes { messagePtr in return secretKey.withUnsafeBytes { secretKeyPtr in return crypto_sign_detached( signaturePtr, nil, messagePtr, CUnsignedLongLong(message.count), secretKeyPtr) } } } if result != 0 { return nil } return signature } /** Verifies a signed message with the sender's public key. - Parameter signedMessage: The signed message to verify. - Parameter publicKey: The sender's public key. - Returns: `true` if verification is successful. */ public func verify(signedMessage: Data, publicKey: PublicKey) -> Bool { let signature = signedMessage.subdata(in: 0..<Bytes) as Data let message = signedMessage.subdata(in: Bytes..<signedMessage.count) as Data return verify(message: message, publicKey: publicKey, signature: signature) } /** Verifies the detached signature of a message with the sender's public key. - Parameter message: The message to verify. - Parameter publicKey: The sender's public key. - Parameter signature: The detached signature to verify. - Returns: `true` if verification is successful. */ public func verify(message: Data, publicKey: PublicKey, signature: Data) -> Bool { if publicKey.count != PublicKeyBytes { return false } return signature.withUnsafeBytes { signaturePtr in return message.withUnsafeBytes { messagePtr in return publicKey.withUnsafeBytes { publicKeyPtr in return crypto_sign_verify_detached( signaturePtr, messagePtr, CUnsignedLongLong(message.count), publicKeyPtr) == 0 } } } } /** Extracts and returns the message data of a signed message if the signature is verified with the sender's secret key. - Parameter signedMessage: The signed message to open. - Parameter publicKey: The sender's public key. - Returns: The message data if verification is successful. */ public func open(signedMessage: Data, publicKey: PublicKey) -> Data? { if publicKey.count != PublicKeyBytes || signedMessage.count < Bytes { return nil } var message = Data(count: signedMessage.count - Bytes) var mlen: CUnsignedLongLong = 0; let result = message.withUnsafeMutableBytes { messagePtr in return signedMessage.withUnsafeBytes { signedMessagePtr in return publicKey.withUnsafeBytes { publicKeyPtr in return crypto_sign_open(messagePtr, &mlen, signedMessagePtr, CUnsignedLongLong(signedMessage.count), publicKeyPtr) } } } if result != 0 { return nil } return message } }
bd11fef87303e51a602f9863a37e737a
30.156951
134
0.589378
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/PostContentPresentationController.swift
apache-2.0
1
// // PostContentPresentationController.swift // Slide for Reddit // // Created by Jonathan Cole on 8/3/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import AVFoundation import UIKit class PostContentPresentationController: UIPresentationController { private var sourceImageView: UIView init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?, sourceImageView: UIView) { self.sourceImageView = sourceImageView super.init(presentedViewController: presentedViewController, presenting: presentingViewController) } override func containerViewWillLayoutSubviews() { presentedView?.frame = frameOfPresentedViewInContainerView } // func transformFromRect(from source: CGRect, toRect destination: CGRect) -> CGAffineTransform { // return CGAffineTransform.identity // .translatedBy(x: destination.midX - source.midX, y: destination.midY - source.midY) // .scaledBy(x: destination.width / source.width, y: destination.height / source.height) // } // override func presentationTransitionWillBegin() { // guard let coordinator = presentedViewController.transitionCoordinator else { // return // } // // if let vc = self.presentedViewController as? ModalMediaViewController { // // let image = (sourceImageView as! UIImageView).image! // let fromRect = vc.view.convert(sourceImageView.bounds, from: sourceImageView) // // if let embeddedVC = vc.embeddedVC as? ImageMediaViewController { // // presentingViewController.view.layoutIfNeeded() // // let inner = AVMakeRect(aspectRatio: embeddedVC.imageView.bounds.size, insideRect: embeddedVC.view.bounds) // let toRect = vc.view.convert(inner, from: embeddedVC.scrollView) // // let newTransform = transformFromRect(from: toRect, toRect: fromRect) // // embeddedVC.scrollView.transform = embeddedVC.scrollView.transform.concatenating(newTransform) // let storedZ = embeddedVC.scrollView.layer.zPosition // embeddedVC.scrollView.layer.zPosition = sourceImageView.layer.zPosition // coordinator.animate(alongsideTransition: { _ in // embeddedVC.scrollView.transform = CGAffineTransform.identity // embeddedVC.scrollView.layer.zPosition = storedZ // }) // // } else if let embeddedVC = vc.embeddedVC as? VideoMediaViewController { // // if embeddedVC.isYoutubeView { // // } else { // presentingViewController.view.layoutIfNeeded() // // let inner = AVMakeRect(aspectRatio: image.size, insideRect: embeddedVC.view.bounds) // let toRect = vc.view.convert(inner, from: embeddedVC.view) // // let newTransform = transformFromRect(from: toRect, toRect: fromRect) // // embeddedVC.videoView.transform = embeddedVC.videoView.transform.concatenating(newTransform) // coordinator.animate(alongsideTransition: { _ in // embeddedVC.videoView.transform = CGAffineTransform.identity // }) // } // } // } // } }
a6cf457586b319b05a330fdc0c13b99c
39.915663
123
0.641048
false
false
false
false
byu-oit/ios-byuSuite
refs/heads/dev
byuSuite/Apps/Parking/controller/VehicleViewController.swift
apache-2.0
1
// // VehicleViewController.swift // byuSuite // // Created by Erik Brady on 11/22/17. // Copyright © 2017 Brigham Young University. All rights reserved. // let UNWIND_TO_VEHICLE = "unwindToVehicle" private let ACTIVATE = "Activate" private let DEACTIVATE = "Deactivate" private let EDIT_TEXT = "Edit" private let DELETE_TEXT = "Delete" protocol VehicleViewControllerDelegate { func startActivating(vehicle: Vehicle) } class VehicleViewController: ByuTableDataViewController { //MARK: IBOutlets @IBOutlet private weak var editDeleteButton: UIBarButtonItem! @IBOutlet private weak var activateButton: UIBarButtonItem! //MARK: Public Properties var delegate: VehicleViewControllerDelegate! var vehicle: Vehicle! var eligibility: AddVehicleEligibility! override func viewDidLoad() { super.viewDidLoad() loadTableData() //Set up the button text on the bottom if vehicle.active { editDeleteButton.title = EDIT_TEXT activateButton.title = DEACTIVATE } else { editDeleteButton.title = DELETE_TEXT activateButton.title = ACTIVATE } } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "edit", let vc = segue.destination as? AddEditVehicleViewController { vc.editVehicle = vehicle } } //MARK: IBActions @IBAction func unwindToVehicleView(_ segue: UIStoryboardSegue) { //Called when a vehicle has been successfully edited loadTableData() NotificationCenter.default.post(name: VEHICLE_CHANGE_NOTIFICATION, object: nil) } @IBAction func activateVehicle(_ sender: Any) { spinner?.startAnimating() if !vehicle.active { if eligibility.canRegisterPerm { //Activate Vehicle ParkingRegistrationClient.registerVehicle(vehicle: vehicle, callback: { (vehicle, error) in self.spinner?.stopAnimating() if let error = error { super.displayAlert(error: error, title: "Activation Failed") } else { super.displayAlert(title: "Success", message: "Successfully activated vehicle. Be aware that it can take up to 15 minutes in some cases for privileges to reflect on this vehicle.", alertHandler: { (_) in self.performSegue(withIdentifier: UNWIND_TO_MY_VEHICLES, sender: nil) }) } }) } else { self.delegate.startActivating(vehicle: self.vehicle) self.popBack() } } else { //Deactivate Vehicle ParkingRegistrationClient.unregisterVehicle(vehicle: vehicle, callback: { (vehicle, error) in self.spinner?.stopAnimating() if let error = error { super.displayAlert(error: error, title: "Deactivation Failed") } else { super.displayAlert(title: "Success", message: "Successfully deactivated vehicle.", alertHandler: { (_) in self.performSegue(withIdentifier: UNWIND_TO_MY_VEHICLES, sender: nil) }) } }) } } @IBAction func editDeleteButtonTapped(_ sender: Any) { if vehicle.active { performSegue(withIdentifier: "edit", sender: sender) } else if let vehicleId = vehicle.vehicleId { spinner?.startAnimating() ParkingRegistrationClient.deleteVehicle(vehicleId: vehicleId, callback: { (error) in self.spinner?.stopAnimating() if let error = error { super.displayAlert(error: error) } else { super.displayAlert(title: "Success", message: "Successfully deleted vehicle", alertHandler: { (_) in self.performSegue(withIdentifier: UNWIND_TO_MY_VEHICLES, sender: nil) }) } }) } } //MARK: Custom Methods private func loadTableData() { tableData = TableData(rows: [ Row(text: "Make", detailText: vehicle.makeCode?.descr), Row(text: "Model", detailText: vehicle.model), Row(text: "Color", detailText: vehicle.colorCode?.descr), Row(text: "State", detailText: vehicle.stateCode?.descr), Row(text: "License Plate", detailText: vehicle.licensePlate) ]) tableView.reloadData() } }
beff69e614d15eb21c2c3e7658d5c370
28.969466
209
0.705298
false
false
false
false
markedwardmurray/Starlight
refs/heads/master
Starlight/Starlight/Data/StoreCoordinator.swift
mit
1
// // StoreCoordinator.swift // Starlight // // Created by Mark Murray on 11/26/16. // Copyright © 2016 Mark Murray. All rights reserved. // import Foundation import SwiftyJSON enum JSONResult { case error(error: Error) case json(json: JSON) } enum SuccessResult { case error(error: Error) case success(success: Bool) } enum StoreError: Error { case fileDoesNotExistAtPath case storedFileIsObsolete } fileprivate enum Directory { case temporary case documents } class StoreCoordinator { static let sharedInstance = StoreCoordinator() let gregorian = NSCalendar(calendarIdentifier: .gregorian)! //MARK: Private properties and methods fileprivate let fileManager = FileManager.default fileprivate let k_dot_json = ".json" fileprivate let k_folder_bills = "Bills/" fileprivate let k_file_legislators_home = "legislators_home" fileprivate func modificationDate(folderName: String?, fileName: String, directory: Directory) -> Date? { let filePath = self.filePath(folderName: folderName, fileName: fileName, directory: directory) do { let attr = try fileManager.attributesOfItem(atPath: filePath) return attr[FileAttributeKey.modificationDate] as? Date } catch let error as NSError { print(error.localizedDescription) return nil } } fileprivate func loadJSON(folderName: String?, fileName: String, directory: Directory) -> JSONResult { let filePath = self.filePath(folderName: folderName, fileName: fileName, directory: directory) let fileURL = URL(fileURLWithPath: filePath) guard fileManager.fileExists(atPath: filePath) else { print("error, no file at path") return JSONResult.error(error: StoreError.fileDoesNotExistAtPath) } do { let data = try Data(contentsOf: fileURL) let json = JSON(data: data) return JSONResult.json(json: json) } catch let error as NSError { print(error.localizedDescription) return JSONResult.error(error: error) } } fileprivate func save(json: JSON, folderName: String?, fileName: String, directory: Directory) -> SuccessResult { let filePath = self.filePath(folderName: folderName, fileName: fileName, directory: directory) if let folderName = folderName { let error = self.createDirectoryIfNeeded(folderName: folderName, directory: directory) if let error = error { return SuccessResult.error(error: error) } } if self.fileManager.fileExists(atPath: filePath) { do { try fileManager.removeItem(atPath: filePath) } catch let error as NSError { print(error.localizedDescription) return SuccessResult.error(error: error) } } do { let data = try json.rawData(options: .prettyPrinted) let fileCreated = fileManager.createFile(atPath: filePath, contents: data, attributes: nil) return SuccessResult.success(success: fileCreated) } catch let error as NSError { print(error.localizedDescription) return SuccessResult.error(error: error) } } fileprivate func filePath(folderName: String?, fileName: String, directory: Directory) -> String { var filePath = "" switch (directory) { case .temporary: filePath += NSTemporaryDirectory() case .documents: filePath += DocumentsDirectory() } if let folderName = folderName { filePath += folderName } filePath += fileName + k_dot_json return filePath } fileprivate func directoryPath(folderName: String, directory: Directory) -> String { switch (directory) { case .temporary: return NSTemporaryDirectory() + folderName case .documents: return DocumentsDirectory() + folderName } } fileprivate func createDirectoryIfNeeded(folderName: String, directory: Directory) -> NSError? { let directoryPath = self.directoryPath(folderName: folderName, directory: directory) if self.fileManager.fileExists(atPath: directoryPath) == false { do { try self.fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { print(error.localizedDescription) return error } return nil } else { return nil } } //MARK: Public methods func loadHomeLegislators() -> LegislatorsResult { let result = self.loadJSON(folderName: nil, fileName: k_file_legislators_home, directory: .documents) switch result { case .error(let error): return LegislatorsResult.error(error: error) case .json(let json): let homeLegislators = Legislator.legislatorsWithResults(results: json) return LegislatorsResult.legislators(legislators: homeLegislators) } } func save(homeLegislators: [Legislator]) -> SuccessResult { var jsonArray = [JSON]() for legislator in homeLegislators { jsonArray.append(legislator.json) } let json = JSON(jsonArray) return self.save(json: json, folderName: nil, fileName: k_file_legislators_home, directory: .documents) } func loadBill(bill_id: String) -> BillResult { if let modificationDate = self.modificationDate(folderName: k_folder_bills, fileName: bill_id, directory: .temporary) { if self.gregorian.isDateInToday(modificationDate) == false { print("bill info is older than today") return BillResult.error(error: StoreError.storedFileIsObsolete) } } let result = self.loadJSON(folderName: k_folder_bills, fileName: bill_id, directory: .temporary) switch result { case .error(let error): return BillResult.error(error: error) case .json(let json): let bill = Bill(result: json) print("StoreCoordinator: load bill \(bill.bill_id)") return BillResult.bill(bill: bill) } } func save(bill: Bill) -> SuccessResult { print("StoreCoordinator: save bill \(bill.bill_id)") return self.save(json: bill.json, folderName: k_folder_bills, fileName: bill.bill_id, directory: .temporary) } } fileprivate func DocumentsDirectory() -> String { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) return paths.first! + "/"; }
18ba5818434c39db16f3398668112f77
33.199029
128
0.617317
false
false
false
false
Rapid-SDK/ios
refs/heads/master
Examples/RapiDO - ToDo list/RapiDO iOS/ListViewController.swift
mit
1
// // ListViewController.swift // ExampleApp // // Created by Jan on 05/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import UIKit import Rapid class ListViewController: UIViewController { var searchedTerm = "" var searchTimer: Timer? @IBOutlet weak var tableView: UITableView! @IBOutlet weak var orderButton: UIBarButtonItem! @IBOutlet weak var filterButton: UIBarButtonItem! fileprivate var tasks: [Task] = [] fileprivate var subscription: RapidSubscription? fileprivate var ordering = RapidOrdering(keyPath: Task.createdAttributeName, ordering: .descending) fileprivate var filter: RapidFilter? override func viewDidLoad() { super.viewDidLoad() setupUI() subscribe() } // MARK: Actions @IBAction func addTask(_ sender: Any) { presentNewTaskController() } @objc func showOrderModal(_ sender: Any) { presentOrderModal() } @objc func showFilterModal(_ sender: Any) { presentFilterModal() } } fileprivate extension ListViewController { func setupUI() { navigationController?.navigationBar.prefersLargeTitles = true let searchController = UISearchController(searchResultsController: nil) searchController.delegate = self searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true navigationItem.searchController = searchController navigationItem.title = "Tasks" navigationItem.largeTitleDisplayMode = .always tableView.dataSource = self tableView.delegate = self tableView.separatorColor = .appSeparator tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension orderButton.target = self orderButton.action = #selector(self.showOrderModal(_:)) filterButton.target = self filterButton.action = #selector(self.showFilterModal(_:)) } /// Subscribe to a collection func subscribe() { // If there is a previous subscription then unsubscribe from it subscription?.unsubscribe() tasks.removeAll() tableView.reloadData() // Get Rapid collection reference with a given name var collection = Rapid.collection(named: Constants.collectionName) // If a filter is set, modify the collection reference with it if let filter = filter { // If the search bar text is not empty, filter also by the text if !searchedTerm.isEmpty { // The search bar text can be in a title or in a description // Combine two "CONTAINS" filters with logical "OR" let combinedFilter = RapidFilter.or([ RapidFilter.contains(keyPath: Task.titleAttributeName, subString: searchedTerm), RapidFilter.contains(keyPath: Task.descriptionAttributeName, subString: searchedTerm) ]) // And then, combine the search bar text filter with a filter from the filter modal collection.filtered(by: RapidFilter.and([filter, combinedFilter])) } else { // Associate the collection reference with the filter collection.filtered(by: filter) } } // If the searchBar text is not empty, filter by the text else if !searchedTerm.isEmpty { let combinedFilter = RapidFilter.or([ RapidFilter.contains(keyPath: Task.titleAttributeName, subString: searchedTerm), RapidFilter.contains(keyPath: Task.descriptionAttributeName, subString: searchedTerm) ]) collection.filtered(by: combinedFilter) } // Order the collection by a given ordering // Subscribe to the collection // Store a subscribtion reference to be able to unsubscribe from it subscription = collection.order(by: ordering).subscribeWithChanges { result in switch result { case .success(let changes): let (documents, insert, update, delete) = changes let previousSet = self.tasks self.tasks = documents.flatMap({ Task(withSnapshot: $0) }) self.tableView.animateChanges(previousData: previousSet, data: self.tasks, new: insert, updated: update, deleted: delete) case .failure: self.tasks = [] self.tableView.reloadData() } } } func presentNewTaskController() { let controller = self.storyboard!.instantiateViewController(withIdentifier: "TaskNavigationViewController") present(controller, animated: true, completion: nil) } func presentOrderModal() { let controller = self.storyboard?.instantiateViewController(withIdentifier: "OrderViewController") as! OrderViewController controller.delegate = self controller.ordering = ordering controller.modalPresentationStyle = .custom controller.modalTransitionStyle = .crossDissolve present(controller, animated: true, completion: nil) } func presentFilterModal() { let controller = self.storyboard?.instantiateViewController(withIdentifier: "FilterViewController") as! FilterViewController controller.delegate = self controller.filter = filter controller.modalPresentationStyle = .custom controller.modalTransitionStyle = .crossDissolve present(controller, animated: true, completion: nil) } func presentEditTask(_ task: Task) { let controller = self.storyboard?.instantiateViewController(withIdentifier: "TaskViewController") as! TaskViewController controller.task = task navigationController?.pushViewController(controller, animated: true) } } // MARK: Table view extension ListViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tasks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell let task = tasks[indexPath.row] cell.configure(withTask: task, delegate: self) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let task = tasks[indexPath.row] presentEditTask(task) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let action = UIContextualAction(style: .destructive, title: "Delete") { (_, _, completion) in let task = self.tasks[indexPath.row] task.delete() } action.backgroundColor = .appRed return UISwipeActionsConfiguration(actions: [action]) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let task = tasks[indexPath.row] task.delete() } } } extension ListViewController: TaskCellDelegate { func cellCheckmarkChanged(_ cell: TaskCell, value: Bool) { if let indexPath = tableView.indexPath(for: cell) { let task = tasks[indexPath.row] task.updateCompleted(value) } } } // MARK: Search bar delegate extension ListViewController: UISearchControllerDelegate, UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { guard searchedTerm != (searchController.searchBar.text ?? "") else { return } searchedTerm = searchController.searchBar.text ?? "" searchTimer?.invalidate() searchTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] _ in self?.subscribe() } } } // MARK: Ordering delegate extension ListViewController: OrderViewControllerDelegate { func orderViewControllerDidCancel(_ controller: OrderViewController) { controller.dismiss(animated: true, completion: nil) } func orderViewControllerDidFinish(_ controller: OrderViewController, withOrdering ordering: RapidOrdering) { self.ordering = ordering subscribe() controller.dismiss(animated: true, completion: nil) } } // MARK: Filter delegate extension ListViewController: FilterViewControllerDelegate { func filterViewControllerDidCancel(_ controller: FilterViewController) { controller.dismiss(animated: true, completion: nil) } func filterViewControllerDidFinish(_ controller: FilterViewController, withFilter filter: RapidFilter?) { self.filter = filter subscribe() controller.dismiss(animated: true, completion: nil) } }
b337f26192b1a8ab960eb130b1e98cef
34.711679
142
0.646602
false
false
false
false
okerivy/AlgorithmLeetCode
refs/heads/master
AlgorithmLeetCode/AlgorithmLeetCode/H_84_LargestRectangleinHistogram.swift
mit
1
// // H_84_LargestRectangleinHistogram.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/8. // Copyright © 2017年 okerivy. All rights reserved. // https://leetcode.com/problems/largest-rectangle-in-histogram import Foundation // MARK: - 题目名称: 84. Largest Rectangle in Histogram /* MARK: - 所属类别: 标签: Array, Stack 相关题目: (H) Maximal Rectangle */ /* MARK: - 题目英文: Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. The largest rectangle is shown in the shaded area, which has area = 10 unit. For example, Given heights = [2,1,5,6,2,3], return 10. */ /* MARK: - 题目翻译: */ /* MARK: - 解题思路: (1) 在height尾部添加一个0,也就是一个高度为0的立柱。作用是在最后也能凑成上面提的那种“波峰图”。 (2) 定义了一个stack,然后遍历时如果height[i] 大于stack.top(),进栈。反之,出栈直到栈顶元素小于height[i]。 由于出栈的这些元素高度都是递增的,我们可以求出这些立柱中所围成的最大矩形。更妙的是,由于这些被弹出的立柱处于“波峰”之上(比如弹出i 到 i+k,那么所有这些立柱的高度都高于 i-1和 i+k+1的高度),因此,如果我们使用之前所提的“左右延伸找立柱”的思路解,以这些立柱的高度作为整个矩形的高度时,左右延伸出的矩形所包含的立柱不会超出这段“波峰”,因为波峰外的立柱高度都比他们低。“波峰图”其实就是求解最大矩形的“孤岛”,它不会干扰到外部。 (3) 由于比height[i]大的元素都出完了,height[i]又比栈顶元素大了,因此再次进栈。如此往复,直到遍历到最后那个高度为0的柱,触发最后的弹出以及最后一次面积的计算,此后stack为空。 (4) 返回面积最大值。 栈中存的不是高度,而是height的索引,这样做的好处是不会影响宽度的计算,索引值相减 = 宽度。 自己实现代码如下,虽然是二重循环,但时间复杂度实际 2N,故为O(N) (1) stack里存的是index,计算面积时的宽度使用 index的差值,所以虽然stack 弹出了立柱,但是不影响宽度的计算,依然可以计算面积。 (2) 这种解法本质上是查看以每一个立柱为矩形高度,求出最大面积,但是它通过入栈出栈,把整个height变成一组组“波峰图”来解,这种高度布局下,最大面积的计算是O(n)的,然后将所有波峰图的最大面积取最大值。最后做到了以O(n)的时间复杂度覆盖了所有的立柱。 */ // FIXME: 没有完成 /* MARK: - 复杂度分析: */ // MARK: - 代码: private class Solution { func largestRectangleArea(_ heights: [Int]) -> Int { var stack:[Int] = [] var maxArea = 0 // 这个标记很重要, 用来指示 小于 (栈低的下标 对应的元素) 的下标 var i = 0 // 需要遍历完全 // 修正错误 以前少遍历一次 while i < heights.count { // 如果当前栈为空, 那么就把 当前元素的下标 压入栈底 // 如果 当前i对应的元素 大于 当前栈顶的数据(下标) 所对应的元素 那么就把 i 压入栈中 // 直到找到 小于的值 if stack.isEmpty || heights[i] >= heights[stack.last!] { // 压入栈中 stack.append(i) // 继续向后寻找 i += 1 } else { print(stack) // 如果 当前栈顶对应的元素 大于 当前i对应的元素, 那么就可以计算面积了 let topStact = stack.last! // 把栈顶的数据从栈中去除 stack.removeLast() // 1, 首先计算的是 栈顶的元素的面积 // 面积的计算 是当前被pop出来的元素的高度 * (i 与 当前栈顶的数据(下标) 中间的差距) // 如果 栈为空, 那么 这个间距 就是 i let areaWithTop = heights[topStact] * (stack.isEmpty ? i : (i - stack.last! - 1)) // 2, 和当前最大值比较 获取最大值 maxArea = max(areaWithTop, maxArea) print(maxArea) // 3, 如果 栈中还有元素, 一旦 if判断不成立 那么下次还会来到这里 // 需要注意的是 这里 i 并没有++ // 这个很重要, 这保证了栈中数据(下标)对应的元素 是从 小向大的 是有顺序的 } } // 遍历完成后, 栈中可能还有数据, 然后依次出栈 计算面积 while stack.isEmpty == false { print(stack) let topStact = stack.last! stack.removeLast() let areaWithTop = heights[topStact] * (stack.isEmpty ? i : (i - stack.last! - 1)) maxArea = max(maxArea, areaWithTop) print(maxArea) } return maxArea } } // MARK: - 测试代码: func largestRectangleinHistogram() { var nums1 = [Int]() nums1 = [3, 1, 3, 2, 2]//[2,1,5,6,2,3] print(Solution().largestRectangleArea(nums1)) print(nums1) }
5f9dfa34ee9726a154bdd208f8a253d0
23.084416
222
0.575896
false
false
false
false
motoom/ios-apps
refs/heads/master
Pour/Pour/String+extents.swift
mit
1
import UIKit extension String { func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: CGFloat.max) let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return boundingBox.height } } extension NSAttributedString { func heightWithConstrainedWidth(width: CGFloat) -> CGFloat { let constraintRect = CGSize(width: width, height: CGFloat.max) let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil) return ceil(boundingBox.height) } func widthWithConstrainedHeight(height: CGFloat) -> CGFloat { let constraintRect = CGSize(width: CGFloat.max, height: height) let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil) return ceil(boundingBox.width) } }
35797e5d6afa9f19eea27cac81b4b770
41.423077
178
0.731641
false
false
false
false
dtweston/Tribute
refs/heads/master
Pod/Classes/MarkdownLayoutManagerDelegate.swift
mit
1
// // MarkdownLayoutManagerDelegate.swift // Pods // // Created by Dave Weston on 3/27/15. // // #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif public class MarkdownLayoutManagerDelegate: NSObject, NSLayoutManagerDelegate { public func layoutManager(layoutManager: NSLayoutManager, paragraphSpacingBeforeGlyphAtIndex glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat { let charIndex = layoutManager.characterIndexForGlyphAtIndex(glyphIndex) if let storage = layoutManager.textStorage { if storage.length > charIndex { if let isCodeBlockStart = storage.attribute(CodeBlockStartAttributeName, atIndex: charIndex, effectiveRange: nil) as! Bool? { if isCodeBlockStart { return 15.0 } } } } return 0.0 } public func layoutManager(layoutManager: NSLayoutManager, lineSpacingAfterGlyphAtIndex glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat { let charIndex = layoutManager.characterIndexForGlyphAtIndex(glyphIndex) let val: AnyObject? = layoutManager.textStorage?.attribute(CodeBlockEndAttributeName, atIndex: charIndex, effectiveRange: nil) if let isCodeBlockStart = val as! Bool? { if isCodeBlockStart { return 15.0 } } return 0.0 } }
cc335ced0bb0205c5a6177e2d0e119f6
32.795455
169
0.64425
false
false
false
false
typarker/LotLizard
refs/heads/LotLizard
KitchenSink/ExampleFiles/ViewControllers/BuySpotViewController.swift
mit
1
// // BuySpotViewController.swift // DrawerControllerKitchenSink // // Created by Ty Parker on 1/15/15. // Copyright (c) 2015 evolved.io. All rights reserved. // import UIKit import MapKit class BuySpotViewController: UIViewController, MKMapViewDelegate { var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() self.title = "Reserve a Spot" self.mapView = MKMapView() // 1 let location = CLLocationCoordinate2D( latitude: 29.6520, longitude: -82.35 ) // 2 let span = MKCoordinateSpanMake(0.025, 0.025) let region = MKCoordinateRegion(center: location, span: span) self.mapView.setRegion(region, animated: true) self.mapView.mapType = .Standard self.mapView.frame = view.frame self.mapView.delegate = self self.view.addSubview(self.mapView) let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTap:") doubleTap.numberOfTapsRequired = 2 self.view.addGestureRecognizer(doubleTap) let twoFingerDoubleTap = UITapGestureRecognizer(target: self, action: "twoFingerDoubleTap:") twoFingerDoubleTap.numberOfTapsRequired = 2 twoFingerDoubleTap.numberOfTouchesRequired = 2 self.view.addGestureRecognizer(twoFingerDoubleTap) self.setupLeftMenuButton() //self.setupRightMenuButton() let barColor = UIColor(red: 247/255, green: 249/255, blue: 250/255, alpha: 1.0) self.navigationController?.navigationBar.barTintColor = barColor self.navigationController?.view.layer.cornerRadius = 10.0 let backView = UIView() backView.backgroundColor = UIColor(red: 208/255, green: 208/255, blue: 208/255, alpha: 1.0) //self.tableView.backgroundView = backView populateMap() } func populateMap(){ self.mapView.removeAnnotations(mapView.annotations) // 1 //let lots = Lot.allObjectsInRealm(realm) //var lotWithSpot = lots.objectsWhere("spots > 0") var query = PFQuery(className:"MyLotParse") query.whereKey("spots", greaterThan: 0) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in if error == nil { // The find succeeded. NSLog("Successfully retrieved \(objects.count) spots.") // Do something with the found objects for object in objects { NSLog("%@", object.objectId) let location = object ["location"] as PFGeoPoint let latitude = location.latitude as Double let longitude = location.longitude as Double let price = object["price"] as String let owner = object["owner"] as PFUser? let coord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let id = object.objectId let notes = object["notes"] as String? let spots = object["spots"] as Int let lotAnnotation = LotAnnotation(coordinate: coord, title: price, subtitle: "Dollars", id: id, owner: owner!, notes: notes, spots: spots) // 3 self.mapView.addAnnotation(lotAnnotation) // 4 } } else { // Log details of the failure NSLog("Error: %@ %@", error, error.userInfo!) } } } func mapView(_mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { let reuseId = "test" let button : UIButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as UIButton var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) if anView == nil { anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) anView.image = UIImage(named:"redPin.png") anView.canShowCallout = true anView.rightCalloutAccessoryView = button button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside) } else { //we are re-using a view, update its annotation reference... anView.annotation = annotation } return anView } func buttonClicked(sender: UIButton!) { let ann = self.mapView.selectedAnnotations[0] as LotAnnotation let secondViewController: PurchaseSpotViewController = PurchaseSpotViewController(nibName:"PurchaseSpot", bundle: nil) secondViewController.latitude = ann.coordinate.latitude secondViewController.longitude = ann.coordinate.longitude secondViewController.ann = ann //let secondViewController: BuySpotViewController = BuySpotViewController() self.presentViewController(secondViewController, animated: true, completion: nil) //performSegueWithIdentifier("goToAddLot", sender: sender) } func setupLeftMenuButton() { let leftDrawerButton = DrawerBarButtonItem(target: self, action: "leftDrawerButtonPress:") self.navigationItem.setLeftBarButtonItem(leftDrawerButton, animated: true) } func setupRightMenuButton() { let rightDrawerButton = DrawerBarButtonItem(target: self, action: "rightDrawerButtonPress:") self.navigationItem.setRightBarButtonItem(rightDrawerButton, animated: true) } func leftDrawerButtonPress(sender: AnyObject?) { self.evo_drawerController?.toggleDrawerSide(.Left, animated: true, completion: nil) } func rightDrawerButtonPress(sender: AnyObject?) { self.evo_drawerController?.toggleDrawerSide(.Right, animated: true, completion: nil) } func doubleTap(gesture: UITapGestureRecognizer) { self.evo_drawerController?.bouncePreviewForDrawerSide(.Left, completion: nil) } func twoFingerDoubleTap(gesture: UITapGestureRecognizer) { self.evo_drawerController?.bouncePreviewForDrawerSide(.Right, completion: nil) } }
59876ec0948ab9251a3095551882a528
35.438202
163
0.614863
false
false
false
false
MKGitHub/UIPheonix
refs/heads/master
Demo/macOS/DemoCollectionViewController.swift
apache-2.0
1
/** UIPheonix Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved. https://github.com/MKGitHub/UIPheonix http://www.xybernic.com Copyright 2016/2017/2018/2019 Mohsan Khan 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 Cocoa final class DemoCollectionViewController:UIPBaseViewController, UIPButtonDelegate, NSCollectionViewDataSource, NSCollectionViewDelegateFlowLayout { // MARK: Public Inner Struct struct AttributeKeyName { static let appDisplayState = "AppDisplayState" } // MARK: Public IB Outlet @IBOutlet private weak var ibCollectionView:NSCollectionView! // MARK: Private Members private var mAppDisplayStateType:AppDisplayStateType! private var mUIPheonix:UIPheonix! // (for demo purpose only) private var mPersistentDisplayModels:Array<UIPBaseCellModelProtocol>? // MARK:- Life Cycle override func viewDidLoad() { super.viewDidLoad() // init member mAppDisplayStateType = (newInstanceAttributes[AttributeKeyName.appDisplayState] as! AppDisplayState).value initUIPheonix() setupCollectionView() updateView() } // MARK:- NSCollectionViewDataSource func collectionView(_ collectionView:NSCollectionView, numberOfItemsInSection section:Int) -> Int { return mUIPheonix.displayModelsCount(forSection:0) } func collectionView(_ collectionView:NSCollectionView, itemForRepresentedObjectAt indexPath:IndexPath) -> NSCollectionViewItem { return mUIPheonix.collectionViewItem(forIndexPath:indexPath) } // MARK:- NSCollectionViewDelegate func collectionView(_ collectionView:NSCollectionView, layout collectionViewLayout:NSCollectionViewLayout, insetForSectionAt section:Int) -> NSEdgeInsets { return NSEdgeInsets(top:10, left:0, bottom:0, right:0) } func collectionView(_ collectionView:NSCollectionView, layout collectionViewLayout:NSCollectionViewLayout, minimumLineSpacingForSectionAt section:Int) -> CGFloat { return 10 } func collectionView(_ collectionView:NSCollectionView, layout collectionViewLayout:NSCollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { return mUIPheonix.collectionViewItemSize(forIndexPath:indexPath) } // MARK:- UIPButtonDelegate func handleAction(forButtonId buttonId:Int) { var isTheAppendModelsDemo = false var isThePersistentModelsDemo = false var isTheCustomMadeModelsDemo = false var shouldAnimateChange = true // set the display state depending on which button we clicked switch (buttonId) { case ButtonId.startUp.rawValue: mAppDisplayStateType = AppDisplayState.startUp.value; break case ButtonId.mixed.rawValue: mAppDisplayStateType = AppDisplayState.mixed.value; break case ButtonId.animations.rawValue: mAppDisplayStateType = AppDisplayState.animations.value; break case ButtonId.switching.rawValue: mAppDisplayStateType = AppDisplayState.switching.value; break case ButtonId.appending.rawValue: mAppDisplayStateType = AppDisplayState.appending.value; break case ButtonId.appendingReload.rawValue: mAppDisplayStateType = AppDisplayState.appending.value isTheAppendModelsDemo = true shouldAnimateChange = false break case ButtonId.persistent.rawValue: mAppDisplayStateType = AppDisplayState.persistent.value isThePersistentModelsDemo = true break case ButtonId.persistentGoBack.rawValue: mAppDisplayStateType = AppDisplayState.startUp.value // when we leave the state, store the current display models for later reuse // so that when we re-enter the state, we can just use them as they were mPersistentDisplayModels = mUIPheonix.displayModels(forSection:0) break case ButtonId.specific.rawValue: mAppDisplayStateType = AppDisplayState.specific.value; break case ButtonId.customMadeModels.rawValue: mAppDisplayStateType = AppDisplayState.customMadeModels.value; isTheCustomMadeModelsDemo = true break default: mAppDisplayStateType = AppDisplayState.startUp.value; break } // update UI if (shouldAnimateChange) { animateView(animationState:false, completionHandler: { [weak self] in guard let self = self else { fatalError("DemoCollectionViewController buttonAction: `self` does not exist anymore!") } self.updateView(isTheAppendModelsDemo:isTheAppendModelsDemo, isThePersistentDemo:isThePersistentModelsDemo, isTheCustomMadeModelsDemo:isTheCustomMadeModelsDemo) self.animateView(animationState:true, completionHandler:nil) }) } else { updateView(isTheAppendModelsDemo:isTheAppendModelsDemo, isThePersistentDemo:isThePersistentModelsDemo, isTheCustomMadeModelsDemo:isTheCustomMadeModelsDemo) } } // MARK:- Private private func initUIPheonix() { mUIPheonix = UIPheonix(collectionView:ibCollectionView, delegate:self) } private func setupCollectionView() { ibCollectionView.delegate = self ibCollectionView.dataSource = self } private func setupWithJSON() { if let jsonDictionary = DataProvider.loadJSON(inFilePath:mAppDisplayStateType.jsonFileName.rawValue) { mUIPheonix.setModelViewRelationships(withDictionary:jsonDictionary[UIPConstants.Collection.modelViewRelationships] as! Dictionary<String, String>) mUIPheonix.setDisplayModels(jsonDictionary[UIPConstants.Collection.cellModels] as! Array<Any>, forSection:0, append:false) } else { fatalError("DemoCollectionViewController setupWithJSON: Failed to init with JSON file!") } } private func setupWithModels() { mUIPheonix.setModelViewRelationships(withDictionary:[SimpleButtonModel.nameOfClass:SimpleButtonModelCVCell.nameOfClass, SimpleCounterModel.nameOfClass:SimpleCounterModelCVCell.nameOfClass, SimpleLabelModel.nameOfClass:SimpleLabelModelCVCell.nameOfClass, SimpleTextFieldModel.nameOfClass:SimpleTextFieldModelCVCell.nameOfClass, SimpleVerticalSpaceModel.nameOfClass:SimpleVerticalSpaceModelCVCell.nameOfClass, SimpleViewAnimationModel.nameOfClass:SimpleViewAnimationModelCVCell.nameOfClass]) var models = [UIPBaseCellModel]() for i in 1 ... 20 { let simpleLabelModel:SimpleLabelModel = SimpleLabelModel(text:" Label \(i)", size:(12.0 + CGFloat(i) * 2.0), alignment:SimpleLabelModel.Alignment.left, style:SimpleLabelModel.Style.regular, backgroundColorHue:(CGFloat(i) * 0.05), notificationId:"") models.append(simpleLabelModel) } let simpleButtonModel = SimpleButtonModel(id:ButtonId.startUp.rawValue, title:"Enough with the RAINBOW!", alignment:SimpleButtonModel.Alignment.center) models.append(simpleButtonModel) mUIPheonix.setDisplayModels(models, forSection:0) } private func updateView(isTheAppendModelsDemo:Bool=false, isThePersistentDemo:Bool=false, isTheCustomMadeModelsDemo:Bool=false) { if (isTheAppendModelsDemo) { // append the current display models list to itself mUIPheonix.addDisplayModels(mUIPheonix.displayModels(forSection:0), inSection:0) } else if (isThePersistentDemo) { if (mPersistentDisplayModels == nil) { setupWithJSON() } else { // set the persistent display models mUIPheonix!.setDisplayModels(mPersistentDisplayModels!, forSection:0) } } else if (isTheCustomMadeModelsDemo) { setupWithModels() } else { setupWithJSON() } // reload the collection view ibCollectionView.reloadData() } private func animateView(animationState:Bool, completionHandler:(()->Void)?) { // do a nice fading animation NSAnimationContext.runAnimationGroup( { [weak self] (context:NSAnimationContext) in guard let self = self else { fatalError("DemoCollectionViewController animateView: `self` does not exist anymore!") } context.duration = 0.25 self.view.animator().alphaValue = animationState ? 1.0 : 0.0 }, completionHandler:completionHandler) } }
c0d7dba630d2cbe7ba07323d84950af2
35.435714
165
0.634483
false
false
false
false
vector-im/vector-ios
refs/heads/master
Riot/Modules/Room/EmojiPicker/EmojiPickerViewController.swift
apache-2.0
1
// File created from ScreenTemplate // $ createScreen.sh toto EmojiPicker /* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import Reusable final class EmojiPickerViewController: UIViewController { // MARK: - Constants private enum CollectionViewLayout { static let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) static let minimumInteritemSpacing: CGFloat = 6.0 static let minimumLineSpacing: CGFloat = 2.0 static let itemSize = CGSize(width: 50, height: 50) } private static let sizingHeaderView = EmojiPickerHeaderView.loadFromNib() // MARK: - Properties // MARK: Outlets @IBOutlet private weak var collectionView: UICollectionView! // MARK: Private private var viewModel: EmojiPickerViewModelType! private var theme: Theme! private var keyboardAvoider: KeyboardAvoider? private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var searchController: UISearchController? private var emojiCategories: [EmojiPickerCategoryViewData] = [] // MARK: - Setup class func instantiate(with viewModel: EmojiPickerViewModelType) -> EmojiPickerViewController { let viewController = StoryboardScene.EmojiPickerViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = VectorL10n.emojiPickerTitle self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.collectionView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.keyboardAvoider?.startAvoiding() // Update theme here otherwise the UISearchBar search text color is not updated self.update(theme: self.theme) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Enable to hide search bar on scrolling after first time view appear // Commenting out below code for now. It broke the navigation bar background. For details: https://github.com/vector-im/riot-ios/issues/3271 // self.navigationItem.hidesSearchBarWhenScrolling = true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.keyboardAvoider?.stopAvoiding() } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.backgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } if let searchController = self.searchController { theme.applyStyle(onSearchBar: searchController.searchBar) } } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.navigationItem.rightBarButtonItem = cancelBarButtonItem self.setupCollectionView() self.setupSearchController() } private func setupCollectionView() { self.collectionView.delegate = self self.collectionView.dataSource = self self.collectionView.keyboardDismissMode = .interactive if let collectionViewFlowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout { collectionViewFlowLayout.minimumInteritemSpacing = CollectionViewLayout.minimumInteritemSpacing collectionViewFlowLayout.minimumLineSpacing = CollectionViewLayout.minimumLineSpacing collectionViewFlowLayout.itemSize = CollectionViewLayout.itemSize collectionViewFlowLayout.sectionInset = CollectionViewLayout.sectionInsets collectionViewFlowLayout.sectionHeadersPinToVisibleBounds = true // Enable sticky headers // Avoid device notch in landscape (e.g. iPhone X) collectionViewFlowLayout.sectionInsetReference = .fromSafeArea } self.collectionView.register(supplementaryViewType: EmojiPickerHeaderView.self, ofKind: UICollectionView.elementKindSectionHeader) self.collectionView.register(cellType: EmojiPickerViewCell.self) } private func setupSearchController() { let searchController = UISearchController(searchResultsController: nil) searchController.obscuresBackgroundDuringPresentation = false searchController.searchResultsUpdater = self searchController.searchBar.placeholder = VectorL10n.searchDefaultPlaceholder searchController.hidesNavigationBarDuringPresentation = false self.navigationItem.searchController = searchController // Make the search bar visible on first view appearance self.navigationItem.hidesSearchBarWhenScrolling = false self.definesPresentationContext = true self.searchController = searchController } private func render(viewState: EmojiPickerViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(emojiCategories: let emojiCategories): self.renderLoaded(emojiCategories: emojiCategories) case .error(let error): self.render(error: error) } } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded(emojiCategories: [EmojiPickerCategoryViewData]) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.update(emojiCategories: emojiCategories) } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } private func update(emojiCategories: [EmojiPickerCategoryViewData]) { self.emojiCategories = emojiCategories self.collectionView.reloadData() } private func emojiItemViewData(at indexPath: IndexPath) -> EmojiPickerItemViewData { return self.emojiCategories[indexPath.section].emojiViewDataList[indexPath.row] } private func emojiCategoryViewData(at section: Int) -> EmojiPickerCategoryViewData? { return self.emojiCategories[section] } private func headerViewSize(for title: String) -> CGSize { let sizingHeaderView = EmojiPickerViewController.sizingHeaderView sizingHeaderView.fill(with: title) sizingHeaderView.setNeedsLayout() sizingHeaderView.layoutIfNeeded() var fittingSize = UIView.layoutFittingCompressedSize fittingSize.width = self.collectionView.bounds.size.width return sizingHeaderView.systemLayoutSizeFitting(fittingSize) } // MARK: - Actions private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } } // MARK: - UICollectionViewDataSource extension EmojiPickerViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return self.emojiCategories.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.emojiCategories[section].emojiViewDataList.count } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let emojiPickerCategory = self.emojiCategories[indexPath.section] let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, for: indexPath) as EmojiPickerHeaderView headerView.update(theme: self.theme) headerView.fill(with: emojiPickerCategory.name) return headerView } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: EmojiPickerViewCell = collectionView.dequeueReusableCell(for: indexPath) if let theme = self.theme { cell.update(theme: theme) } let viewData = self.emojiItemViewData(at: indexPath) cell.fill(viewData: viewData) return cell } } // MARK: - UICollectionViewDelegate extension EmojiPickerViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let emojiItemViewData = self.emojiItemViewData(at: indexPath) self.viewModel.process(viewAction: .tap(emojiItemViewData: emojiItemViewData)) } func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) { // Fix UICollectionView scroll bar appears underneath header view view.layer.zPosition = 0.0 } } // MARK: - UICollectionViewDelegateFlowLayout extension EmojiPickerViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { let emojiCategory = self.emojiCategories[section] let headerSize = self.headerViewSize(for: emojiCategory.name) return headerSize } } // MARK: - EmojiPickerViewModelViewDelegate extension EmojiPickerViewController: EmojiPickerViewModelViewDelegate { func emojiPickerViewModel(_ viewModel: EmojiPickerViewModelType, didUpdateViewState viewSate: EmojiPickerViewState) { self.render(viewState: viewSate) } } // MARK: - UISearchResultsUpdating extension EmojiPickerViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { let searchText = searchController.searchBar.text self.viewModel.process(viewAction: .search(text: searchText)) } }
31f43d247973aae34c9ad81489bebbef
37.551282
183
0.708513
false
false
false
false
yanif/circator
refs/heads/master
MetabolicCompass/View/BaseControls/FontScaleLabel.swift
apache-2.0
1
// // FontScaleLabel.swift // MetabolicCompass // // Created by Vladimir on 5/25/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import Foundation import UIKit public class FontScaleLabel: UILabel { private var notScaledFont:UIFont? = nil public static var scaleFactor: CGFloat = 1.0 // required public init(coder aDecoder: NSCoder) { // super.init(coder: aDecoder)! // self.commonInit() // } // // override init(frame: CGRect) { // super.init(frame: frame) // self.commonInit() // } // // func commonInit(){ // // } override public func awakeFromNib() { super.awakeFromNib() if self.notScaledFont == nil { self.notScaledFont = self.font; self.font = self.notScaledFont; } } override public var font: UIFont!{ get { return super.font } set { self.notScaledFont = newValue; if newValue != nil{ let scaledFont = newValue!.fontWithSize(newValue!.pointSize * FontScaleLabel.scaleFactor) super.font = scaledFont } } } }
2078eeeb69e5f1f2c2dd4a3427b8d4dc
21.807692
105
0.569983
false
false
false
false
AssistoLab/FloatingLabel
refs/heads/master
FloatingLabel/src/input/FloatingFieldTextView.swift
mit
2
// // FloatingFieldTextView.swift // FloatingLabel // // Created by Kevin Hirsch on 5/08/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit import SZTextView public class FloatingFieldTextView: SZTextView { //MARK: - Init's init() { super.init(frame: CGRectZero, textContainer: nil) listenToTextView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) listenToTextView() } deinit { stopListeningToTextView() } //MARK: - Properties private var shouldUpdateSizeIfNeeded = true } //MARK: - UIView public extension FloatingFieldTextView { override func layoutSubviews() { super.layoutSubviews() if shouldUpdateSizeIfNeeded && bounds.size != intrinsicContentSize() { invalidateIntrinsicContentSize() parentCollectionView()?.collectionViewLayout.invalidateLayout() } } override func intrinsicContentSize() -> CGSize { #if TARGET_INTERFACE_BUILDER return CGSize(width: UIViewNoIntrinsicMetric, height: 24) #else return contentSize #endif } } //MARK: - Listeners extension FloatingFieldTextView { private func listenToTextView() { NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(textViewTextDidBeginEditingNotification), name: UITextViewTextDidBeginEditingNotification, object: self) NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(textViewTextDidChangeNotification), name: UITextViewTextDidChangeNotification, object: self) NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(textViewTextDidEndEditingNotification), name: UITextViewTextDidEndEditingNotification, object: self) self.addObserver(self, forKeyPath: "text", options: .New, context: &textKVOContext) } func stopListeningToTextView() { NSNotificationCenter.defaultCenter().removeObserver( self, name: UITextViewTextDidBeginEditingNotification, object: self) NSNotificationCenter.defaultCenter().removeObserver( self, name: UITextViewTextDidChangeNotification, object: self) NSNotificationCenter.defaultCenter().removeObserver( self, name: UITextViewTextDidEndEditingNotification, object: self) self.removeObserver(self, forKeyPath: "text", context: &textKVOContext) } @objc func textViewTextDidEndEditingNotification() { shouldUpdateSizeIfNeeded = false parentCollectionView()?.collectionViewLayout.invalidateLayout() } @objc func textViewTextDidBeginEditingNotification() { shouldUpdateSizeIfNeeded = true } @objc func textViewTextDidChangeNotification() { shouldUpdateSizeIfNeeded = true parentCollectionView()?.collectionViewLayout.invalidateLayout() } } //MARK: - KVO private var textKVOContext = 0 extension FloatingFieldTextView { override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &textKVOContext && (change?[NSKeyValueChangeNewKey] as? String) != nil { parentCollectionView()?.collectionViewLayout.invalidateLayout() } super.observeValueForKeyPath(keyPath!, ofObject: object!, change: change!, context: context) } }
0dbf8a713e21dae3c1bab816918501df
22.553957
161
0.754659
false
false
false
false
arvedviehweger/swift
refs/heads/master
test/expr/unary/keypath/keypath.swift
apache-2.0
1
// RUN: %target-swift-frontend -typecheck -parse-as-library -enable-experimental-keypaths %s -verify struct Sub {} struct OptSub {} struct Prop { subscript(sub: Sub) -> A { get { return A() } set { } } subscript(optSub: OptSub) -> A? { get { return A() } set { } } var nonMutatingProperty: B { get { fatalError() } nonmutating set { fatalError() } } } struct A: Hashable { init() { fatalError() } var property: Prop var optProperty: Prop? subscript(sub: Sub) -> A { get { return self } set { } } static func ==(_: A, _: A) -> Bool { fatalError() } var hashValue: Int { fatalError() } } struct B {} struct C<T> { var value: T subscript(sub: Sub) -> T { get { return value } set { } } subscript<U>(sub: U) -> U { get { return sub } set { } } } extension Array where Element == A { var property: Prop { fatalError() } } struct Exactly<T> {} func expect<T>(_ x: inout T, toHaveType _: Exactly<T>.Type) {} func testKeyPath(sub: Sub, optSub: OptSub, x: Int) { var a = #keyPath2(A, .property) expect(&a, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var b = #keyPath2(A, [sub]) expect(&b, toHaveType: Exactly<WritableKeyPath<A, A>>.self) var c = #keyPath2(A, [sub].property) expect(&c, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var d = #keyPath2(A, .optProperty?) expect(&d, toHaveType: Exactly<KeyPath<A, Prop?>>.self) var e = #keyPath2(A, .optProperty?[sub]) expect(&e, toHaveType: Exactly<KeyPath<A, A?>>.self) var f = #keyPath2(A, .optProperty!) expect(&f, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var g = #keyPath2(A, .property[optSub]?.optProperty![sub]) expect(&g, toHaveType: Exactly<KeyPath<A, A?>>.self) var h = #keyPath2([A], .property) expect(&h, toHaveType: Exactly<KeyPath<[A], Prop>>.self) var i = #keyPath2([A], .property.nonMutatingProperty) expect(&i, toHaveType: Exactly<ReferenceWritableKeyPath<[A], B>>.self) var j = #keyPath2([A], [x]) expect(&j, toHaveType: Exactly<WritableKeyPath<[A], A>>.self) var k = #keyPath2([A: B], [A()]) expect(&k, toHaveType: Exactly<WritableKeyPath<[A: B], B?>>.self) var l = #keyPath2(C<A>, .value) expect(&l, toHaveType: Exactly<WritableKeyPath<C<A>, A>>.self) // expected-error@+1{{generic parameter 'T' could not be inferred}} _ = #keyPath2(C, .value) // expected-error@+1{{}} _ = #keyPath2(() -> (), .noMember) // FIXME crash let _: PartialKeyPath<A> = #keyPath2(.property) let _: KeyPath<A, Prop> = #keyPath2(.property) let _: WritableKeyPath<A, Prop> = #keyPath2(.property) // expected-error@+1{{ambiguous}} (need to improve diagnostic) let _: ReferenceWritableKeyPath<A, Prop> = #keyPath2(.property) // FIXME crash let _: PartialKeyPath<A> = #keyPath2([sub]) // FIXME should resolve: expected-error@+1{{}} let _: KeyPath<A, A> = #keyPath2([sub]) // FIXME should resolve: expected-error@+1{{}} let _: WritableKeyPath<A, A> = #keyPath2([sub]) // expected-error@+1{{ambiguous}} (need to improve diagnostic) let _: ReferenceWritableKeyPath<A, A> = #keyPath2([sub]) // FIXME crash let _: PartialKeyPath<A> = #keyPath2(.optProperty?) let _: KeyPath<A, Prop?> = #keyPath2(.optProperty?) // expected-error@+1{{cannot convert}} let _: WritableKeyPath<A, Prop?> = #keyPath2(.optProperty?) // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<A, Prop?> = #keyPath2(.optProperty?) // FIXME crash let _: PartialKeyPath<A> = #keyPath2(.optProperty?[sub]) let _: KeyPath<A, A?> = #keyPath2(.optProperty?[sub]) // expected-error@+1{{cannot convert}} let _: WritableKeyPath<A, A?> = #keyPath2(.optProperty?[sub]) // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<A, A?> = #keyPath2(.optProperty?[sub]) // FIXME should resolve: expected-error@+1{{}} let _: KeyPath<A, Prop> = #keyPath2(.optProperty!) // FIXME should resolve: expected-error@+1{{}} let _: KeyPath<A, Prop?> = #keyPath2(.property[optSub]?.optProperty![sub]) // FIXME crash let _: PartialKeyPath<C<A>> = #keyPath2(.value) let _: KeyPath<C<A>, A> = #keyPath2(.value) let _: WritableKeyPath<C<A>, A> = #keyPath2(.value) // expected-error@+1{{ambiguous}} (need to improve diagnostic) let _: ReferenceWritableKeyPath<C<A>, A> = #keyPath2(.value) // FIXME crash let _: PartialKeyPath<C<A>> = #keyPath2(C, .value) let _: KeyPath<C<A>, A> = #keyPath2(C, .value) let _: WritableKeyPath<C<A>, A> = #keyPath2(C, .value) // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<C<A>, A> = #keyPath2(C, .value) // FIXME crash let _: PartialKeyPath<Prop> = #keyPath2(.nonMutatingProperty) let _: KeyPath<Prop, B> = #keyPath2(.nonMutatingProperty) let _: WritableKeyPath<Prop, B> = #keyPath2(.nonMutatingProperty) let _: ReferenceWritableKeyPath<Prop, B> = #keyPath2(.nonMutatingProperty) } struct Z { } func testKeyPathSubscript(readonly: Z, writable: inout Z, kp: KeyPath<Z, Int>, wkp: WritableKeyPath<Z, Int>, rkp: ReferenceWritableKeyPath<Z, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testKeyPathSubscriptMetatype(readonly: Z.Type, writable: inout Z.Type, kp: KeyPath<Z.Type, Int>, wkp: WritableKeyPath<Z.Type, Int>, rkp: ReferenceWritableKeyPath<Z.Type, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testKeyPathSubscriptTuple(readonly: (Z,Z), writable: inout (Z,Z), kp: KeyPath<(Z,Z), Int>, wkp: WritableKeyPath<(Z,Z), Int>, rkp: ReferenceWritableKeyPath<(Z,Z), Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testSyntaxErrors() { // expected-note{{}} // TODO: recovery _ = #keyPath2(. ; // expected-error{{expected property or type name}} _ = #keyPath2(.a ; _ = #keyPath2([a ; _ = #keyPath2([a]; _ = #keyPath2(? ; _ = #keyPath2(! ; _ = #keyPath2(. ; _ = #keyPath2(.a ; _ = #keyPath2([a ; _ = #keyPath2([a,; _ = #keyPath2([a:; _ = #keyPath2([a]; _ = #keyPath2(.a?; _ = #keyPath2(.a!; _ = #keyPath2(A ; _ = #keyPath2(A, ; _ = #keyPath2(A< ; _ = #keyPath2(A, . ; _ = #keyPath2(A, .a ; _ = #keyPath2(A, [a ; _ = #keyPath2(A, [a]; _ = #keyPath2(A, ? ; _ = #keyPath2(A, ! ; _ = #keyPath2(A, . ; _ = #keyPath2(A, .a ; _ = #keyPath2(A, [a ; _ = #keyPath2(A, [a,; _ = #keyPath2(A, [a:; _ = #keyPath2(A, [a]; _ = #keyPath2(A, .a?; _ = #keyPath2(A, .a!; } // expected-error@+1{{}}
b27df1210be1263da95a95e48ce38a64
34.386957
101
0.621207
false
false
false
false
ColorPenBoy/ios-charts
refs/heads/master
Charts/Classes/Renderers/ChartLegendRenderer.swift
apache-2.0
5
// // ChartLegendRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartLegendRenderer: ChartRendererBase { /// the legend object this renderer renders internal var _legend: ChartLegend! public init(viewPortHandler: ChartViewPortHandler, legend: ChartLegend?) { super.init(viewPortHandler: viewPortHandler) _legend = legend } /// Prepares the legend and calculates all needed forms, labels and colors. public func computeLegend(data: ChartData) { if (!_legend.isLegendCustom) { var labels = [String?]() var colors = [UIColor?]() // loop for building up the colors and labels used in the legend for (var i = 0, count = data.dataSetCount; i < count; i++) { let dataSet = data.getDataSetByIndex(i)! var clrs: [UIColor] = dataSet.colors let entryCount = dataSet.entryCount // if we have a barchart with stacked bars if (dataSet.isKindOfClass(BarChartDataSet) && (dataSet as! BarChartDataSet).isStacked) { let bds = dataSet as! BarChartDataSet var sLabels = bds.stackLabels for (var j = 0; j < clrs.count && j < bds.stackSize; j++) { labels.append(sLabels[j % sLabels.count]) colors.append(clrs[j]) } if (bds.label != nil) { // add the legend description label colors.append(nil) labels.append(bds.label) } } else if (dataSet.isKindOfClass(PieChartDataSet)) { var xVals = data.xVals let pds = dataSet as! PieChartDataSet for (var j = 0; j < clrs.count && j < entryCount && j < xVals.count; j++) { labels.append(xVals[j]) colors.append(clrs[j]) } if (pds.label != nil) { // add the legend description label colors.append(nil) labels.append(pds.label) } } else { // all others for (var j = 0; j < clrs.count && j < entryCount; j++) { // if multiple colors are set for a DataSet, group them if (j < clrs.count - 1 && j < entryCount - 1) { labels.append(nil) } else { // add label to the last entry labels.append(dataSet.label) } colors.append(clrs[j]) } } } _legend.colors = colors + _legend._extraColors _legend.labels = labels + _legend._extraLabels } // calculate all dimensions of the legend _legend.calculateDimensions(labelFont: _legend.font, viewPortHandler: viewPortHandler) } public func renderLegend(context context: CGContext?) { if (_legend === nil || !_legend.enabled) { return } let labelFont = _legend.font let labelTextColor = _legend.textColor let labelLineHeight = labelFont.lineHeight let formYOffset = labelLineHeight / 2.0 var labels = _legend.labels var colors = _legend.colors let formSize = _legend.formSize let formToTextSpace = _legend.formToTextSpace let xEntrySpace = _legend.xEntrySpace let direction = _legend.direction // space between the entries let stackSpace = _legend.stackSpace let yoffset = _legend.yOffset let xoffset = _legend.xOffset let legendPosition = _legend.position switch (legendPosition) { case .BelowChartLeft: fallthrough case .BelowChartRight: fallthrough case .BelowChartCenter: let contentWidth: CGFloat = viewPortHandler.contentWidth var originPosX: CGFloat if (legendPosition == .BelowChartLeft) { originPosX = viewPortHandler.contentLeft + xoffset if (direction == .RightToLeft) { originPosX += _legend.neededWidth } } else if (legendPosition == .BelowChartRight) { originPosX = viewPortHandler.contentRight - xoffset if (direction == .LeftToRight) { originPosX -= _legend.neededWidth } } else // if (legendPosition == .BelowChartCenter) { originPosX = viewPortHandler.contentLeft + contentWidth / 2.0 } var calculatedLineSizes = _legend.calculatedLineSizes var calculatedLabelSizes = _legend.calculatedLabelSizes var calculatedLabelBreakPoints = _legend.calculatedLabelBreakPoints var posX: CGFloat = originPosX var posY: CGFloat = viewPortHandler.chartHeight - yoffset - _legend.neededHeight var lineIndex: Int = 0 for (var i = 0, count = labels.count; i < count; i++) { if (calculatedLabelBreakPoints[i]) { posX = originPosX posY += labelLineHeight } if (posX == originPosX && legendPosition == .BelowChartCenter) { posX += (direction == .RightToLeft ? calculatedLineSizes[lineIndex].width : -calculatedLineSizes[lineIndex].width) / 2.0 lineIndex++ } let drawingForm = colors[i] != nil let isStacked = labels[i] == nil; // grouped forms have null labels if (drawingForm) { if (direction == .RightToLeft) { posX -= formSize } drawForm(context, x: posX, y: posY + formYOffset, colorIndex: i, legend: _legend) if (direction == .LeftToRight) { posX += formSize } } if (!isStacked) { if (drawingForm) { posX += direction == .RightToLeft ? -formToTextSpace : formToTextSpace } if (direction == .RightToLeft) { posX -= calculatedLabelSizes[i].width } drawLabel(context, x: posX, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) if (direction == .LeftToRight) { posX += calculatedLabelSizes[i].width } posX += direction == .RightToLeft ? -xEntrySpace : xEntrySpace } else { posX += direction == .RightToLeft ? -stackSpace : stackSpace } } break case .PiechartCenter: fallthrough case .RightOfChart: fallthrough case .RightOfChartCenter: fallthrough case .RightOfChartInside: fallthrough case .LeftOfChart: fallthrough case .LeftOfChartCenter: fallthrough case .LeftOfChartInside: // contains the stacked legend size in pixels var stack = CGFloat(0.0) var wasStacked = false var posX: CGFloat = 0.0, posY: CGFloat = 0.0 if (legendPosition == .PiechartCenter) { posX = viewPortHandler.chartWidth / 2.0 + (direction == .LeftToRight ? -_legend.textWidthMax / 2.0 : _legend.textWidthMax / 2.0) posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0 + _legend.yOffset } else { let isRightAligned = legendPosition == .RightOfChart || legendPosition == .RightOfChartCenter || legendPosition == .RightOfChartInside if (isRightAligned) { posX = viewPortHandler.chartWidth - xoffset if (direction == .LeftToRight) { posX -= _legend.textWidthMax } } else { posX = xoffset if (direction == .RightToLeft) { posX += _legend.textWidthMax } } if (legendPosition == .RightOfChart || legendPosition == .LeftOfChart) { posY = viewPortHandler.contentTop + yoffset } else if (legendPosition == .RightOfChartCenter || legendPosition == .LeftOfChartCenter) { posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0 } else /*if (legend.position == .RightOfChartInside || legend.position == .LeftOfChartInside)*/ { posY = viewPortHandler.contentTop + yoffset } } for (var i = 0; i < labels.count; i++) { let drawingForm = colors[i] != nil var x = posX if (drawingForm) { if (direction == .LeftToRight) { x += stack } else { x -= formSize - stack } drawForm(context, x: x, y: posY + formYOffset, colorIndex: i, legend: _legend) if (direction == .LeftToRight) { x += formSize } } if (labels[i] != nil) { if (drawingForm && !wasStacked) { x += direction == .LeftToRight ? formToTextSpace : -formToTextSpace } else if (wasStacked) { x = posX } if (direction == .RightToLeft) { x -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width } if (!wasStacked) { drawLabel(context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } else { posY += labelLineHeight drawLabel(context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } // make a step down posY += labelLineHeight stack = 0.0 } else { stack += formSize + stackSpace wasStacked = true } } break } } private var _formLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) /// Draws the Legend-form at the given position with the color at the given index. internal func drawForm(context: CGContext?, x: CGFloat, y: CGFloat, colorIndex: Int, legend: ChartLegend) { let formColor = legend.colors[colorIndex] if (formColor === nil || formColor == UIColor.clearColor()) { return } let formsize = legend.formSize CGContextSaveGState(context) switch (legend.form) { case .Circle: CGContextSetFillColorWithColor(context, formColor!.CGColor) CGContextFillEllipseInRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) break case .Square: CGContextSetFillColorWithColor(context, formColor!.CGColor) CGContextFillRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) break case .Line: CGContextSetLineWidth(context, legend.formLineWidth) CGContextSetStrokeColorWithColor(context, formColor!.CGColor) _formLineSegmentsBuffer[0].x = x _formLineSegmentsBuffer[0].y = y _formLineSegmentsBuffer[1].x = x + formsize _formLineSegmentsBuffer[1].y = y CGContextStrokeLineSegments(context, _formLineSegmentsBuffer, 2) break } CGContextRestoreGState(context) } /// Draws the provided label at the given position. internal func drawLabel(context: CGContext?, x: CGFloat, y: CGFloat, label: String, font: UIFont, textColor: UIColor) { ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .Left, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor]) } }
12782eefdefd8c1974caca0b1069f00b
35.23301
184
0.449722
false
false
false
false
puttin/Curator
refs/heads/master
Tests/UtilityTests.swift
mit
1
import XCTest @testable import Curator class UtilityTests: XCTestCase { func testFileManager() { let fileManager = CuratorFileManager let defaultFileManager = FileManager.default XCTAssertNotEqual(fileManager, defaultFileManager) } func testURLComponents_CuratorLocation() { var goodURLComponents = URLComponents() goodURLComponents.scheme = "file" goodURLComponents.host = "" goodURLComponents.path = "/file" let _ = try! (goodURLComponents as CuratorLocation).asURL() var badURLComponents = URLComponents() badURLComponents.path = "//" do { let _ = try (badURLComponents as CuratorLocation).asURL() XCTFail() } catch Curator.Error.invalidLocation(_) {} catch { XCTFail() } } func testKeepableExtension() { let data = Data(count: 100) try! data.crt.save(to: "\(UUID().uuidString)", in: .tmp) } func testCuratorEasyGetData() { let data = Data(count: 100) let uuidString = UUID().uuidString try! data.crt.save(to: uuidString, in: .tmp) let _ = try! Curator.getData(of: uuidString, in: .tmp) } }
658c7abc6b29ed46ff6e9c857f335680
30.692308
69
0.607605
false
true
false
false
ZHSD/ZHZB
refs/heads/master
ZHZB/ZHZB/Classes/Tools/Extension/UIBarButtonItem-Extension.swift
mit
1
// // UIBarButtonItem-Extension.swift // ZHZB // // Created by 张浩 on 2016/11/15. // Copyright © 2016年 张浩. All rights reserved. // import UIKit extension UIBarButtonItem { //类方法 class func creatItem(imageName: String, highImageName:String, size:CGSize) -> UIBarButtonItem{ let btn = UIButton() btn.setImage(UIImage(named: imageName), for: .normal) btn.setImage(UIImage(named: highImageName), for: .highlighted) btn.frame = CGRect(origin:CGPoint.zero, size: size) return UIBarButtonItem(customView: btn) } //便利构造方法1.以convenience init 不需要写返回值 2.必须调用设计的构造函数(self) convenience init(imageName: String, highImageName:String = "", size:CGSize = CGSize.zero) { //1创建Btn let btn = UIButton() //2.设置btn图片 btn.setImage(UIImage(named: imageName), for: .normal) if highImageName != "" { btn.setImage(UIImage(named: highImageName), for: .highlighted) } //3.设置btn大小 if size == CGSize.zero { btn.sizeToFit() }else{ btn.frame = CGRect(origin:CGPoint.zero, size: size) } //4.创建uibarbuttonItem self.init(customView:btn) } }
75811a7189c8169951c5821e06dd1200
27.545455
98
0.594745
false
false
false
false
Syerram/asphalos
refs/heads/master
asphalos/FormBaseCell.swift
mit
1
// // FormBaseCell.swift // SwiftForms // // Created by Miguel Angel Ortuno on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit class FormBaseCell: UITableViewCell { /// MARK: Properties var rowDescriptor: FormRowDescriptor! { didSet { self.update() } } var formViewController: FormViewController! var rowIndex:NSIndexPath? private var customConstraints: [AnyObject] = [] /// MARK: Init required override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// MARK: Public interface func configure() { /// override } func update() { /// override } func defaultVisualConstraints() -> [String] { /// override return [] } func constraintsViews() -> [String : UIView] { /// override return [:] } func firstResponderElement() -> UIResponder? { /// override return nil } func inputAccesoryView() -> UIToolbar { let actionBar = UIToolbar() actionBar.translucent = true actionBar.sizeToFit() actionBar.barStyle = .Default // let prevNext = UISegmentedControl(items: [NSLocalizedString("Previous", comment: ""), NSLocalizedString("Next", comment: "")]) // prevNext.momentary = true // prevNext.tintColor = actionBar.tintColor // prevNext.addTarget(self, action: "handleActionBarPreviousNext:", forControlEvents: .ValueChanged) let doneButton = UIBarButtonItem(title: NSLocalizedString("Done", comment: ""), style: .Done, target: self, action: "handleDoneAction:") // let prevNextWrapper = UIBarButtonItem(customView: prevNext) let flexible = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) actionBar.items = [/*prevNextWrapper, */ flexible, doneButton] return actionBar } func handleActionBarPreviousNext(segmentedControl: UISegmentedControl) { } func handleDoneAction(_: UIBarButtonItem) { firstResponderElement()?.resignFirstResponder() } class func formRowCellHeight() -> CGFloat { return 44.0 } class func formRowCanBecomeFirstResponder() -> Bool { return false } class func formViewController(formViewController: FormViewController, didSelectRow: FormBaseCell) { } /// MARK: Constraints override func updateConstraints() { if customConstraints.count > 0 { contentView.removeConstraints(customConstraints) } var views = constraintsViews() customConstraints.removeAll() var visualConstraints: NSArray! if rowDescriptor.visualConstraintsBlock != nil { visualConstraints = rowDescriptor.visualConstraintsBlock(self) } else { visualConstraints = self.defaultVisualConstraints() } for visualConstraint in visualConstraints { let constraints = NSLayoutConstraint.constraintsWithVisualFormat(visualConstraint as! String, options: NSLayoutFormatOptions(0), metrics: nil, views: views) for constraint in constraints { customConstraints.append(constraint) } } contentView.addConstraints(customConstraints) super.updateConstraints() } }
9f725b26298f6edf1fd104d272eac5be
27.234848
168
0.61363
false
false
false
false
phpmaple/Stick-Hero-Swift
refs/heads/master
Stick-Hero/GameViewController.swift
mit
1
// // GameViewController.swift // Stick-Hero // // Created by 顾枫 on 15/6/19. // Copyright (c) 2015年 koofrank. All rights reserved. // import UIKit import SpriteKit import AVFoundation class GameViewController: UIViewController { var musicPlayer:AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() let scene = StickHeroGameScene(size:CGSize(width: DefinedScreenWidth, height: DefinedScreenHeight)) // Configure the view. let skView = self.view as! SKView // skView.showsFPS = true // skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .aspectFill skView.presentScene(scene) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) musicPlayer = setupAudioPlayerWithFile("bg_country", type: "mp3") musicPlayer.numberOfLoops = -1 musicPlayer.play() } func setupAudioPlayerWithFile(_ file:NSString, type:NSString) -> AVAudioPlayer { let url = Bundle.main.url(forResource: file as String, withExtension: type as String) var audioPlayer:AVAudioPlayer? do { try audioPlayer = AVAudioPlayer(contentsOf: url!) } catch { print("NO AUDIO PLAYER") } return audioPlayer! } override var shouldAutorotate : Bool { return true } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .portrait } override var prefersStatusBarHidden : Bool { return true } }
e690d7d4adb1542969c6883037d72b64
25.3
107
0.625747
false
false
false
false
JohnPJenkins/swift-t
refs/heads/master
stc/tests/850-checkpoint.swift
apache-2.0
2
import assert; // Basic test for checkpointing main { trace(f(1)); trace(f(2)); foreach i in [1:100] { trace(f(i)); t1, t2 = g(i); trace(t1, t2); trace(h(i, fromint(i*10), blob_from_string(fromint(i*1000)))); } assertEqual(f(1), 2, "f(1)"); x1, x2 = g(3); assertEqual(x1, 4, "x1"); assertEqual(x2, 5, "x2"); // 10 + 10 + 4 tot = h(10, "word", blob_from_string("word word")); assertEqual(tot, 24, "tot"); } // Single scalar arg @checkpoint (int o) f (int i) { trace("f executed args: " + fromint(i)); o = i + 1; } // Single scalar arg, multiple outputs @checkpoint (int o1, int o2) g (int i) "turbine" "0.0" [ "puts \"trace: g executed args: <<i>>\"; lassign [ list [ expr <<i>> + 1 ] [ expr <<i>> + 2 ] ] <<o1>> <<o2>>" ]; import blob; import string; // Multiple scalar args, including blob @checkpoint (int o) h (int i, string s, blob b) { trace("h executed args: " + fromint(i)); o = i + blob_size(b) + strlen(s); }
549dc10e9a942f75eff08bd1490f5ece
18.294118
112
0.557927
false
false
false
false
danthorpe/YapDatabaseExtensions
refs/heads/development
Sources/Curried_ValueWithObjectMetadata.swift
mit
1
// // Curried_ValueWithObjectMetadata.swift // YapDatabaseExtensions // // Created by Daniel Thorpe on 14/10/2015. // // import Foundation import ValueCoding // MARK: - Persistable extension Persistable where Self: ValueCoding, Self.Coder: NSCoding, Self.Coder.ValueType == Self, Self.MetadataType: NSCoding { /** Returns a closure which, given a read transaction will return the item at the given index. - parameter index: a YapDB.Index - returns: a (ReadTransaction) -> Self? closure. */ public static func readAtIndex< ReadTransaction where ReadTransaction: ReadTransactionType>(index: YapDB.Index) -> ReadTransaction -> Self? { return { $0.readAtIndex(index) } } /** Returns a closure which, given a read transaction will return the items at the given indexes. - parameter indexes: a SequenceType of YapDB.Index values - returns: a (ReadTransaction) -> [Self] closure. */ public static func readAtIndexes< Indexes, ReadTransaction where Indexes: SequenceType, Indexes.Generator.Element == YapDB.Index, ReadTransaction: ReadTransactionType>(indexes: Indexes) -> ReadTransaction -> [Self] { return { $0.readAtIndexes(indexes) } } /** Returns a closure which, given a read transaction will return the item at the given key. - parameter key: a String - returns: a (ReadTransaction) -> Self? closure. */ public static func readByKey< ReadTransaction where ReadTransaction: ReadTransactionType>(key: String) -> ReadTransaction -> Self? { return { $0.readByKey(key) } } /** Returns a closure which, given a read transaction will return the items at the given keys. - parameter keys: a SequenceType of String values - returns: a (ReadTransaction) -> [Self] closure. */ public static func readByKeys< Keys, ReadTransaction where Keys: SequenceType, Keys.Generator.Element == String, ReadTransaction: ReadTransactionType>(keys: Keys) -> ReadTransaction -> [Self] { return { $0.readAtIndexes(Self.indexesWithKeys(keys)) } } /** Returns a closure which, given a write transaction will write and return the item. - warning: Be aware that this will capure `self`. - returns: a (WriteTransaction) -> Self closure */ public func write<WriteTransaction: WriteTransactionType>() -> WriteTransaction -> Self { return { $0.write(self) } } }
587d94da46ea5be6df4adf5c5530e480
28.976744
95
0.653607
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGPU/CoreImage/PalettizeKernel.swift
mit
1
// // PalettizeKernel.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if canImport(CoreImage) extension CIImage { private class PalettizeKernel: CIImageProcessorKernel { override class var synchronizeInputs: Bool { return false } override class func roi(forInput input: Int32, arguments: [String: Any]?, outputRect: CGRect) -> CGRect { if input == 1, let palette_extent = arguments?["palette_extent"] as? CGRect { return palette_extent } return outputRect } override class func process(with inputs: [CIImageProcessorInput]?, arguments: [String: Any]?, output: CIImageProcessorOutput) throws { guard let commandBuffer = output.metalCommandBuffer else { return } guard let input = inputs?[0].metalTexture else { return } guard let palette = inputs?[1].metalTexture, palette.width > 0 && palette.height == 1 else { return } guard let output = output.metalTexture else { return } let device = commandBuffer.device guard let pipeline = self.make_pipeline(device, "palettize") else { return } guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return } encoder.setComputePipelineState(pipeline) encoder.setTexture(input, index: 0) encoder.setTexture(palette, index: 1) encoder.setTexture(output, index: 2) let group_width = max(1, pipeline.threadExecutionWidth) let group_height = max(1, pipeline.maxTotalThreadsPerThreadgroup / group_width) let threadsPerThreadgroup = MTLSize(width: group_width, height: group_height, depth: 1) let threadgroupsPerGrid = MTLSize(width: (output.width + group_width - 1) / group_width, height: (output.height + group_height - 1) / group_height, depth: 1) encoder.dispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup) encoder.endEncoding() } } public func palettize(palette: CIImage) -> CIImage { if extent.isEmpty { return .empty() } let rendered = try? PalettizeKernel.apply(withExtent: self.extent, inputs: [self, palette], arguments: ["palette_extent": palette.extent]) return rendered ?? .empty() } public func palettize<C: Collection>(palette: C) -> CIImage where C.Element: ColorPixel, C.Element.Model == RGBColorModel { if extent.isEmpty { return .empty() } let _palette = CIImage( bitmapData: MappedBuffer(palette).map { Float32ColorPixel($0).premultiplied() }.data, bytesPerRow: palette.count * 16, size: CGSize(width: palette.count, height: 1), format: .RGBAf, colorSpace: colorSpace) return palettize(palette: _palette) } } #endif
52b23fd479fc6c8f134f3535720e1a69
41.939394
169
0.637732
false
false
false
false
ThumbWorks/i-meditated
refs/heads/master
Carthage/Checkouts/RxSwift/RxCocoa/iOS/UIBarButtonItem+Rx.swift
mit
6
// // UIBarButtonItem+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/31/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif var rx_tap_key: UInt8 = 0 extension Reactive where Base: UIBarButtonItem { /** Bindable sink for `enabled` property. */ public var enabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: self.base) { UIElement, value in UIElement.isEnabled = value }.asObserver() } /** Reactive wrapper for target action pattern on `self`. */ public var tap: ControlEvent<Void> { let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<Void> in Observable.create { [weak control = self.base] observer in guard let control = control else { observer.on(.completed) return Disposables.create() } let target = BarButtonItemTarget(barButtonItem: control) { observer.on(.next()) } return target } .takeUntil(self.deallocated) .share() } return ControlEvent(events: source) } } @objc class BarButtonItemTarget: RxTarget { typealias Callback = () -> Void weak var barButtonItem: UIBarButtonItem? var callback: Callback! init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) { self.barButtonItem = barButtonItem self.callback = callback super.init() barButtonItem.target = self barButtonItem.action = #selector(BarButtonItemTarget.action(_:)) } override func dispose() { super.dispose() #if DEBUG MainScheduler.ensureExecutingOnScheduler() #endif barButtonItem?.target = nil barButtonItem?.action = nil callback = nil } func action(_ sender: AnyObject) { callback() } } #endif
5616cca0a14113a52d83cdeb13c48eec
23.255814
84
0.580058
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/EditPreviewViewController.swift
mit
1
import UIKit import WMF protocol EditPreviewViewControllerDelegate: NSObjectProtocol { func editPreviewViewControllerDidTapNext(_ editPreviewViewController: EditPreviewViewController) } class EditPreviewViewController: ViewController, WMFPreviewAnchorTapAlertDelegate, InternalLinkPreviewing { var sectionID: Int? var articleURL: URL var languageCode: String? var wikitext = "" var editFunnel: EditFunnel? var loggedEditActions: NSMutableSet? var editFunnelSource: EditFunnelSource = .unknown var savedPagesFunnel: SavedPagesFunnel? weak var delegate: EditPreviewViewControllerDelegate? lazy var messagingController: ArticleWebMessagingController = { let controller = ArticleWebMessagingController() controller.delegate = self return controller }() lazy var fetcher = ArticleFetcher() private let previewWebViewContainer: PreviewWebViewContainer var scrollToAnchorCompletions: [ScrollToAnchorCompletion] = [] var scrollViewAnimationCompletions: [() -> Void] = [] lazy var referenceWebViewBackgroundTapGestureRecognizer: UITapGestureRecognizer = { let tapGR = UITapGestureRecognizer(target: self, action: #selector(tappedWebViewBackground)) tapGR.delegate = self webView.scrollView.addGestureRecognizer(tapGR) tapGR.isEnabled = false return tapGR }() init(articleURL: URL) { self.articleURL = articleURL self.previewWebViewContainer = PreviewWebViewContainer() super.init() webView.scrollView.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func previewWebViewContainer(_ previewWebViewContainer: PreviewWebViewContainer, didTapLink url: URL) { let isExternal = url.host != articleURL.host if isExternal { showExternalLinkInAlert(link: url.absoluteString) } else { showInternalLink(url: url) } } func showExternalLinkInAlert(link: String) { let title = WMFLocalizedString("wikitext-preview-link-external-preview-title", value: "External link", comment: "Title for external link preview popup") let message = String(format: WMFLocalizedString("wikitext-preview-link-external-preview-description", value: "This link leads to an external website: %1$@", comment: "Description for external link preview popup. $1$@ is the external url."), link) let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: CommonStrings.okTitle, style: .default, handler: nil)) present(alertController, animated: true) } func showInternalLinkInAlert(link: String) { let title = WMFLocalizedString("wikitext-preview-link-preview-title", value: "Link preview", comment: "Title for link preview popup") let message = String(format: WMFLocalizedString("wikitext-preview-link-preview-description", value: "This link leads to '%1$@'", comment: "Description of the link URL. %1$@ is the URL."), link) let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: CommonStrings.okTitle, style: .default, handler: nil)) present(alertController, animated: true) } @objc func goBack() { navigationController?.popViewController(animated: true) } @objc func goForward() { delegate?.editPreviewViewControllerDidTapNext(self) } override func viewDidLoad() { super.viewDidLoad() view.addSubview(previewWebViewContainer) view.wmf_addConstraintsToEdgesOfView(previewWebViewContainer) previewWebViewContainer.previewAnchorTapAlertDelegate = self navigationItem.title = WMFLocalizedString("navbar-title-mode-edit-wikitext-preview", value: "Preview", comment: "Header text shown when wikitext changes are being previewed. {{Identical|Preview}}") navigationItem.leftBarButtonItem = UIBarButtonItem.wmf_buttonType(.caretLeft, target: self, action: #selector(self.goBack)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: CommonStrings.nextTitle, style: .done, target: self, action: #selector(self.goForward)) navigationItem.rightBarButtonItem?.tintColor = theme.colors.link if let loggedEditActions = loggedEditActions, !loggedEditActions.contains(EditFunnel.Action.preview) { editFunnel?.logEditPreviewForArticle(from: editFunnelSource, language: languageCode) loggedEditActions.add(EditFunnel.Action.preview) } apply(theme: theme) previewWebViewContainer.webView.uiDelegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadPreviewIfNecessary() } override func viewWillDisappear(_ animated: Bool) { WMFAlertManager.sharedInstance.dismissAlert() super.viewWillDisappear(animated) } deinit { messagingController.removeScriptMessageHandler() } private var hasPreviewed = false private func loadPreviewIfNecessary() { guard !hasPreviewed else { return } hasPreviewed = true messagingController.setup(with: previewWebViewContainer.webView, languageCode: languageCode ?? "en", theme: theme, layoutMargins: articleMargins, areTablesInitiallyExpanded: true) WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("wikitext-preview-changes", value: "Retrieving preview of your changes...", comment: "Alert text shown when getting preview of user changes to wikitext"), sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) let pcsLocalAndStagingEnvironmentsCompletion: () throws -> Void = { [weak self] in guard let self = self else { return } // If on local or staging PCS, we need to split this call. On the RESTBase server, wikitext-to-mobilehtml just puts together two other // calls - wikitext-to-html, and html-to-mobilehtml. Since we have html-to-mobilehtml in local/staging PCS but not the first call, if // we're making PCS edits to mobilehtml we need this code in order to view them. We split the call (similar to what the server dioes) // routing the wikitext-to-html call to production, and html-to-mobilehtml to local or staging PCS. let completion: ((String?, URL?) -> Void) = { [weak self] (html, responseUrl) in DispatchQueue.main.async { guard let html = html else { self?.showGenericError() return } // While we'd normally expect this second request to be able to loaded via `...webView.load(request)`, for unknown // reasons it wasn't working in that route - but was working when loaded via HTML string (in completion handler) - // despite both responses being identical when inspected via a proxy server. self?.previewWebViewContainer.webView.loadHTMLString(html, baseURL: responseUrl) } } try self.fetcher.fetchMobileHTMLFromWikitext(articleURL: self.articleURL, wikitext: self.wikitext, mobileHTMLOutput: .editPreview, completion: completion) } let pcsProductionCompletion: () throws -> Void = { [weak self] in guard let self = self else { return } let request = try self.fetcher.wikitextToMobileHTMLPreviewRequest(articleURL: self.articleURL, wikitext: self.wikitext, mobileHTMLOutput: .editPreview) self.previewWebViewContainer.webView.load(request) } do { let environment = Configuration.current.environment switch environment { case .local(let options): if options.contains(.localPCS) { try pcsLocalAndStagingEnvironmentsCompletion() return } try pcsProductionCompletion() case .staging(let options): if options.contains(.appsLabsforPCS) { try pcsLocalAndStagingEnvironmentsCompletion() return } try pcsProductionCompletion() default: try pcsProductionCompletion() } } catch { showGenericError() } } override func apply(theme: Theme) { super.apply(theme: theme) if viewIfLoaded == nil { return } previewWebViewContainer.apply(theme: theme) } @objc func tappedWebViewBackground() { dismissReferenceBackLinksViewController() } } // MARK: - References extension EditPreviewViewController: WMFReferencePageViewAppearanceDelegate, ReferenceViewControllerDelegate, UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { didFinishAnimating(pageViewController) } } extension EditPreviewViewController: ReferenceBackLinksViewControllerDelegate, ReferenceShowing { var webView: WKWebView { return previewWebViewContainer.webView } } extension EditPreviewViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return shouldRecognizeSimultaneousGesture(recognizer: gestureRecognizer) } } extension EditPreviewViewController: ArticleWebMessageHandling { func didRecieve(action: ArticleWebMessagingController.Action) { switch action { case .unknown(let href): showExternalLinkInAlert(link: href) case .backLink(let referenceId, let referenceText, let backLinks): showReferenceBackLinks(backLinks, referenceId: referenceId, referenceText: referenceText) case .reference(let index, let group): showReferences(group, selectedIndex: index, animated: true) case .link(let href, _, let title): if let title = title, !title.isEmpty { guard let host = articleURL.host, let encodedTitle = title.percentEncodedPageTitleForPathComponents, let newArticleURL = Configuration.current.articleURLForHost(host, languageVariantCode: articleURL.wmf_languageVariantCode, appending: [encodedTitle]) else { showInternalLinkInAlert(link: href) break } showInternalLink(url: newArticleURL) } else { showExternalLinkInAlert(link: href) } case .scrollToAnchor(let anchor, let rect): scrollToAnchorCompletions.popLast()?(anchor, rect) default: break } } internal func updateArticleMargins() { messagingController.updateMargins(with: articleMargins, leadImageHeight: 0) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let marginUpdater: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { _ in self.updateArticleMargins() } coordinator.animate(alongsideTransition: marginUpdater) } } // MARK: - Context Menu extension EditPreviewViewController: ArticleContextMenuPresenting, WKUIDelegate { var configuration: Configuration { return Configuration.current } func getPeekViewControllerAsync(for destination: Router.Destination, completion: @escaping (UIViewController?) -> Void) { completion(getPeekViewController(for: destination)) } func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo, completionHandler: @escaping (UIContextMenuConfiguration?) -> Void) { self.contextMenuConfigurationForElement(elementInfo, completionHandler: completionHandler) } // func webView(_ webView: WKWebView, contextMenuForElement elementInfo: WKContextMenuElementInfo, willCommitWithAnimator animator: UIContextMenuInteractionCommitAnimating) // No function with this signature, as we don't want to have any context menu elements in preview - and we get that behavior by default by not implementing this. func getPeekViewController(for destination: Router.Destination) -> UIViewController? { let dataStore = MWKDataStore.shared() switch destination { case .article(let articleURL): return ArticlePeekPreviewViewController(articleURL: articleURL, dataStore: dataStore, theme: theme) default: return nil } } // This function needed is for ArticleContextMenuPresenting, but not applicable to EditPreviewVC func hideFindInPage(_ completion: (() -> Void)? = nil) { } var previewMenuItems: [UIMenuElement]? { return nil } } extension EditPreviewViewController: EditingFlowViewController { }
819596080128a509f8ca879052ad01d4
43.937294
284
0.681551
false
false
false
false
Jnosh/SwiftBinaryHeapExperiments
refs/heads/master
Tests/ClosureHeapTests.swift
mit
1
// // ClosureHeapTests.swift // BinaryHeap // // Created by Janosch Hildebrand on 05/12/15. // Copyright © 2015 Janosch Hildebrand. All rights reserved. // import XCTest import Framework // FIXME: Ideally we would just reuse the standard shared tests // But we currently can't do that as we can't conform the closure heaps to BinaryHeapType // For now we duplicate the tests. Alternatively could initialize the arrays outside the tests // but that would require a lot of boilerplate initialization code + passing the heaps as // inout args to have them uniquely referenced. // MARK: Tests func runInitTest<Heap: ClosureBinaryHeapType where Heap.Element : Comparable>(heapType: Heap.Type) -> Heap { let heap = heapType.init() assertEmpty(heap) return heap } func runInsertTest<Heap: ClosureBinaryHeapType where Heap.Element : Comparable>(heapType: Heap.Type, element: Heap.Element) { var heap = runInitTest(heapType) heap.insert(element) XCTAssert(heap.count == 1, "Element inserted") XCTAssert(heap.first == element, "Element inserted") assertInvariants(&heap) } func runRemoveTest<Heap: ClosureBinaryHeapType where Heap.Element : Comparable>(heapType: Heap.Type, element: Heap.Element) { var heap = runInitTest(heapType) heap.insert(element) let root = heap.removeFirst() XCTAssert(element == root, "Element removed") assertEmpty(heap) assertInvariants(&heap) } func runRemoveAllTest<Heap: ClosureBinaryHeapType where Heap.Element : Comparable>(heapType: Heap.Type, elements: [Heap.Element]) { var heap = runInitTest(heapType) insertElements(&heap, elements: elements) assertInvariants(&heap) // Remove heap.removeAll(keepCapacity: false) assertEmpty(heap) assertInvariants(&heap) } func runOrderTest<Heap: ClosureBinaryHeapType, Element : Comparable where Element == Heap.Element>(heapType: Heap.Type, elements: [Element]) { let sortedElements = elements.sort() var heap = runInitTest(heapType) insertElements(&heap, elements: elements) assertInvariants(&heap) // Remove var heapElements = [Element]() while !heap.isEmpty { heapElements.append(heap.removeFirst()) } assertEmpty(heap) assertInvariants(&heap) XCTAssert(sortedElements == heapElements, "Correct order") } func runCoWTest<Heap: ClosureBinaryHeapType, Element : Comparable where Element == Heap.Element>(heapType: Heap.Type, elements: [Element]) { var heap = runInitTest(heapType) insertElements(&heap, elements: elements) assertInvariants(&heap) // Copy var copy = heap // Remove var heapElements = [Element]() while !heap.isEmpty { heapElements.append(heap.removeFirst()) } // TODO: Should also test that other mutating funcs work with CoW (insert, removeAll, popFirst, ...) assertEmpty(heap) assertInvariants(&heap) XCTAssert(heapElements.count == elements.count, "Correct count") XCTAssert(copy.count == elements.count, "Elements not removed") XCTAssert(copy.first != nil, "Elements not removed") assertInvariants(&copy) var copyElements = [Element]() while !copy.isEmpty { copyElements.append(copy.removeFirst()) } assertEmpty(copy) assertInvariants(&copy) XCTAssert(heapElements == copyElements, "Same contents") }
a49df69df371e5a97eb77e724a77ea3a
29.770642
142
0.714371
false
true
false
false
Laptopmini/SwiftyArtik
refs/heads/master
Source/Subscription.swift
mit
1
// // Subscription.swift // SwiftyArtik // // Created by Paul-Valentin Mini on 9/5/17. // Copyright © 2017 Paul-Valentin Mini. All rights reserved. // import Foundation import ObjectMapper import PromiseKit open class Subscription: Mappable, PullableArtikInstance, RemovableArtikInstance { public var id: String? public var aid: String? public var messageType: MessagesAPI.MessageType? public var uid: String? public var description: String? public var subscriptionType: SubscriptionsAPI.SubscriptionType? public var status: SubscriptionsAPI.SubscriptionStatus? public var callbackURL: URL? public var awsKey: String? public var awsSecret: String? public var awsRegion: String? public var awsKinesisStream: String? public var createdOn: ArtikTimestamp? public var modifiedOn: ArtikTimestamp? public init() {} public required init?(map: Map) {} public func mapping(map: Map) { id <- map["id"] aid <- map["aid"] messageType <- map["messageType"] uid <- map["uid"] description <- map["description"] subscriptionType <- map["subscriptionType"] status <- map["status"] callbackURL <- map["callbackUrl"] awsKey <- map["awsKey"] awsSecret <- map["awsSecret"] awsRegion <- map["awsRegion"] awsKinesisStream <- map["awsKinesisStream"] createdOn <- map["createdOn"] modifiedOn <- map["modifiedOn"] } public func confirm(aid: String? = nil, nonce: String) -> Promise<Subscription> { let promise = Promise<Subscription>.pending() if let id = id { SubscriptionsAPI.confirm(sid: id, aid: aid, nonce: nonce).then { result -> Void in promise.fulfill(result) }.catch { error -> Void in promise.reject(error) } } else { promise.reject(ArtikError.missingValue(reason: .noID)) } return promise.promise } // MARK: - PullableArtikInstance public func pullFromArtik() -> Promise<Void> { let promise = Promise<Void>.pending() if let id = id { SubscriptionsAPI.get(sid: id).then { result -> Void in self.mapping(map: Map(mappingType: .fromJSON, JSON: result.toJSON(), toObject: true, context: nil, shouldIncludeNilValues: true)) promise.fulfill(()) }.catch { error -> Void in promise.reject(error) } } else { promise.reject(ArtikError.missingValue(reason: .noID)) } return promise.promise } // MARK: - RemovableArtikInstance public func removeFromArtik() -> Promise<Void> { let promise = Promise<Void>.pending() if let id = id { SubscriptionsAPI.remove(sid: id).then { _ -> Void in promise.fulfill(()) }.catch { error -> Void in promise.reject(error) } } else { promise.reject(ArtikError.missingValue(reason: .noID)) } return promise.promise } }
80e6234c08f19b6fd913a2485730e8d0
30.95
145
0.587793
false
false
false
false