repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
SeriousChoice/SCSwift
SCSwift/Controllers/SCVideoViewController.swift
1
9218
// // SCVideoViewController.swift // SCSwiftExample // // Created by Nicola Innocenti on 08/01/2022. // Copyright © 2022 Nicola Innocenti. All rights reserved. // import UIKit import AVFoundation import AVKit public enum VideoAspect: Int { case resizeAspectFill = 1 case resizeAspect = 2 case resize = 3 } public protocol SCVideoViewControllerDelegate : AnyObject { func videoReadyToPlay() func videoDidPlay() func videoDidPause() func videoDidStop() func videoDidFinishPlay() func videoDidFailLoad() func videoDidUpdateProgress(currentTime: TimeInterval, duration: TimeInterval) } open class SCVideoViewController: SCMediaViewController, SCMediaPlayerViewControllerDelegate { // MARK: - Xibs private var videoView: UIView = { let view = UIView() return view }() private var imgPlaceholder: UIImageView = { let image = UIImageView() image.contentMode = .scaleAspectFit image.clipsToBounds = true return image }() private var spinner: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView(style: .large) indicator.color = .lightGray indicator.hidesWhenStopped = true return indicator }() // MARK: - Constants & Variables internal var player: AVPlayer? internal var playerLayer: AVPlayerLayer? private var videoAspect: VideoAspect = .resizeAspectFill private var didFirstLoad: Bool = false public var autoPlay: Bool = false public var loop: Bool = false public weak var videoDelegate: SCVideoViewControllerDelegate? private var timeObserver: Any? // MARK: - Initialization public convenience init(media: SCMedia, autoPlay: Bool, loop: Bool, delegate: SCVideoViewControllerDelegate?) { self.init() self.media = media self.autoPlay = autoPlay self.loop = loop self.videoDelegate = delegate } // MARK: - UIViewController Methods override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .clear setupLayout() } private func setupLayout() { view.addSubview(videoView) videoView.sc_pinEdgesToSuperViewEdges() videoView.addSubview(imgPlaceholder) imgPlaceholder.sc_pinEdgesToSuperViewEdges() videoView.addSubview(spinner) videoView.sc_alignAxisToSuperviewAxis() spinner.startAnimating() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) videoDelegate?.videoDidUpdateProgress(currentTime: currentTime, duration: duration) if !didFirstLoad { self.initialize() } else { if player?.currentItem != nil { self.addObservers() } } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.pause() self.removeObservers() } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() playerLayer?.frame = videoView.frame /* if UIDevice.isPortrait { videoAspect = .resizeAspect } else { videoAspect = .resizeAspectFill }*/ videoAspect = .resizeAspect switch(videoAspect) { case .resizeAspectFill: playerLayer?.videoGravity = .resizeAspectFill case .resizeAspect: playerLayer?.videoGravity = .resizeAspect case .resize: playerLayer?.videoGravity = .resize } } // MARK: - Player Methods func addObservers() { NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlay(notification:)), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem) player?.addObserver(self, forKeyPath: "status", options: [], context: nil) timeObserver = player?.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 2), queue: DispatchQueue.main) { (time) in self.videoDelegate?.videoDidUpdateProgress(currentTime: time.seconds, duration: self.duration) } } func removeObservers() { NotificationCenter.default.removeObserver(self, name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem) player?.removeObserver(self, forKeyPath: "status") if let observer = timeObserver { player?.removeTimeObserver(observer) timeObserver = nil } } public var isReadyToPlay : Bool { return player?.status == .readyToPlay } public var isPlaying : Bool { return player?.rate != 0 } public var duration : TimeInterval { if let item = player?.currentItem { let seconds = item.duration.seconds return seconds.isNaN ? 0.0 : seconds } return 0.0 } public var currentTime : TimeInterval { if let item = player?.currentItem { let seconds = item.currentTime().seconds return seconds.isNaN ? 0.0 : seconds } return 0.0 } public var remainingTime : TimeInterval { return (self.duration - self.currentTime) } public func initialize() { guard let url = media.url else { return } player = AVPlayer(url: url) playerLayer = AVPlayerLayer(player: player) playerLayer?.frame = videoView.frame videoView.layer.addSublayer(playerLayer!) self.addObservers() self.loadThumbnail() } public func loadThumbnail() { guard let asset = player?.currentItem?.asset else { imgPlaceholder.image = nil return } DispatchQueue.global(qos: .background).async { let assetImgGenerate = AVAssetImageGenerator(asset: asset) assetImgGenerate.appliesPreferredTrackTransform = true let time = CMTimeMakeWithSeconds(Float64(self.media.videoThumbnailSecond), preferredTimescale: 100) var thumbnail: UIImage? do { let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil) thumbnail = UIImage(cgImage: img) } catch { } DispatchQueue.main.sync { self.imgPlaceholder.image = thumbnail } } } public func play() { player?.play() videoDelegate?.videoDidPlay() } public func play(from seconds: TimeInterval) { player?.seek(to: CMTime(seconds: seconds, preferredTimescale: 1000), toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero) self.play() videoDelegate?.videoDidPlay() } public func pause() { player?.pause() videoDelegate?.videoDidPause() } public func stop() { player?.pause() player?.seek(to: CMTime.zero) videoDelegate?.videoDidStop() } @objc public func playerDidFinishPlay(notification: Notification) { self.stop() videoDelegate?.videoDidFinishPlay() if loop { play() } } // MARK: - SCMediaPlayerViewController Delegate public func mediaPlayerDidTapPlay() { if isPlaying { self.pause() } else { self.play() } } public func mediaPlayerDidTapPause() { self.pause() } public func mediaPlayerDidTapStop() { self.stop() } public func mediaPlayerDidChangeTime(seconds: TimeInterval) { self.play(from: seconds) } // MARK: - Other Methods open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if (object as? AVPlayer) == player { if keyPath == "status" { if player?.status == .readyToPlay { let playable = player?.currentItem?.asset.isPlayable if playable == true { spinner.stopAnimating() imgPlaceholder.isHidden = true videoDelegate?.videoReadyToPlay() if autoPlay && !didFirstLoad { self.play() didFirstLoad = true } } else { videoDelegate?.videoDidFailLoad() self.delegate?.mediaDidFailLoad(media: self.media) } } } } } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
829b9bacd6a307c475c57cae905e0820
28.828479
156
0.58544
5.565821
false
false
false
false
xhamr/fave-button
Source/FaveButton.swift
1
8338
// // FaveButton.swift // FaveButton // // Copyright © 2016 Jansel Valentin. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public typealias DotColors = (first: UIColor, second: UIColor) public protocol FaveButtonDelegate{ func faveButton(_ faveButton: FaveButton, didSelected selected: Bool) func faveButtonDotColors(_ faveButton: FaveButton) -> [DotColors]? } // MARK: Default implementation public extension FaveButtonDelegate{ func faveButtonDotColors(_ faveButton: FaveButton) -> [DotColors]?{ return nil } } open class FaveButton: UIButton { fileprivate struct Const{ static let duration = 1.0 static let expandDuration = 0.1298 static let collapseDuration = 0.1089 static let faveIconShowDelay = Const.expandDuration + Const.collapseDuration/2.0 static let dotRadiusFactors = (first: 0.0633, second: 0.04) } @IBInspectable open var normalColor: UIColor = UIColor(red: 137/255, green: 156/255, blue: 167/255, alpha: 1) @IBInspectable open var selectedColor: UIColor = UIColor(red: 226/255, green: 38/255, blue: 77/255, alpha: 1) @IBInspectable open var dotFirstColor: UIColor = UIColor(red: 152/255, green: 219/255, blue: 236/255, alpha: 1) @IBInspectable open var dotSecondColor: UIColor = UIColor(red: 247/255, green: 188/255, blue: 48/255, alpha: 1) @IBInspectable open var circleFromColor: UIColor = UIColor(red: 221/255, green: 70/255, blue: 136/255, alpha: 1) @IBInspectable open var circleToColor: UIColor = UIColor(red: 205/255, green: 143/255, blue: 246/255, alpha: 1) @IBOutlet open weak var delegate: AnyObject? fileprivate(set) var sparkGroupCount: Int = 7 fileprivate var faveIconImage:UIImage? fileprivate var faveIcon: FaveIcon! fileprivate var animationsEnabled = true override open var isSelected: Bool { didSet{ guard self.animationsEnabled else { return } animateSelect(self.isSelected, duration: Const.duration) } } convenience public init(frame: CGRect, faveIconNormal: UIImage?) { self.init(frame: frame) guard let icon = faveIconNormal else{ fatalError("missing image for normal state") } faveIconImage = icon applyInit() } override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) applyInit() } public func setSelected(selected: Bool, animated: Bool) { guard selected != self.isSelected else { return } guard animated == false else { self.isSelected = selected return } self.animationsEnabled = false self.isSelected = selected self.animationsEnabled = true animateSelect(self.isSelected, duration: 0.0) // trigger state change without animation } } // MARK: create extension FaveButton{ fileprivate func applyInit(){ if nil == faveIconImage{ #if swift(>=4.2) faveIconImage = image(for: UIControl.State()) #else faveIconImage = image(for: UIControlState()) #endif } guard let faveIconImage = faveIconImage else{ fatalError("please provide an image for normal state.") } #if swift(>=4.2) setImage(UIImage(), for: UIControl.State()) setTitle(nil, for: UIControl.State()) #else setImage(UIImage(), for: UIControlState()) setTitle(nil, for: UIControlState()) #endif setImage(UIImage(), for: .selected) setTitle(nil, for: .selected) faveIcon = createFaveIcon(faveIconImage) addActions() } fileprivate func createFaveIcon(_ faveIconImage: UIImage) -> FaveIcon{ return FaveIcon.createFaveIcon(self, icon: faveIconImage,color: normalColor) } fileprivate func createSparks(_ radius: CGFloat) -> [Spark] { var sparks = [Spark]() let step = 360.0/Double(sparkGroupCount) let base = Double(bounds.size.width) let dotRadius = (base * Const.dotRadiusFactors.first, base * Const.dotRadiusFactors.second) let offset = 10.0 for index in 0..<sparkGroupCount{ let theta = step * Double(index) + offset let colors = dotColors(at: index) let spark = Spark.createSpark(self, radius: radius, firstColor: colors.first,secondColor: colors.second, angle: theta, dotRadius: dotRadius) sparks.append(spark) } return sparks } } // MARK: utils extension FaveButton{ fileprivate func dotColors(at index: Int) -> DotColors{ if case let delegate as FaveButtonDelegate = delegate , nil != delegate.faveButtonDotColors(self){ let colors = delegate.faveButtonDotColors(self)! let colorIndex = 0..<colors.count ~= index ? index : index % colors.count return colors[colorIndex] } return DotColors(self.dotFirstColor, self.dotSecondColor) } } // MARK: actions extension FaveButton{ func addActions(){ self.addTarget(self, action: #selector(toggle(_:)), for: .touchUpInside) } @objc func toggle(_ sender: FaveButton){ sender.isSelected = !sender.isSelected guard case let delegate as FaveButtonDelegate = self.delegate else{ return } let delay = DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * Const.duration)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delay){ delegate.faveButton(sender, didSelected: sender.isSelected) } } } // MARK: animation extension FaveButton { fileprivate func animateSelect(_ isSelected: Bool, duration: Double){ let color = isSelected ? selectedColor : normalColor faveIcon.animateSelect(isSelected, fillColor: color, duration: duration, delay: duration > 0.0 ? Const.faveIconShowDelay : 0.0) guard duration > 0.0 else { return } if isSelected{ let radius = bounds.size.scaleBy(1.3).width/2 // ring radius let igniteFromRadius = radius*0.8 let igniteToRadius = radius*1.1 let ring = Ring.createRing(self, radius: 0.01, lineWidth: 3, fillColor: self.circleFromColor) let sparks = createSparks(igniteFromRadius) ring.animateToRadius(radius, toColor: circleToColor, duration: Const.expandDuration, delay: 0) ring.animateColapse(radius, duration: Const.collapseDuration, delay: Const.expandDuration) sparks.forEach{ $0.animateIgniteShow(igniteToRadius, duration:0.4, delay: Const.collapseDuration/3.0) $0.animateIgniteHide(0.7, delay: 0.2) } } } }
mit
437ffdc08667e44bb01f9916f178acd3
34.326271
135
0.628164
4.575741
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/EditExperimentViewController.swift
1
12442
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Dialogs_Dialogs import third_party_objective_c_material_components_ios_components_Palettes_Palettes import third_party_objective_c_material_components_ios_components_TextFields_TextFields // swiftlint:disable line_length import third_party_objective_c_material_components_ios_components_private_KeyboardWatcher_KeyboardWatcher // swiftlint:enable line_length protocol EditExperimentViewControllerDelegate: class { /// Informs the delegate a new title was set. /// /// - Parameters: /// - title: A string title. /// - experimentID: The ID of the changed experiment. func editExperimentViewControllerDidSetTitle(_ title: String?, forExperimentID experimentID: String) /// Informs the delegate a new cover image was set. /// /// - Parameters: /// - imageData: The cover image data. /// - metadata: The image metadata. /// - experimentID: The ID of the changed experiment. func editExperimentViewControllerDidSetCoverImageData(_ imageData: Data?, metadata: NSDictionary?, forExperimentID experimentID: String) } /// A view allowing a user to edit an experiment's title and picture. class EditExperimentViewController: MaterialHeaderViewController, EditExperimentPhotoViewDelegate, ImageSelectorDelegate, UITextFieldDelegate { // MARK: - Constants let verticalPadding: CGFloat = 16.0 // MARK: - Properties weak var delegate: EditExperimentViewControllerDelegate? private let experiment: Experiment private let metadataManager: MetadataManager private let photoPicker = EditExperimentPhotoView() private let scrollView = UIScrollView() private let textField = MDCTextField() private var textFieldController: MDCTextInputController? private var existingTitle: String? private var existingPhoto: UIImage? private var selectedImageInfo: (imageData: Data, metadata: NSDictionary?)? private var textFieldLeadingConstraint: NSLayoutConstraint? private var textFieldTrailingConstraint: NSLayoutConstraint? private var textFieldWidthConstraint: NSLayoutConstraint? private var horizontalPadding: CGFloat { var padding: CGFloat { switch displayType { case .compact, .compactWide: return 16.0 case .regular: return 100 case .regularWide: return 300 } } return padding + view.safeAreaInsetsOrZero.left + view.safeAreaInsetsOrZero.right } override var trackedScrollView: UIScrollView? { return scrollView } // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - experiment: An experiment. /// - analyticsReporter: The analytics reporter. /// - metadataManager: The metadata manager. init(experiment: Experiment, analyticsReporter: AnalyticsReporter, metadataManager: MetadataManager) { self.experiment = experiment self.metadataManager = metadataManager super.init(analyticsReporter: analyticsReporter) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(red: 0.937, green: 0.933, blue: 0.933, alpha: 1.0) accessibilityViewIsModal = true if isPresented && UIDevice.current.userInterfaceIdiom == .pad { appBar.hideStatusBarOverlay() } // Configure the nav bar. title = String.editExperimentTitle let cancelButton = MaterialCloseBarButtonItem(target: self, action: #selector(cancelButtonPressed)) navigationItem.leftBarButtonItem = cancelButton let saveBarButton = MaterialBarButtonItem() saveBarButton.button.addTarget(self, action: #selector(saveButtonPressed), for: .touchUpInside) saveBarButton.button.setImage(UIImage(named: "ic_check"), for: .normal) saveBarButton.accessibilityLabel = String.saveBtnContentDescription navigationItem.rightBarButtonItem = saveBarButton // Configure the scroll view. view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.pinToEdgesOfView(view) // Bring the app bar to the front. view.bringSubviewToFront(appBar.headerViewController.headerView) // Text field and its controller. scrollView.addSubview(textField) textField.delegate = self textField.text = experiment.title existingTitle = experiment.title textField.clearButtonMode = .whileEditing textField.translatesAutoresizingMaskIntoConstraints = false textField.placeholder = String.experimentTitleHint textField.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: verticalPadding).isActive = true textFieldLeadingConstraint = textField.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor) textFieldLeadingConstraint?.isActive = true textFieldTrailingConstraint = textField.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor) textFieldTrailingConstraint?.isActive = true textFieldWidthConstraint = textField.widthAnchor.constraint(equalTo: scrollView.widthAnchor) textFieldWidthConstraint?.isActive = true let controller = MDCTextInputControllerUnderline(textInput: textField) controller.floatingPlaceholderNormalColor = .appBarReviewBackgroundColor controller.activeColor = .appBarReviewBackgroundColor textFieldController = controller // Photo picker. scrollView.addSubview(photoPicker) photoPicker.delegate = self photoPicker.translatesAutoresizingMaskIntoConstraints = false photoPicker.setContentHuggingPriority(.defaultHigh, for: .vertical) photoPicker.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: verticalPadding).isActive = true photoPicker.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -verticalPadding).isActive = true photoPicker.leadingAnchor.constraint(equalTo: textField.leadingAnchor).isActive = true photoPicker.trailingAnchor.constraint(equalTo: textField.trailingAnchor).isActive = true // Set the photo if one exists. if let image = metadataManager.imageForExperiment(experiment) { photoPicker.photo = image existingPhoto = image } NotificationCenter.default.addObserver( self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardDidChangeFrameNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateConstraintsForDisplayType() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (_) in self.updateConstraintsForDisplayType() }) } override func viewSafeAreaInsetsDidChange() { updateConstraintsForDisplayType() } override func accessibilityPerformEscape() -> Bool { guard existingTitle != trimmedTitleOrDefault() || photoPicker.photo != existingPhoto else { dismiss(animated: true) return true } // If changes need to be saved, ask the user first. cancelButtonPressed() return false } // MARK: - EditExperimentPhotoViewDelegate func choosePhotoButtonPressed() { let photoLibrary = EditExperimentPhotoLibraryViewController(analyticsReporter: analyticsReporter) photoLibrary.delegate = self present(photoLibrary, animated: true) } // MARK: - ImageSelectorDelegate func imageSelectorDidCreateImageData(_ imageDatas: [ImageData]) { // Check if the photo can be saved before proceeding. Normally this happens lower in the stack // but we do it here because it is currently not possible to pass the error up the UI to here. guard let imageDataTuple = imageDatas.first else { sjlog_info("[EditExperimentViewController] No imageData in imageSelectorDidCreateImageData.", category: .general) return } if imageDatas.count > 1 { sjlog_info("[EditExperimentViewController] More than 1 ImageData.", category: .general) } if metadataManager.canSave(imageDataTuple.imageData) { guard let image = UIImage(data: imageDataTuple.imageData) else { return } photoPicker.photo = image selectedImageInfo = imageDataTuple } else { dismiss(animated: true) { showSnackbar(withMessage: String.photoDiskSpaceErrorMessage) } } } func imageSelectorDidCancel() {} // MARK: - Notifications @objc func handleKeyboardNotification(_ notification: Notification) { let keyboardHeight = MDCKeyboardWatcher.shared().visibleKeyboardHeight scrollView.contentInset.bottom = keyboardHeight scrollView.scrollIndicatorInsets = scrollView.contentInset } // MARK: - Private /// Trims the text field's text of all whitespace and returns it if it's not empty. Otherwise it /// returns the default untitled experiment name. private func trimmedTitleOrDefault() -> String { if let title = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines), title != "" { return title } return String.localizedUntitledExperiment } private func updateConstraintsForDisplayType() { textFieldLeadingConstraint?.constant = horizontalPadding textFieldTrailingConstraint?.constant = -horizontalPadding textFieldWidthConstraint?.constant = -(horizontalPadding * 2) } // MARK: - User actions @objc private func cancelButtonPressed() { guard existingTitle != trimmedTitleOrDefault() || photoPicker.photo != existingPhoto else { dismiss(animated: true) return } // Prompt the user to save changes. let alertController = MDCAlertController(title: String.editExperimentUnsavedChangesDialogTitle, message: String.editExperimentUnsavedChangesDialogMessage) let saveAction = MDCAlertAction(title: String.btnEditExperimentSaveChanges) { _ in self.saveButtonPressed() } let deleteAction = MDCAlertAction(title: String.btnEditExperimentDiscardChanges) { _ in self.dismiss(animated: true) } alertController.addAction(saveAction) alertController.addAction(deleteAction) present(alertController, animated: true) } @objc private func saveButtonPressed() { if experiment.title != trimmedTitleOrDefault() { delegate?.editExperimentViewControllerDidSetTitle(trimmedTitleOrDefault(), forExperimentID: experiment.ID) } // Only save a new cover image if the photo changed. if existingPhoto != photoPicker.photo { if let (imageData, metadata) = selectedImageInfo { delegate?.editExperimentViewControllerDidSetCoverImageData(imageData, metadata: metadata, forExperimentID: experiment.ID) } else { delegate?.editExperimentViewControllerDidSetCoverImageData(nil, metadata: nil, forExperimentID: experiment.ID) } } dismiss(animated: true) } }
apache-2.0
39fc707112f594d5f96c7536a6175aa4
36.817629
105
0.697396
5.60703
false
false
false
false
jldemolina/CookieCrush
Cookie Crush/GameScene.swift
1
13630
// // GameScene.swift // Cookie Crush // // Created by Jose Luis Molina on 27/1/15. // Copyright (c) 2015 Jose Luis Molina. All rights reserved. // import SpriteKit class GameScene: SKScene { var level: Level! let TileWidth: CGFloat = 32.0 let TileHeight: CGFloat = 36.0 let gameLayer = SKNode() let cookiesLayer = SKNode() let tilesLayer = SKNode() var selectionSprite = SKSpriteNode() var swipeFromColumn: Int? var swipeFromRow: Int? var swipeHandler: ((Swap) -> ())? let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false) let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false) let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false) let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false) let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false) required init?(coder aDecoder: NSCoder) { fatalError("init(coder) is not used in this app") } override init(size: CGSize) { super.init(size: size) swipeFromColumn = nil swipeFromRow = nil anchorPoint = CGPoint(x: 0.5, y: 0.5) let background = SKSpriteNode(imageNamed: "Background") addChild(background) addChild(gameLayer) let layerPosition = CGPoint( x: -TileWidth * CGFloat(NumColumns) / 2, y: -TileHeight * CGFloat(NumRows) / 2) tilesLayer.position = layerPosition gameLayer.addChild(tilesLayer) cookiesLayer.position = layerPosition gameLayer.addChild(cookiesLayer) gameLayer.hidden = true SKLabelNode(fontNamed: "GillSans-BoldItalic") } func addSpritesForCookies(cookies: Set<Cookie>) { for cookie in cookies { let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName) sprite.position = pointForColumn(cookie.column, row:cookie.row) cookiesLayer.addChild(sprite) cookie.sprite = sprite sprite.alpha = 0 sprite.xScale = 0.5 sprite.yScale = 0.5 sprite.runAction( SKAction.sequence([ SKAction.waitForDuration(0.25, withRange: 0.5), SKAction.group([ SKAction.fadeInWithDuration(0.25), SKAction.scaleTo(1.0, duration: 0.25) ]) ])) } } func addTiles() { for row in 0..<NumRows { for column in 0..<NumColumns { if let tile = level.tileAtColumn(column, row: row) { let tileNode = SKSpriteNode(imageNamed: "Tile") tileNode.position = pointForColumn(column, row: row) tilesLayer.addChild(tileNode) } } } } func pointForColumn(column: Int, row: Int) -> CGPoint { return CGPoint( x: CGFloat(column)*TileWidth + TileWidth/2, y: CGFloat(row)*TileHeight + TileHeight/2) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch let location = touch.locationInNode(cookiesLayer) let (success, column, row) = convertPoint(location) if success { if let cookie = level.cookieAtColumn(column, row: row) { showSelectionIndicatorForCookie(cookie) swipeFromColumn = column swipeFromRow = row } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { if swipeFromColumn == nil { return } let touch = touches.anyObject() as UITouch let location = touch.locationInNode(cookiesLayer) let (success, column, row) = convertPoint(location) if success { var horzDelta = 0, vertDelta = 0 if column < swipeFromColumn! { // swipe left horzDelta = -1 } else if column > swipeFromColumn! { // swipe right horzDelta = 1 } else if row < swipeFromRow! { // swipe down vertDelta = -1 } else if row > swipeFromRow! { // swipe up vertDelta = 1 } if horzDelta != 0 || vertDelta != 0 { trySwapHorizontal(horzDelta, vertical: vertDelta) hideSelectionIndicator() swipeFromColumn = nil } } } func convertPoint(point: CGPoint) -> (success: Bool, column: Int, row: Int) { if point.x >= 0 && point.x < CGFloat(NumColumns)*TileWidth && point.y >= 0 && point.y < CGFloat(NumRows)*TileHeight { return (true, Int(point.x / TileWidth), Int(point.y / TileHeight)) } else { return (false, 0, 0) // invalid location } } func trySwapHorizontal(horzDelta: Int, vertical vertDelta: Int) { // 1 let toColumn = swipeFromColumn! + horzDelta let toRow = swipeFromRow! + vertDelta // 2 if toColumn < 0 || toColumn >= NumColumns { return } if toRow < 0 || toRow >= NumRows { return } // 3 if let toCookie = level.cookieAtColumn(toColumn, row: toRow) { if let fromCookie = level.cookieAtColumn(swipeFromColumn!, row: swipeFromRow!) { // 4 if let handler = swipeHandler { let swap = Swap(cookieA: fromCookie, cookieB: toCookie) handler(swap) } } } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { if selectionSprite.parent != nil && swipeFromColumn != nil { hideSelectionIndicator() } swipeFromColumn = nil swipeFromRow = nil } override func touchesCancelled(touches: NSSet, withEvent event: UIEvent) { touchesEnded(touches, withEvent: event) } func animateSwap(swap: Swap, completion: () -> ()) { let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.3 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut spriteA.runAction(moveA, completion: completion) let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteB.runAction(moveB) runAction(swapSound) } func animateInvalidSwap(swap: Swap, completion: () -> ()) { let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.2 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteA.runAction(SKAction.sequence([moveA, moveB]), completion: completion) spriteB.runAction(SKAction.sequence([moveB, moveA])) runAction(invalidSwapSound) } func showSelectionIndicatorForCookie(cookie: Cookie) { if selectionSprite.parent != nil { selectionSprite.removeFromParent() } if let sprite = cookie.sprite { let texture = SKTexture(imageNamed: cookie.cookieType.highlightedSpriteName) selectionSprite.size = texture.size() selectionSprite.runAction(SKAction.setTexture(texture)) sprite.addChild(selectionSprite) selectionSprite.alpha = 1.0 } } func hideSelectionIndicator() { selectionSprite.runAction(SKAction.sequence([ SKAction.fadeOutWithDuration(0.3), SKAction.removeFromParent()])) } func animateMatchedCookies(chains: Set<Chain>, completion: () -> ()) { for chain in chains { animateScoreForChain(chain) for cookie in chain.cookies { if let sprite = cookie.sprite { if sprite.actionForKey("removing") == nil { let scaleAction = SKAction.scaleTo(0.1, duration: 0.3) scaleAction.timingMode = .EaseOut sprite.runAction(SKAction.sequence([scaleAction, SKAction.removeFromParent()]), withKey:"removing") } } } } runAction(matchSound) runAction(SKAction.waitForDuration(0.3), completion: completion) } func animateFallingCookies(columns: [[Cookie]], completion: () -> ()) { // 1 var longestDuration: NSTimeInterval = 0 for array in columns { for (idx, cookie) in enumerate(array) { let newPosition = pointForColumn(cookie.column, row: cookie.row) // 2 let delay = 0.05 + 0.15*NSTimeInterval(idx) // 3 let sprite = cookie.sprite! let duration = NSTimeInterval(((sprite.position.y - newPosition.y) / TileHeight) * 0.1) // 4 longestDuration = max(longestDuration, duration + delay) // 5 let moveAction = SKAction.moveTo(newPosition, duration: duration) moveAction.timingMode = .EaseOut sprite.runAction( SKAction.sequence([ SKAction.waitForDuration(delay), SKAction.group([moveAction, fallingCookieSound])])) } } // 6 runAction(SKAction.waitForDuration(longestDuration), completion: completion) } func animateNewCookies(columns: [[Cookie]], completion: () -> ()) { // 1 var longestDuration: NSTimeInterval = 0 for array in columns { // 2 let startRow = array[0].row + 1 for (idx, cookie) in enumerate(array) { // 3 let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName) sprite.position = pointForColumn(cookie.column, row: startRow) cookiesLayer.addChild(sprite) cookie.sprite = sprite // 4 let delay = 0.1 + 0.2 * NSTimeInterval(array.count - idx - 1) // 5 let duration = NSTimeInterval(startRow - cookie.row) * 0.1 longestDuration = max(longestDuration, duration + delay) // 6 let newPosition = pointForColumn(cookie.column, row: cookie.row) let moveAction = SKAction.moveTo(newPosition, duration: duration) moveAction.timingMode = .EaseOut sprite.alpha = 0 sprite.runAction( SKAction.sequence([ SKAction.waitForDuration(delay), SKAction.group([ SKAction.fadeInWithDuration(0.05), moveAction, addCookieSound]) ])) } } // 7 runAction(SKAction.waitForDuration(longestDuration), completion: completion) } func animateScoreForChain(chain: Chain) { // Figure out what the midpoint of the chain is. let firstSprite = chain.firstCookie().sprite! let lastSprite = chain.lastCookie().sprite! let centerPosition = CGPoint( x: (firstSprite.position.x + lastSprite.position.x)/2, y: (firstSprite.position.y + lastSprite.position.y)/2 - 8) // Add a label for the score that slowly floats up. let scoreLabel = SKLabelNode(fontNamed: "GillSans-BoldItalic") scoreLabel.fontSize = 16 scoreLabel.text = NSString(format: "%ld", chain.score) scoreLabel.position = centerPosition scoreLabel.zPosition = 300 cookiesLayer.addChild(scoreLabel) let moveAction = SKAction.moveBy(CGVector(dx: 0, dy: 3), duration: 0.7) moveAction.timingMode = .EaseOut scoreLabel.runAction(SKAction.sequence([moveAction, SKAction.removeFromParent()])) } func animateGameOver(completion: () -> ()) { let action = SKAction.moveBy(CGVector(dx: 0, dy: -size.height), duration: 0.3) action.timingMode = .EaseIn gameLayer.runAction(action, completion: completion) } func animateBeginGame(completion: () -> ()) { gameLayer.hidden = false gameLayer.position = CGPoint(x: 0, y: size.height) let action = SKAction.moveBy(CGVector(dx: 0, dy: -size.height), duration: 0.3) action.timingMode = .EaseOut gameLayer.runAction(action, completion: completion) } func removeAllCookieSprites() { cookiesLayer.removeAllChildren() } }
apache-2.0
45de6afcf34d21fda03c6b5cf8998b8d
36.243169
103
0.556713
5.095327
false
false
false
false
jkereako/NSProgressExample
Source/FileListTableViewController.swift
1
4848
// // FileListTableViewController.swift // NSProgressExample // // Created by Jeff Kereakoglow on 10/18/16. // Copyright © 2016 Alexis Digital. All rights reserved. // import UIKit fileprivate var FileListTableViewControllerObservationContext = 0 class FileListTableViewController: UITableViewController { fileprivate var networkManager: NetworkManager? fileprivate let cellIdentifier = "cell" fileprivate let observedKeyPath = "fractionCompleted" fileprivate var selectedIndexPath: IndexPath? fileprivate lazy var dataSource: [FileViewModel] = [ FileViewModel(endpoint: .file1MB), FileViewModel(endpoint: .file3MB), FileViewModel(endpoint: .file5MB), FileViewModel(endpoint: .file10MB), FileViewModel(endpoint: .file20MB), FileViewModel(endpoint: .file30MB) ] } // MARK: - Table view data source extension FileListTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) let viewModel = dataSource[indexPath.row] cell.textLabel?.text = viewModel.endpoint.description cell.detailTextLabel?.text = viewModel.detail cell.accessoryType = viewModel.state == .saved ? .checkmark : .none return cell } } // MARK: - Table view delegate extension FileListTableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) // Commence downloading if the file isn't already saved. guard self.dataSource[indexPath.row].state == .empty else { return } selectedIndexPath = indexPath networkManager = NetworkManager(endpoint: dataSource[indexPath.row].endpoint) { url in OperationQueue.main.addOperation { [unowned self] in // REVIEW: This crashes when tapping on multiple rows too quickly self.networkManager?.progress.removeObserver( self, forKeyPath: self.observedKeyPath, context: &FileListTableViewControllerObservationContext ) self.dataSource[indexPath.row] = FileViewModel( endpoint: self.dataSource[indexPath.row].endpoint, detail: FileState.saved.description, state: .saved ) tableView.beginUpdates() tableView.reloadRows(at: [indexPath], with: .fade) tableView.endUpdates() } } networkManager?.progress.addObserver( self, forKeyPath: observedKeyPath, options: [], context: &FileListTableViewControllerObservationContext ) networkManager?.download() self.dataSource[indexPath.row] = FileViewModel( endpoint: self.dataSource[indexPath.row].endpoint, state: .downloading ) } } // MARK: - KVO extension FileListTableViewController { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard context == &FileListTableViewControllerObservationContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } guard let progress = object as? Progress else { assertionFailure("Expected a Progress object") return } // Update the UI OperationQueue.main.addOperation { [unowned self] in guard let indexPath = self.selectedIndexPath else { assertionFailure("`selectedIndexPath` is nil") return } let viewModel = self.dataSource[indexPath.row] self.dataSource[indexPath.row] = FileViewModel( endpoint: viewModel.endpoint, detail: progress.localizedAdditionalDescription, state: .downloading ) self.tableView.beginUpdates() self.tableView.reloadRows(at: [indexPath], with: .none) self.tableView.endUpdates() } } }
mit
5845d9f9baa78f039d1a48457ecfb373
35.171642
109
0.611512
5.875152
false
false
false
false
savelii/Swift-cfenv
Sources/CloudFoundryEnv/App.swift
1
1826
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** * See https://docs.run.pivotal.io/devguide/deploy-apps/environment-variable.html#VCAP-APPLICATION. */ public struct App { public struct Limits { let memory: Int let disk: Int let fds: Int public init(memory: Int, disk: Int, fds: Int) { self.memory = memory self.disk = disk self.fds = fds } } public let id: String public let name: String public let uris: [String] public let version: String public let instanceId: String public let instanceIndex: Int public let limits: Limits public let port: Int public let spaceId: String public let startedAtTs: TimeInterval public let startedAt: Date /** * Constructor. */ public init(id: String, name: String, uris: [String], version: String, instanceId: String, instanceIndex: Int, limits: Limits, port: Int, spaceId: String, startedAtTs: TimeInterval, startedAt: Date) { self.id = id self.name = name self.uris = uris self.version = version self.instanceId = instanceId self.instanceIndex = instanceIndex self.limits = limits self.port = port self.spaceId = spaceId self.startedAtTs = startedAtTs self.startedAt = startedAt } }
apache-2.0
0f2221e7f6d5bfb9688ae294e5b52955
26.253731
99
0.697152
4.030905
false
false
false
false
zColdWater/YPCache
YPCache/YPMemoryCache.swift
1
9561
// // YPMemoryCache.swift // YPCache // // Created by Yongpeng.Zhu on 2016/8/26. // Copyright © 2016年 Yongpeng.Zhu. All rights reserved. // import UIKit import Foundation class YPLinkedListNode : NSObject, YPLog { weak var prevNode : YPLinkedListNode? = nil weak var nextNode : YPLinkedListNode? = nil var key : String var value : AnyObject? var time : NSTimeInterval? = 0 init(value: AnyObject?, key: String) { self.value = value self.key = key } deinit { // printLog("YPLinkedListNode release") } } /** YPLinkedList can be viewed as a two-way LRU list */ class YPLinkedList: NSObject, YPLog { typealias Node = YPLinkedListNode var dic = NSMutableDictionary() var totalCount : NSInteger = 0 var first : Node? = nil var last : Node? = nil func insertNodeAtFirst(node:Node) { dic[node.key] = node totalCount = dic.count if first != nil { node.nextNode = first! first!.prevNode = node first = node } else { last = node first = last } } func bringNodeToFirst(node:Node) { if first == node { return } if last == node { last = node.prevNode last!.nextNode = nil } else { node.prevNode!.nextNode = node.nextNode node.nextNode!.prevNode = node.prevNode } node.nextNode = first node.prevNode = nil first!.prevNode = node first = node } func removeNode(node:Node) { dic.removeObjectForKey(node.key) totalCount = dic.count if node.nextNode != nil { node.nextNode!.prevNode = node.prevNode } if node.prevNode != nil { node.prevNode!.nextNode = node.nextNode } if first == node { first = node.nextNode } if last == node { last = node.prevNode } } func removeLastNode() { if last == nil { return } dic.removeObjectForKey(last!.key) totalCount = dic.count if first == last { first = nil last = nil } else { last = last!.prevNode last!.nextNode = nil } return } func removeAll() { totalCount = 0 first = nil last = nil dic = [:] } deinit { printLog("YPLinkedList release") } } public class YPMemoryCache : YPLog { public typealias Completion = (isSuccess: Bool, obj: AnyObject?) -> Void let LRU = YPLinkedList() let queue: dispatch_queue_t = dispatch_queue_create("https://github.com/MLGZ", DISPATCH_QUEUE_SERIAL) let name: String var totalCount: Int { get{ return self.LRU.totalCount } } // MARK: - Property ///============================================================================= /// @name Limit ///============================================================================= var countLimit: NSInteger = NSIntegerMax var ageLimit: NSTimeInterval = DBL_MAX var autoTrimInterval: NSTimeInterval = 5.0 var shouldRemoveAllObjectsOnMemoryWarning: Bool = true var shouldRemoveAllObjectsWhenEnteringBackground: Bool = false // MARK: - Public ///============================================================================= /// @name YPMemoryCache Public API ///============================================================================= init(cacheName: String) { name = cacheName NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YPMemoryCache._appDidReceiveMemoryWarningNotification), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YPMemoryCache._appDidEnterBackgroundNotification), name: UIApplicationDidEnterBackgroundNotification, object: nil) _trimRecursively() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil) LRU.removeAll() print("YPMemoryCache release") } public func containsObjectForKey(key:String) -> Bool { var keyExists: Bool = false objc_sync_enter(self) keyExists = self.LRU.dic[key] != nil objc_sync_exit(self) return keyExists } public func objectForKey(key: String, result:(object:AnyObject?) -> Void) { objc_sync_enter(self) var node: YPLinkedListNode? node = self.LRU.dic[key] as? YPLinkedListNode if node != nil { node!.time! = CACurrentMediaTime() self.LRU.bringNodeToFirst(node!) } dispatch_async(dispatch_get_main_queue(), { result(object: (node != nil) ? node!.value : nil) }) objc_sync_exit(self) } public func setObject(object obj: AnyObject? = nil, forkey key: String, completion: Completion? = nil) { guard obj != nil else { self.removeObjectForKey(key) completion?(isSuccess: false, obj: nil) return } objc_sync_enter(self) var node = self.LRU.dic[key] as? YPLinkedListNode let now = CACurrentMediaTime() if node != nil { node!.time = now node!.value = obj! self.LRU.bringNodeToFirst(node!) } else { node = YPLinkedListNode(value: obj, key: key) node!.time = now self.LRU.insertNodeAtFirst(node!) } if self.LRU.totalCount > self.countLimit { dispatch_sync(self.queue, { self.LRU.removeLastNode() }) } completion?(isSuccess: true, obj: nil) objc_sync_exit(self) } public func removeObjectForKey(key: String) { objc_sync_enter(self) let node = self.LRU.dic[key] as? YPLinkedListNode if node != nil { self.LRU.removeNode(node!) } objc_sync_exit(self) } public func removeAllObjects() { objc_sync_enter(self) self.LRU.removeAll() objc_sync_exit(self) } public func trimToCount(count: NSInteger, completion: (()->Void)? = nil) { self._trimToCount(count, completion: completion) } public func trimToAge(age: NSTimeInterval, completion: (()->Void)? = nil) { self._trimToAge(age, completion: completion) } // MARK: - Private ///============================================================================= /// @name YPMemoryCache trim ///============================================================================= @objc private func _appDidReceiveMemoryWarningNotification() { if self.shouldRemoveAllObjectsOnMemoryWarning { self.removeAllObjects() } } @objc private func _appDidEnterBackgroundNotification() { if self.shouldRemoveAllObjectsWhenEnteringBackground { self.removeAllObjects() } } private func _trimRecursively() { dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(autoTrimInterval) * Int64(NSEC_PER_SEC)), queue, { [weak self] in if self == nil {return} self!._trimToCount(self!.countLimit) self!._trimToAge(self!.ageLimit) self!._trimRecursively() self!.printLog("YPDiskCache object count is :\(self!.totalCount)") }) } private func _trimToCount(countLimit: NSInteger, completion: (()->Void)? = nil) { var finish = false objc_sync_enter(self) if (countLimit == 0) { self.LRU.removeAll() finish = true } else if self.LRU.totalCount <= countLimit { finish = true } objc_sync_exit(self) completion?() if finish {return} while !finish { objc_sync_enter(self) if self.LRU.totalCount > countLimit { self.LRU.removeLastNode() } else { finish = true completion?() } objc_sync_exit(self) } } private func _trimToAge(ageLimit: NSTimeInterval, completion: (()->Void)? = nil) { var finish = false let now = CACurrentMediaTime() objc_sync_enter(self) if ageLimit <= 0 { self.LRU.removeAll() finish = true } else if (self.LRU.last == nil || (now - self.LRU.last!.time!) <= ageLimit ) { finish = true } objc_sync_exit(self) completion?() if finish {return} while !finish { objc_sync_enter(self) if self.LRU.last != nil && (now - self.LRU.last!.time!) > ageLimit { self.LRU.removeLastNode() } else { finish = true completion?() } objc_sync_exit(self) } } }
mit
926e67351e95158e16c1541331faedec
27.963636
207
0.522494
4.972945
false
false
false
false
cxpyear/SPDBDemo
spdbapp/spdbapp/Classes/View/BottomBarView.swift
1
2639
// // BottomBarView.swift // spdbapp // // Created by GBTouchG3 on 15/7/27. // Copyright (c) 2015年 shgbit. All rights reserved. // import UIKit class BottomBarView: UIView { @IBOutlet weak var btnBack: UIButton! @IBOutlet weak var btnReconnect: UIButton! @IBOutlet weak var btnUser: UIButton! @IBOutlet weak var lblUserName: UILabel! @IBOutlet weak var btnHelp: UIButton! @IBOutlet weak var btnShare: UIButton! var myTarget = UIViewController() override func awakeFromNib() { super.awakeFromNib() self.hidden = true self.btnReconnect.addTarget(self, action: "getReconn", forControlEvents: UIControlEvents.TouchUpInside) self.lblUserName.text = appManager.appGBUser.name Poller().start(self, method: "checkstatus:", timerInter: 5.0) if appManager.netConnect == true { self.btnReconnect.hidden = true } } func checkstatus(timer: NSTimer){ self.btnReconnect.hidden = (appManager.netConnect == true) ? true : false } //页面下方的“重连”按钮出发的事件 func getReconn(){ appManager.starttimer() } func getBottomInstance(owner: NSObject) -> BottomBarView { var view = NSBundle.mainBundle().loadNibNamed("BottomBarView", owner: owner, options: nil)[0] as! BottomBarView var p = owner as! UIViewController println("owner = \(p)") view.frame = CGRectMake(0, p.view.frame.height - 49, p.view.frame.width, 49) myTarget = p view.btnShare.addTarget(p, action: "shareClick", forControlEvents: UIControlEvents.TouchUpInside) view.btnHelp.addTarget(p, action: "helpClick", forControlEvents: UIControlEvents.TouchUpInside) view.btnBack.addTarget(p, action: "backClick", forControlEvents: UIControlEvents.TouchUpInside) // println("self.btnshare = \(btnShare.frame)") // self.btnShare.addTarget(p, action: "shareClick:", forControlEvents: UIControlEvents.TouchUpInside) // p.view.addSubview(view) return view } func hideOrShowBottomBar(gesture: UITapGestureRecognizer){ self.hidden = !self.hidden } // func shareClick(sender: UIButton){ // var shareVC = ShareViewController() // println("myTarget = \(myTarget)") //// var myTargetVC = myTarget //// println("myTargetVC = \(myTargetVC)") // myTarget.presentViewController(shareVC, animated: true, completion: nil) // } }
bsd-3-clause
ec96b6bff1740f37a6959a97786fc96a
28.269663
119
0.626488
4.348915
false
false
false
false
LPinguo/Showlive
Showlive/Showlive/Classes/Tools/Common.swift
1
324
// // Common.swift // Showlive // // Created by LPGuo on 2016/12/16. // Copyright © 2016年 apple. All rights reserved. // import UIKit let kStatusBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabbarH : CGFloat = 44 let kScreenW = UIScreen.main.bounds.width let kScreenH = UIScreen.main.bounds.height
mit
192acd982ef12c3d161c4ade5ecbeba0
17.882353
49
0.713396
3.451613
false
false
false
false
daltoniam/Jazz
Sources/ButtonView.swift
1
4308
// // ButtonView.swift // // Created by Dalton Cherry on 3/11/15. // Copyright (c) 2015 Vluxe. All rights reserved. // import UIKit open class ButtonView: ShapeView { fileprivate var highlighted = false open var isHightlighted: Bool {return highlighted} open var highlightColor: UIColor? open var textLabel: UILabel = UILabel() open var enabled: Bool = true { didSet { textLabel.isEnabled = enabled } } open var ripple = false open var didTap: (() -> Void)? //standard view init method override public init(frame: CGRect) { super.init(frame: frame) } //standard view init method required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(layout: ShapePath) { super.init(layout: layout) } //setup the properties override func commonInit() { super.commonInit() layer.masksToBounds = true autoresizesSubviews = true textLabel.backgroundColor = UIColor.clear textLabel.textAlignment = .center textLabel.contentMode = .center textLabel.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin] addSubview(textLabel) let tap = UITapGestureRecognizer(target: self, action:#selector(handleTap(_:))) tap.numberOfTapsRequired = 1 addGestureRecognizer(tap) } //layout the subviews open override func layoutSubviews() { super.layoutSubviews() textLabel.frame = bounds } //process touches to known when to highlight the button override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) if enabled { highlighted = true drawPath() } } //touch ended, remove hightlight open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) if enabled { highlighted = false drawPath() } } //touch cancelled, remove hightlight open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent!) { super.touchesCancelled(touches, with: event) if enabled { highlighted = false drawPath() } } //highlight support override open func drawPath() { super.drawPath() if highlighted && !ripple { guard let c = highlightColor else {return} layer.fillColor = c.cgColor } } //handle the gesture func handleTap(_ recognizer: UITapGestureRecognizer) { if !enabled { return } if ripple { drawRipple(recognizer) } else if let handler = didTap { handler() } } //draw the ripple effect on the button func drawRipple(_ recognizer: UITapGestureRecognizer) { let rippleLayer = CAShapeLayer() let point = recognizer.location(in: self) let p: CGFloat = frame.size.height rippleLayer.fillColor = highlightColor?.cgColor rippleLayer.path = UIBezierPath(roundedRect: CGRect(x: point.x-(p/2), y: point.y-(p/2), width: p, height: p), cornerRadius: p/2).cgPath rippleLayer.opacity = 0.8 layer.addSublayer(rippleLayer) addSubview(textLabel) let dur = 0.3 let animation = Jazz.createAnimation(dur, key: "opacity") animation.fromValue = 0.8 animation.toValue = 0 let move = Jazz.createAnimation(dur, key: "path") move.fromValue = rippleLayer.path move.toValue = layer.path CATransaction.begin() CATransaction.setCompletionBlock { rippleLayer.removeFromSuperlayer() if let handler = self.didTap { handler() } } rippleLayer.add(animation, forKey: Jazz.oneShotKey()) rippleLayer.add(move, forKey: Jazz.oneShotKey()) rippleLayer.opacity = 0 rippleLayer.path = layer.path CATransaction.commit() } }
apache-2.0
e15d87c0455bf79aaf28b8d3be222918
30.676471
185
0.613278
5.015134
false
false
false
false
Henryforce/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorAnimationBallGridBeat.swift
1
3173
// // KRActivityIndicatorAnimationBallGridBeat.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // 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 Cocoa class KRActivityIndicatorAnimationBallGridBeat: KRActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - circleSpacing * 2) / 3 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let durations = [0.96, 0.93, 1.19, 1.13, 1.34, 0.94, 1.2, 0.82, 1.19] let beginTime = CACurrentMediaTime() let beginTimes = [0.36, 0.4, 0.68, 0.41, 0.71, -0.15, -0.12, 0.01, 0.32] let timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default) // Animation let animation = CAKeyframeAnimation(keyPath: "opacity") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.7, 1] animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 3 { for j in 0 ..< 3 { let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j), y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), width: circleSize, height: circleSize) animation.duration = durations[3 * i + j] animation.beginTime = beginTime + beginTimes[3 * i + j] circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } } }
mit
dff04c50e1c31d525576b0dfbaca3933
44.985507
137
0.645446
4.578644
false
false
false
false
appsembler/edx-app-ios
Source/VideoBlockViewController.swift
1
10470
// // VideoBlockViewController.swift // edX // // Created by Akiva Leffert on 5/6/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import MediaPlayer import UIKit private let StandardVideoAspectRatio : CGFloat = 0.6 class VideoBlockViewController : UIViewController, CourseBlockViewController, OEXVideoPlayerInterfaceDelegate, StatusBarOverriding, InterfaceOrientationOverriding { typealias Environment = protocol<DataManagerProvider, OEXInterfaceProvider, ReachabilityProvider> let environment : Environment let blockID : CourseBlockID? let courseQuerier : CourseOutlineQuerier let videoController : OEXVideoPlayerInterface let loader = BackedStream<CourseBlock>() var rotateDeviceMessageView : IconMessageView? var contentView : UIView? let loadController : LoadStateViewController init(environment : Environment, blockID : CourseBlockID?, courseID: String) { self.blockID = blockID self.environment = environment courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID) videoController = OEXVideoPlayerInterface() loadController = LoadStateViewController() super.init(nibName: nil, bundle: nil) addChildViewController(videoController) videoController.didMoveToParentViewController(self) videoController.delegate = self addLoadListener() } var courseID : String { return courseQuerier.courseID } required init?(coder aDecoder: NSCoder) { // required by the compiler because UIViewController implements NSCoding, // but we don't actually want to serialize these things fatalError("init(coder:) has not been implemented") } func addLoadListener() { loader.listen (self, success : { [weak self] block in if let video = block.type.asVideo where video.isYoutubeVideo, let url = block.blockURL { self?.showYoutubeMessage(url) } else if let video = self?.environment.interface?.stateForVideoWithID(self?.blockID, courseID : self?.courseID) where block.type.asVideo?.preferredEncoding != nil { self?.showLoadedBlock(block, forVideo: video) } else { self?.showError(nil) } }, failure : {[weak self] error in self?.showError(error) } ) } override func viewDidLoad() { super.viewDidLoad() contentView = UIView(frame: CGRectZero) view.addSubview(contentView!) loadController.setupInController(self, contentView : contentView!) contentView!.addSubview(videoController.view) videoController.view.translatesAutoresizingMaskIntoConstraints = false videoController.fadeInOnLoad = false rotateDeviceMessageView = IconMessageView(icon: .RotateDevice, message: Strings.rotateDevice) contentView!.addSubview(rotateDeviceMessageView!) view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor() view.setNeedsUpdateConstraints() videoController.hidesNextPrev = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.loadVideoIfNecessary() } override func viewDidAppear(animated : Bool) { // There's a weird OS bug where the bottom layout guide doesn't get set properly until // the layout cycle after viewDidAppear so cause a layout cycle self.view.setNeedsUpdateConstraints() self.view.updateConstraintsIfNeeded() self.view.setNeedsLayout() self.view.layoutIfNeeded() super.viewDidAppear(animated) guard canDownloadVideo() else { guard let video = self.environment.interface?.stateForVideoWithID(self.blockID, courseID : self.courseID) where video.downloadState == .Complete else { self.showOverlayMessage(Strings.noWifiMessage) return } return } } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) videoController.setAutoPlaying(false) } private func loadVideoIfNecessary() { if !loader.hasBacking { loader.backWithStream(courseQuerier.blockWithID(self.blockID).firstSuccess()) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updateViewConstraints() } override func updateViewConstraints() { if self.isVerticallyCompact() { applyLandscapeConstraints() } else{ applyPortraitConstraints() } super.updateViewConstraints() } private func applyPortraitConstraints() { contentView?.snp_remakeConstraints {make in make.edges.equalTo(view) } videoController.height = view.bounds.size.width * StandardVideoAspectRatio videoController.width = view.bounds.size.width videoController.view.snp_remakeConstraints {make in make.leading.equalTo(contentView!) make.trailing.equalTo(contentView!) if #available(iOS 9, *) { make.top.equalTo(self.topLayoutGuide.bottomAnchor) } else { make.top.equalTo(self.snp_topLayoutGuideBottom) } make.height.equalTo(view.bounds.size.width * StandardVideoAspectRatio) } rotateDeviceMessageView?.snp_remakeConstraints {make in make.top.equalTo(videoController.view.snp_bottom) make.leading.equalTo(contentView!) make.trailing.equalTo(contentView!) // There's a weird OS bug where the bottom layout guide doesn't get set properly until // the layout cycle after viewDidAppear, so use the parent in the mean time if #available(iOS 9, *) { make.bottom.equalTo(self.bottomLayoutGuide.topAnchor) } else { make.bottom.equalTo(self.snp_bottomLayoutGuideTop) } } } private func applyLandscapeConstraints() { contentView?.snp_remakeConstraints {make in make.edges.equalTo(view) } let playerHeight = view.bounds.size.height - (navigationController?.toolbar.bounds.height ?? 0) videoController.height = playerHeight videoController.width = view.bounds.size.width videoController.view.snp_remakeConstraints {make in make.leading.equalTo(contentView!) make.trailing.equalTo(contentView!) if #available(iOS 9, *) { make.top.equalTo(self.topLayoutGuide.bottomAnchor) } else { make.top.equalTo(self.snp_topLayoutGuideBottom) } make.height.equalTo(playerHeight) } rotateDeviceMessageView?.snp_remakeConstraints {make in make.height.equalTo(0.0) } } func movieTimedOut() { if let controller = videoController.moviePlayerController where controller.fullscreen { UIAlertView(title: Strings.videoContentNotAvailable, message: "", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: Strings.close).show() } else { self.showOverlayMessage(Strings.timeoutCheckInternetConnection) } } private func showError(error : NSError?) { loadController.state = LoadState.failed(error, icon: .UnknownError, message: Strings.videoContentNotAvailable) } private func showYoutubeMessage(url: NSURL) { let buttonInfo = MessageButtonInfo(title: Strings.Video.viewOnYoutube) { if UIApplication.sharedApplication().canOpenURL(url){ UIApplication.sharedApplication().openURL(url) } } loadController.state = LoadState.empty(icon: .CourseModeVideo, message: Strings.Video.onlyOnYoutube, attributedMessage: nil, accessibilityMessage: nil, buttonInfo: buttonInfo) } private func showLoadedBlock(block : CourseBlock, forVideo video: OEXHelperVideoDownload) { navigationItem.title = block.displayName dispatch_async(dispatch_get_main_queue()) { self.loadController.state = .Loaded } videoController.playVideoFor(video) } private func canDownloadVideo() -> Bool { let hasWifi = environment.reachability.isReachableViaWiFi() ?? false let onlyOnWifi = environment.dataManager.interface?.shouldDownloadOnlyOnWifi ?? false return !onlyOnWifi || hasWifi } override func childViewControllerForStatusBarStyle() -> UIViewController? { return videoController } override func childViewControllerForStatusBarHidden() -> UIViewController? { return videoController } override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { guard let videoPlayer = videoController.moviePlayerController else { return } if videoPlayer.fullscreen { if newCollection.verticalSizeClass == .Regular { videoPlayer.setFullscreen(false, withOrientation: self.currentOrientation()) } else { videoPlayer.setFullscreen(true, withOrientation: self.currentOrientation()) } } } func videoPlayerTapped(sender: UIGestureRecognizer) { guard let videoPlayer = videoController.moviePlayerController else { return } if self.isVerticallyCompact() && !videoPlayer.fullscreen{ videoPlayer.setFullscreen(true, withOrientation: self.currentOrientation()) } } }
apache-2.0
54209243709663d3ec7e4f80ce7b0e62
35.354167
183
0.626361
5.806988
false
false
false
false
suosuopuo/SwiftyAlgorithm
SwiftyAlgorithm/List.swift
1
8146
// // List.swift // SwiftyAlgorithm // // Created by suosuopuo on 2017/10/23. // Copyright © 2017年 shellpanic. All rights reserved. // import Foundation public final class List<T> { public class ListNode<T> { var value: T var next: ListNode<T>? weak var previous: ListNode<T>? public init(value: T) { self.value = value } } public typealias Node = ListNode<T> private(set) var count: Int = 0 private var head: Node? private var tail: Node? public var isEmpty: Bool { return head == nil } // MARK: - Visit public var first: Node? { return head } public var last: Node? { return tail } public func node(atIndex index: Int) -> Node? { if index < 0 || index >= count { return nil } var node = head var i = index while node != nil { if i == 0 { return node } i -= 1 node = node!.next } return nil } public subscript(index: Int) -> T { let node = self.node(atIndex: index) assert(node != nil, "The `index` is out of bounds!") return node!.value } // MARK: - Append private func appendDirect(_ node: Node) { if tail == nil { head = node tail = node } else { node.previous = tail tail?.next = node tail = node } count += 1 } public func append(_ node: Node) { let newNode = Node(value: node.value) self.appendDirect(newNode) } public func append(_ value: T) { let newNode = Node(value: value) self.appendDirect(newNode) } public func append(_ list: List) { var nodeToCopy = list.head while let node = nodeToCopy { self.append(node) nodeToCopy = node.next } } // MARK: - Prepend private func prependDirect(_ node: Node) { if head == nil { head = node tail = node } else { node.next = head head?.previous = node head = node } count += 1 } public func prepend(_ node: Node) { let newNode = Node(value: node.value) self.prependDirect(newNode) } public func prepend(_ value: T) { let newNode = Node(value: value) self.prependDirect(newNode) } public func prepend(_ list: List) { var nodeToCopy = list.tail while let node = nodeToCopy { self.prepend(node) nodeToCopy = node.previous } } // MARK: - Insert private func nodesBeforeAndAfter(index: Int) -> (Node?, Node?) { assert(index >= 0, "Index is out of bounds!") var i = index var next = head var prev: Node? while next != nil && i > 0 { i -= 1 prev = next next = next!.next } assert(i == 0, "Index is out of bounds!") // if > 0, then specified index was too large return (prev, next) } private func insertDirect(_ node: Node, atIndex index: Int) { let (prev, next) = nodesBeforeAndAfter(index: index) node.previous = prev node.next = next prev?.next = node next?.previous = node if prev == nil { head = node } if next == nil { tail = node } count += 1 } public func insert(_ value: T, atIndex index: Int) { let newNode = Node(value: value) self.insertDirect(newNode, atIndex: index) } public func insert(_ node: Node, atIndex index: Int) { let newNode = ListNode(value: node.value) self.insertDirect(newNode, atIndex: index) } public func insert(_ list: List, atIndex index: Int) { if list.isEmpty { return } var (prev, next) = nodesBeforeAndAfter(index: index) var nodeToCopy = list.head var newNode: Node? while let node = nodeToCopy { newNode = Node(value: node.value) newNode?.previous = prev prev?.next = newNode if prev == nil { self.head = newNode } nodeToCopy = nodeToCopy?.next prev = newNode self.count += 1 } prev?.next = next next?.previous = prev if next == nil { self.tail = prev } } // MARK: - Remove public func removeAll() { count = 0 head = nil tail = nil } @discardableResult public func remove(node: Node) -> T { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } if let next = next { next.previous = prev } else { tail = prev } node.previous = nil node.next = nil count -= 1 return node.value } @discardableResult public func removeLast() -> T? { guard let node = last else { return nil } return remove(node: node) } @discardableResult public func removeFirst() -> T? { guard let node = first else { return nil } return remove(node: node) } @discardableResult public func remove(atIndex index: Int) -> T? { guard let node = self.node(atIndex: index) else { return nil } return remove(node: node) } } extension List: CustomStringConvertible { public var description: String { var s = "[" var node = head while node != nil { s += "\(node!.value)" node = node!.next if node != nil { s += ", " } } return s + "]" } } extension List { public func reverse() { var node = head tail = node while let currentNode = node { node = currentNode.next swap(&currentNode.next, &currentNode.previous) head = currentNode } } } extension List { public func map<U>(transform: (T) -> U) -> List<U> { let result = List<U>() var node = head while node != nil { result.append(transform(node!.value)) node = node!.next } return result } public func mapArray<U>(transform: (T) -> U) -> Array<U> { var result = Array<U>() var node = head while node != nil { result.append(transform(node!.value)) node = node!.next } return result } public func filter(predicate: (T) -> Bool) -> List<T> { let result = List<T>() var node = head while node != nil { if predicate(node!.value) { result.append(node!.value) } node = node!.next } return result } } extension List { public convenience init(array: Array<T>) { self.init() for element in array { self.append(element) } } } extension List: ExpressibleByArrayLiteral { public convenience init(arrayLiteral elements: T...) { self.init() for element in elements { self.append(element) } } } extension List: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() let arr = self.mapArray { $0 } try container.encode(arr) } public convenience init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() let arr = try container.decode([T].self) self.init(array: arr) } }
mit
f296f5c41bc99e22bb61064ed52b58db
22.466859
96
0.489746
4.523889
false
false
false
false
enstulen/ARKitAnimation
Pods/SwiftCharts/SwiftCharts/AxisValues/ChartAxisValueFloat.swift
1
1210
// // ChartAxisValueFloat.swift // swift_charts // // Created by ischuetz on 15/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit @available(*, deprecated: 0.2.5, message: "use ChartAxisValueDouble instead") open class ChartAxisValueFloat: ChartAxisValue { open let formatter: NumberFormatter open var float: CGFloat { return CGFloat(scalar) } public init(_ float: CGFloat, formatter: NumberFormatter = ChartAxisValueFloat.defaultFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.formatter = formatter super.init(scalar: Double(float), labelSettings: labelSettings) } override open func copy(_ scalar: Double) -> ChartAxisValueFloat { return ChartAxisValueFloat(CGFloat(scalar), formatter: formatter, labelSettings: labelSettings) } public static var defaultFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.maximumFractionDigits = 2 return formatter }() // MARK: CustomStringConvertible override open var description: String { return formatter.string(from: NSNumber(value: Float(float)))! } }
mit
90a65d31a8873548c4f6a56d58d0f3d1
29.25
160
0.699174
5.17094
false
false
false
false
thomasvl/swift-protobuf
Sources/SwiftProtobufCore/Message+BinaryAdditions.swift
2
6146
// Sources/SwiftProtobuf/Message+BinaryAdditions.swift - Per-type binary coding // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Extensions to `Message` to provide binary coding and decoding. /// // ----------------------------------------------------------------------------- import Foundation /// Binary encoding and decoding methods for messages. extension Message { /// Returns a `Data` value containing the Protocol Buffer binary format /// serialization of the message. /// /// - Parameters: /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - Returns: A `Data` value containing the binary serialization of the /// message. /// - Throws: `BinaryEncodingError` if encoding fails. public func serializedData(partial: Bool = false) throws -> Data { if !partial && !isInitialized { throw BinaryEncodingError.missingRequiredFields } let requiredSize = try serializedDataSize() var data = Data(count: requiredSize) try data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in if let baseAddress = body.baseAddress, body.count > 0 { var visitor = BinaryEncodingVisitor(forWritingInto: baseAddress) try traverse(visitor: &visitor) // Currently not exposing this from the api because it really would be // an internal error in the library and should never happen. assert(requiredSize == visitor.encoder.distance(pointer: baseAddress)) } } return data } /// Returns the size in bytes required to encode the message in binary format. /// This is used by `serializedData()` to precalculate the size of the buffer /// so that encoding can proceed without bounds checks or reallocation. internal func serializedDataSize() throws -> Int { // Note: since this api is internal, it doesn't currently worry about // needing a partial argument to handle proto2 syntax required fields. // If this become public, it will need that added. var visitor = BinaryEncodingSizeVisitor() try traverse(visitor: &visitor) return visitor.serializedSize } /// Creates a new message by decoding the given `SwiftProtobufContiguousBytes` value /// containing a serialized message in Protocol Buffer binary format. /// /// - Parameters: /// - serializedBytes: The binary-encoded message data to decode. /// - extensions: An `ExtensionMap` used to look up and decode any /// extensions in this message or messages nested within this message's /// fields. /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - options: The BinaryDecodingOptions to use. /// - Throws: `BinaryDecodingError` if decoding fails. @inlinable public init<Bytes: SwiftProtobufContiguousBytes>( serializedBytes bytes: Bytes, extensions: ExtensionMap? = nil, partial: Bool = false, options: BinaryDecodingOptions = BinaryDecodingOptions() ) throws { self.init() try merge(serializedBytes: bytes, extensions: extensions, partial: partial, options: options) } /// Updates the message by decoding the given `SwiftProtobufContiguousBytes` value /// containing a serialized message in Protocol Buffer binary format into the /// receiver. /// /// - Note: If this method throws an error, the message may still have been /// partially mutated by the binary data that was decoded before the error /// occurred. /// /// - Parameters: /// - serializedBytes: The binary-encoded message data to decode. /// - extensions: An `ExtensionMap` used to look up and decode any /// extensions in this message or messages nested within this message's /// fields. /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - options: The BinaryDecodingOptions to use. /// - Throws: `BinaryDecodingError` if decoding fails. @inlinable public mutating func merge<Bytes: SwiftProtobufContiguousBytes>( serializedBytes bytes: Bytes, extensions: ExtensionMap? = nil, partial: Bool = false, options: BinaryDecodingOptions = BinaryDecodingOptions() ) throws { try bytes.withUnsafeBytes { (body: UnsafeRawBufferPointer) in try _merge(rawBuffer: body, extensions: extensions, partial: partial, options: options) } } // Helper for `merge()`s to keep the Decoder internal to SwiftProtobuf while // allowing the generic over `SwiftProtobufContiguousBytes` to get better codegen from the // compiler by being `@inlinable`. For some discussion on this see // https://github.com/apple/swift-protobuf/pull/914#issuecomment-555458153 @usableFromInline internal mutating func _merge( rawBuffer body: UnsafeRawBufferPointer, extensions: ExtensionMap?, partial: Bool, options: BinaryDecodingOptions ) throws { if let baseAddress = body.baseAddress, body.count > 0 { var decoder = BinaryDecoder(forReadingFrom: baseAddress, count: body.count, options: options, extensions: extensions) try decoder.decodeFullMessage(message: &self) } if !partial && !isInitialized { throw BinaryDecodingError.missingRequiredFields } } }
apache-2.0
1815c58a6eb8e63e7145890a8bb91c32
43.536232
97
0.681744
5.025348
false
false
false
false
gu704823/DYTV
dytv/Pods/LeanCloud/Sources/Storage/Logger.swift
4
852
// // Logger.swift // LeanCloud // // Created by Tang Tianyong on 10/19/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation class Logger { static let defaultLogger = Logger() static let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = NSLocale.current dateFormatter.dateFormat = "yyyy'-'MM'-'dd'.'HH':'mm':'ss'.'SSS" return dateFormatter }() public func log<T>( _ value: @autoclosure () -> T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { let date = Logger.dateFormatter.string(from: Date()) let file = NSURL(string: file)?.lastPathComponent ?? "Unknown" print("[LeanCloud \(date) \(file) #\(line) \(function)]:", value()) } }
mit
f9328a07037d3a58873d6da242759973
24.029412
75
0.591069
4.111111
false
false
false
false
tkremenek/swift
test/Constraints/rdar42750089.swift
35
1145
// RUN: %target-typecheck-verify-swift protocol P : Equatable { associatedtype T = String } struct S : Hashable { var key: String init(_ key: String) { self.key = key } } extension S : ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(value) } } extension S : ExpressibleByStringInterpolation { init(stringInterpolation: DefaultStringInterpolation) { self.key = "foo" } } extension S : P {} struct ConcP<F: P, S: P> : P where F.T == S.T { var lhs: F var rhs: S } struct Z : P { } extension P { func bar() -> Z { fatalError() } static func +<T : P>(lhs: Self, rhs: T) -> ConcP<Self, T> { return ConcP(lhs: lhs, rhs: rhs) } } class Container<V> { var value: V init(_ value: V) { self.value = value } } struct A { enum Value : CustomStringConvertible { case foo, bar var description: String { switch self { case .foo: return "foo" case .bar: return "bar" } } } var value: Container<Value> func foo() { let value = self.value.value _ = S("A") + S("\(value)").bar() + S("B") // Ok } }
apache-2.0
5bccb684a42e98e232405ac367951393
15.357143
61
0.584279
3.280802
false
false
false
false
iewam/GBook
GBook/GBook/AppDelegate.swift
1
3662
// // AppDelegate.swift // GBook // // Created by 马伟 on 2017/6/3. // Copyright © 2017年 马伟. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // config leancloud window = UIWindow(frame: UIScreen.main.bounds) let rankNVC = UINavigationController(rootViewController: MERankViewController()) let searchNVC = UINavigationController(rootViewController: MESearchViewController()) let pushNVC = UINavigationController(rootViewController: MEPushViewController()) let circleNVC = UINavigationController(rootViewController: MECircleViewController()) let moreNVC = UINavigationController(rootViewController: MEMoreViewController()) let tabBarC = UITabBarController() tabBarC.viewControllers = [rankNVC, searchNVC, pushNVC, circleNVC, moreNVC] rankNVC.tabBarItem = UITabBarItem(title: "排行榜", image: UIImage(named: "bio"), selectedImage: UIImage(named: "bio_red")) searchNVC.tabBarItem = UITabBarItem(title: "发现", image: UIImage(named: "timer 2"), selectedImage: UIImage(named: "timer 2_red")) pushNVC.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "pencil"), selectedImage: UIImage(named: "pencil_red")) circleNVC.tabBarItem = UITabBarItem(title: "圈子", image: UIImage(named: "users two-2"), selectedImage: UIImage(named: "users two-2_red")) moreNVC.tabBarItem = UITabBarItem(title: "更多", image: UIImage(named: "more"), selectedImage: UIImage(named: "more_red")) window?.rootViewController = tabBarC window?.makeKeyAndVisible() tabBarC.tabBar.tintColor = Main_Color 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 invalidate graphics rendering callbacks. 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 active 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:. } }
apache-2.0
49b8a07b10dc1c4acc16f0966663d79d
48.767123
285
0.71924
5.334802
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/search-insert-position.swift
2
593
/** * https://leetcode.com/problems/search-insert-position/ * * */ // Date: Wed Jun 10 15:08:02 PDT 2020 class Solution { func searchInsert(_ nums: [Int], _ target: Int) -> Int { // guard let last = nums.last else { return 0 } // if last < target { return nums.count } var left = 0 var right = nums.count while left < right { let mid = left + (right - left) / 2 if nums[mid] < target { left = mid + 1 } else { right = mid } } return left } }
mit
e5ae3750291205cfc4deaa1333aacd13
24.782609
60
0.470489
3.901316
false
false
false
false
WWITDC/Underchess
underchess/UCUtility.swift
1
1858
// // UCUtility.swift // Underchess // // Created by Apollonian on 16/2/20. // Copyright © 2016年 WWITDC. All rights reserved. // import UIKit enum UCDirection{ case up case down case left case right } extension UIColor { static let ucBlue = #colorLiteral(red: 0.18, green: 0.46, blue: 0.57, alpha: 1) static let tianyiBlue = #colorLiteral(red: 0.4, green: 0.8, blue: 1, alpha: 1) static let ucPieceRed = #colorLiteral(red: 0.92, green: 0.23, blue: 0.09, alpha: 1) static let ucPieceGreen = #colorLiteral(red: 0.04, green: 0.93, blue: 0.76, alpha: 1) class func random() -> UIColor { let rand = { CGFloat(arc4random_uniform(255)) / CGFloat(255) } return UIColor(red: rand(), green: rand() , blue: rand(), alpha: rand()) } convenience init?(hex code: String) { guard let hex = Int(code, radix: 16) else { return nil } self.init(red: CGFloat(hex & 0xFF0000), green: CGFloat(hex & 0xFF00), blue: CGFloat(hex & 0xFF), alpha: 1) } } func ucCenters(in frame: CGRect) -> [CGPoint] { var result = [CGPoint]() if frame.height > frame.width { let unit = min(frame.width / 6, frame.height / 8) result.append(CGPoint(x: unit * 1, y: unit * 1)) result.append(CGPoint(x: unit * 5, y: unit * 1)) result.append(CGPoint(x: unit * 3, y: unit * 4)) result.append(CGPoint(x: unit * 5, y: unit * 7)) result.append(CGPoint(x: unit * 1, y: unit * 7)) } else { let unit = min(frame.width / 8, frame.height / 6) result.append(CGPoint(x: unit * 1, y: unit * 1)) result.append(CGPoint(x: unit * 7, y: unit * 1)) result.append(CGPoint(x: unit * 4, y: unit * 3)) result.append(CGPoint(x: unit * 7, y: unit * 5)) result.append(CGPoint(x: unit * 1, y: unit * 5)) } return result }
unlicense
b933fb07b2b13d088ca925f65974c1cc
34
114
0.59407
3.107203
false
false
false
false
gbuenoandrade/e-urbano
e-urbano/LoginVC.swift
1
1561
// // LoginVC.swift // e-urbano // // Created by Guilherme Andrade on 7/4/15. // Copyright (c) 2015 Laboratório de Estudos Urbanos da Unicamp. All rights reserved. // import UIKit import Parse class LoginVC: UIViewController { @IBOutlet weak var userTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! var alreadyLoggedIn = false var registerVCSegue = "goToRegisterScreen" func setAlreadyLoggedInToTrue() { alreadyLoggedIn = true } override func viewWillAppear(animated: Bool) { if alreadyLoggedIn { self.dismissViewControllerAnimated(false, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() alreadyLoggedIn = false let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") view.addGestureRecognizer(tapGestureRecognizer) let user = PFUser.currentUser() if user != nil && user!.isAuthenticated() { self.dismissViewControllerAnimated(false, completion: nil) } } @IBAction func logInPressed(sender: AnyObject) { PFUser.logInWithUsernameInBackground(userTextField.text, password: passwordTextField.text) { (user, error) -> Void in if user != nil { self.dismissViewControllerAnimated(false, completion: nil) } else if let error = error { self.showErrorView(error) } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == registerVCSegue { let registerVC = segue.destinationViewController as! RegisterVC registerVC.parentVC = self } } }
mit
1e4cf8f80ec3f6f9050371a6e416b4d9
25
119
0.738462
3.98977
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Bicycle/Controller/BicycleServiceInfoController.swift
1
13450
// // BicycleServiceInfoController.swift // WePeiYang // // Created by JinHongxu on 16/8/7. // Copyright © 2016年 Qin Yubo. All rights reserved. // import Foundation import JBChartView import SnapKit class BicycleServiceInfoController: UIViewController, UITableViewDelegate, UITableViewDataSource, JBLineChartViewDelegate, JBLineChartViewDataSource { var chartView: JBChartView! var infoLabel = UILabel() @IBOutlet weak var tableView: UITableView! var user = timeStampTransfer() //iOS 8 fucking bug init(){ super.init(nibName: "BicycleServiceInfoController", bundle: nil) print("haha") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.view.frame.size.width = (UIApplication.sharedApplication().keyWindow?.frame.size.width)! //self.tableView.bounces = false } override func viewDidLoad() { super.viewDidLoad() //设置delegate, dataSource self.tableView.delegate = self self.tableView.dataSource = self if BicycleUser.sharedInstance.status == 1 { BicycleUser.sharedInstance.getUserInfo({ self.updateUI() }) } } func updateUI() { /* //UI //chartViewBackground let background = UIImage(named: "BicyleChartBackgroundImage") let backgroundView = UIView(frame: CGRect(x: 8, y: 116, width: (UIApplication.sharedApplication().keyWindow?.frame.size.width)!-16, height: 220)) backgroundView.layer.cornerRadius = 8.0 backgroundView.backgroundColor = UIColor(patternImage: background!) self.view.addSubview(backgroundView) //chartView let chartView = JBLineChartView(frame: self.calculateChartViewFrame()) chartView.delegate = self chartView.dataSource = self chartView.backgroundColor = UIColor.clearColor() self.view.addSubview(chartView) chartView.reloadData() let lastHour = BicycleUser.sharedInstance.recent![BicycleUser.sharedInstance.recent!.count-1][0] let lastDuration = BicycleUser.sharedInstance.recent![BicycleUser.sharedInstance.recent!.count-1][1] self.infoLabel!.text = "\(lastHour):00 骑行时间:\(lastDuration)s" */ //tableView tableView.reloadData() //chatrView chartView.reloadData() } func calculateChartViewFrame() -> CGRect { let x = CGFloat(24) let y = CGFloat(24) let width = CGFloat((UIApplication.sharedApplication().keyWindow?.frame.size.width)!-48) let height = CGFloat(188) return CGRect(x: x, y: y, width: width, height: height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func refreshInfo() { if BicycleUser.sharedInstance.status == 1 { BicycleUser.sharedInstance.getUserInfo({ self.updateUI() }) } else { MsgDisplay.showErrorMsg("未绑定自行车卡信息") infoLabel.text = "未绑定自行车卡信息" } } //dataScoure of chartView func numberOfLinesInLineChartView(lineChartView: JBLineChartView!) -> UInt { return 1 } func lineChartView(lineChartView: JBLineChartView!, numberOfVerticalValuesAtLineIndex lineIndex: UInt) -> UInt { return UInt(BicycleUser.sharedInstance.recent.count) } func lineChartView(lineChartView: JBLineChartView!, verticalValueForHorizontalIndex horizontalIndex: UInt, atLineIndex lineIndex: UInt) -> CGFloat { //let res = data[Int(horizontalIndex)]["dist"] as! CGFloat let res = BicycleUser.sharedInstance.recent[Int(horizontalIndex)][1] as? CGFloat return res! } func lineChartView(lineChartView: JBLineChartView!, showsDotsForLineAtLineIndex lineIndex: UInt) -> Bool { return true } func lineChartView(lineChartView: JBLineChartView!, colorForLineAtLineIndex lineIndex: UInt) -> UIColor! { return UIColor(red: 1, green: 1, blue: 1, alpha: 0.5) } func lineChartView(lineChartView: JBLineChartView!, colorForDotAtHorizontalIndex horizontalIndex: UInt, atLineIndex lineIndex: UInt) -> UIColor! { return UIColor(red: 1, green: 1, blue: 1, alpha: 1) } func lineChartView(lineChartView: JBLineChartView!, dotRadiusForDotAtHorizontalIndex horizontalIndex: UInt, atLineIndex lineIndex: UInt) -> CGFloat { return 4.0 } func lineChartView(lineChartView: JBLineChartView!, widthForLineAtLineIndex lineIndex: UInt) -> CGFloat { return 2.0 } func lineChartView(lineChartView: JBLineChartView!, lineStyleForLineAtLineIndex lineIndex: UInt) -> JBLineChartViewLineStyle { return JBLineChartViewLineStyle.Dashed } //delegate of chartView func lineChartView(lineChartView: JBLineChartView!, didSelectLineAtIndex lineIndex: UInt, horizontalIndex: UInt) { let date = BicycleUser.sharedInstance.recent[Int(horizontalIndex)][0] var time = BicycleUser.sharedInstance.recent[Int(horizontalIndex)][1] as! Int var minute: Int var second: Int var hour: Int hour = time / 3600 time %= 3600 minute = time / 60 time %= 60 second = time var hourString = String(hour) if hour < 10 { hourString = "0\(String(hour))" } var minuteString = String(minute) if minute < 10 { minuteString = "0\(String(minute))" } var secondString = String(second) if second < 10 { secondString = "0\(String(second))" } self.infoLabel.text = "\(date) 骑行时间:\(hourString):\(minuteString):\(secondString)" } //dataSource of tableView func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 5 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("BicycleInfoCell") if cell == nil { cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "BicycleInfoCell") } if indexPath.section == 0 { //未完成 cell!.textLabel?.text = "用户:" if let name = BicycleUser.sharedInstance.name { cell!.textLabel?.text = "用户:\(name)" } cell!.imageView?.image = UIImage(named: "ic_account_circle") cell!.selectionStyle = .None } else if indexPath.section == 1 { cell!.textLabel?.text = "余额:" if let balance = BicycleUser.sharedInstance.balance { cell!.textLabel?.text = "余额:¥\(balance)" } cell!.imageView?.image = UIImage(named: "ic_account_balance_wallet") cell!.selectionStyle = .None } else if indexPath.section == 2 { cell!.textLabel?.text = "最近记录:" if let foo = BicycleUser.sharedInstance.record { var timeStampString = foo.objectForKey("arr_time") as! String //借了车,没还车 if Int(timeStampString) == 0 { cell?.textLabel?.text = "最近记录:借车" timeStampString = foo.objectForKey("dep_time") as! String cell?.detailTextLabel?.text = "时间:\(timeStampTransfer.stringFromTimeStampWithFormat("yyyy-MM-dd HH:mm", timeStampString: timeStampString))" } else { cell?.textLabel?.text = "最近记录:还车" cell?.detailTextLabel?.text = "时间:\(timeStampTransfer.stringFromTimeStampWithFormat("yyyy-MM-dd HH:mm", timeStampString: timeStampString))" } } cell!.imageView?.image = UIImage(named: "ic_schedule") cell!.selectionStyle = .None } else if indexPath.section == 3 { cell!.imageView?.image = UIImage(named: "ic_history") cell!.textLabel?.text = "查询记录" } else if indexPath.section == 4 { cell!.imageView?.image = UIImage(named: "ic_history") cell!.textLabel?.text = "数据分析" } return cell! } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 264 } return 4 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section != 0 { let headerView = UIView(frame: CGRectMake(0, 0, (UIApplication.sharedApplication().keyWindow?.frame.size.width)!, 4)) headerView.backgroundColor = UIColor.clearColor() return headerView } //log.word("drawing header view") let headerView = UIView(frame: CGRect(x: 0, y: 0, width: (UIApplication.sharedApplication().keyWindow?.frame.size.width)!, height: 250)) //infoLabel infoLabel = UILabel() headerView.addSubview(infoLabel) infoLabel.text = "骑行时间:" infoLabel.snp_makeConstraints { make in make.centerX.equalTo(headerView) make.top.equalTo(headerView).offset(8) } let bicycleIconView = UIImageView(imageName: "ic_bike", desiredSize: CGSize(width: 30, height: 30)) headerView.addSubview(bicycleIconView!) bicycleIconView?.snp_makeConstraints { make in make.centerY.equalTo(infoLabel) make.right.equalTo(infoLabel.snp_left).offset(-8) } //chartViewBackground let chartBackground = UIImageView(imageName: "BicyleChartBackgroundImage", desiredSize: CGSize(width: (UIApplication.sharedApplication().keyWindow?.frame.size.width)!-16, height: 220)) headerView.addSubview(chartBackground!) chartBackground?.snp_makeConstraints { make in make.top.equalTo(infoLabel.snp_bottom).offset(8) make.left.equalTo(headerView).offset(8) make.right.equalTo(headerView).offset(-8) make.bottom.equalTo(headerView).offset(-8) } chartBackground!.clipsToBounds = true chartBackground!.layer.cornerRadius = 8 for subview in chartBackground!.subviews { subview.layer.cornerRadius = 8 } /* let background = UIImage(named: "BicyleChartBackgroundImage") let backgroundView = UIView(frame: CGRect(x: 8, y: 8, width: (UIApplication.sharedApplication().keyWindow?.frame.size.width)!-16, height: 220)) backgroundView.layer.cornerRadius = 8.0 backgroundView.backgroundColor = UIColor(patternImage: background!) view.addSubview(backgroundView)*/ //chartView chartView = JBLineChartView(frame: CGRectMake(16, 53, (UIApplication.sharedApplication().keyWindow?.frame.size.width)!-32, 188)) //chartView = JBLineChartView(frame: CGRectMake(8, 8, 300, 220)) chartView.delegate = self chartView.dataSource = self chartView.backgroundColor = UIColor.clearColor() headerView.addSubview(chartView) chartView.reloadData() /* chartView.snp_makeConstraints { make in make.left.equalTo(chartBackground!).offset(8) make.right.equalTo(chartBackground!).offset(-8) make.top.equalTo(chartBackground!).offset(8) make.bottom.equalTo(chartBackground!).offset(-8) }*/ return headerView } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 4 } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerView = UIView(frame: CGRectMake(0, 0, (UIApplication.sharedApplication().keyWindow?.frame.size.width)!, 4)) footerView.backgroundColor = UIColor.clearColor() return footerView } //delegate of tableView func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 3 { MsgDisplay.showErrorMsg("暂时没有这个功能哦") } if indexPath.section == 4 { if #available(iOS 9.3, *) { let fitnessVC = BicycleFitnessTrackerViewController() self.navigationController?.pushViewController(fitnessVC, animated: true) tableView.deselectRowAtIndexPath(indexPath, animated: true) } else { // Fallback on earlier versions } } tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
416f3e0a975b748451def72da326724e
36.005587
192
0.614508
5.075862
false
false
false
false
danielrhodes/Swift-ActionCableClient
Example/ActionCableClient/AppDelegate.swift
2
3485
// // 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 UIKit import ActionCableClient @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { let controller = ChatViewController() let navigationController = UINavigationController() navigationController.pushViewController(controller, animated: false) self.window = UIWindow(); self.window?.rootViewController = navigationController; self.window?.makeKeyAndVisible(); return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
41d6a13e32d1c278f45fe6da19a7ccaa
51.80303
285
0.750646
5.320611
false
false
false
false
vknabel/Taps
Sources/Taps/Test.swift
1
1766
import RxSwift /// Provides functions, that create `TestPoint`s. /// Each `TestPoint` is associated to a `Test`. public final class Test: OfferingTests { /// Observes for all `TestPoint`s. /// Each `TestPoint` will be passed to `Taps`. public private(set) var report: AnyObserver<TestPoint> private var plan: Int internal init(report: AnyObserver<TestPoint>, plan: Int?) { self.plan = plan ?? 0 self.report = report self.report = plan != nil ? AnyObserver { switch $0 { case let .next(v): self.plan -= 1 if self.plan < 0 { let errorPoint = TestPoint( isOk: false, message: "more test points emitted than planned", source: v.sourceLocation, details: [ "operator": .string("plan"), "test": .dictionary([ "ok": .bool(v.isOk), "message": .string(v.message ?? "(no message provided)"), "source": .dictionary([ "file": .string(v.sourceLocation.file), "line": .int(v.sourceLocation.line), "column": .int(v.sourceLocation.column), "function": .string(v.sourceLocation.function) ]), "details": .dictionary(v.details ?? [:]) ]) ] ) fatalError("more test points emitted than planned: \(errorPoint)") } else { report.on($0) } if self.plan == 0 { report.on(.completed) } default: report.on($0) } } : report } } public extension OfferingTests { /// Marks a test as finished. /// No `TestPoint` may follow. public func end() { report.onCompleted() } }
mit
10988b10387e50229566629c10133378
28.433333
76
0.525481
4.339066
false
true
false
false
IvanovGeorge/SwiftyScrollableGraph
SwiftyScrollableGraph/BezierView.swift
2
5915
// // BezierView.swift // SwiftyScrollableGraph // // Created by Георгий on 26.09.17. // Copyright © 2017 Георгий. All rights reserved. // import UIKit import Foundation class BezierView: UIView { fileprivate let kStrokeAnimationKey = "StrokeAnimationKey" fileprivate let kFadeAnimationKey = "FadeAnimationKey" var lineColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) var lineSize:CGFloat = 0 var pickedPointColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) var pickedPointSize = 0 var pointsColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) var pointsSize = 0 var pointsShadow = false var lineShadow = false var animates = true var animationTime: CFTimeInterval = 0 var pointLayers = [CAShapeLayer]() var lineLayer = CAShapeLayer() var placedPoint = CAShapeLayer() //MARK: Private members var dataPoints: [CGPoint]? fileprivate var cubicCurveAlgorithm = CubicCurveAlgorithm() override func layoutSubviews() { super.layoutSubviews() } func redraw() { cubicCurveAlgorithm = CubicCurveAlgorithm() self.layer.sublayers?.forEach({ (layer: CALayer) -> () in layer.removeFromSuperlayer() }) pointLayers.removeAll() drawSmoothLines() drawPoints() animateLayers() } func clear() { self.layer.sublayers?.forEach({ (layer: CALayer) -> () in layer.removeFromSuperlayer() }) pointLayers.removeAll() } func placePoint(atPoint point: CGPoint){ placedPoint.removeFromSuperlayer() placedPoint.bounds = CGRect(x: 0, y: 0, width: pickedPointSize, height: pickedPointSize) placedPoint.path = UIBezierPath(ovalIn: placedPoint.bounds).cgPath placedPoint.fillColor = pickedPointColor.cgColor placedPoint.position = point self.layer.addSublayer(placedPoint) } fileprivate func drawPoints(){ guard let points = dataPoints else { return } for point in points { //здесь отрисовываем точки let circleLayer = CAShapeLayer() circleLayer.bounds = CGRect(x: 0, y: 0, width: pointsSize, height: pointsSize) circleLayer.path = UIBezierPath(ovalIn: circleLayer.bounds).cgPath circleLayer.fillColor = pointsColor.cgColor // UIColor(white: 248.0/255.0, alpha: 0.5).cgColor circleLayer.position = point if pointsShadow { circleLayer.shadowColor = UIColor.black.cgColor circleLayer.shadowOffset = CGSize(width: 0, height: 2) circleLayer.shadowOpacity = 0.7 circleLayer.shadowRadius = 3.0 } self.layer.addSublayer(circleLayer) if animates { circleLayer.opacity = 0 pointLayers.append(circleLayer) } } } fileprivate func drawSmoothLines() { guard let points = dataPoints else { return } let controlPoints = cubicCurveAlgorithm.controlPointsFromPoints(points) let linePath = UIBezierPath() for i in 0 ..< points.count { let point = points[i]; if i==0 { linePath.move(to: point) } else { let segment = controlPoints[i-1] linePath.addCurve(to: point, controlPoint1: segment.controlPoint1, controlPoint2: segment.controlPoint2) } } lineLayer = CAShapeLayer() lineLayer.path = linePath.cgPath lineLayer.fillColor = UIColor.clear.cgColor lineLayer.strokeColor = lineColor.cgColor //толщина линии lineLayer.lineWidth = lineSize if lineShadow { //тень линии lineLayer.shadowColor = UIColor.black.cgColor lineLayer.shadowOffset = CGSize(width: 0, height: 8) lineLayer.shadowOpacity = 0.5 lineLayer.shadowRadius = 6.0 } self.layer.addSublayer(lineLayer) if animates { lineLayer.strokeEnd = 0 } } } extension BezierView { func animateLayers() { animatePoints() animateLine() } func animatePoints() { var delay = animationTime / Double(dataPoints!.count ) for point in pointLayers { let fadeAnimation = CABasicAnimation(keyPath: "opacity") fadeAnimation.toValue = 1 fadeAnimation.beginTime = CACurrentMediaTime() + 0.2//delay * Double(index) fadeAnimation.duration = 0.2 fadeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) fadeAnimation.fillMode = kCAFillModeForwards fadeAnimation.isRemovedOnCompletion = false point.add(fadeAnimation, forKey: kFadeAnimationKey) delay += 0.15 } } func animateLine() { let growAnimation = CABasicAnimation(keyPath: "strokeEnd") growAnimation.toValue = 1 growAnimation.beginTime = CACurrentMediaTime() //+ 0.5 growAnimation.duration = animationTime growAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) growAnimation.fillMode = kCAFillModeForwards growAnimation.isRemovedOnCompletion = false lineLayer.add(growAnimation, forKey: kStrokeAnimationKey) } }
mit
ef293c1130f1fc5ceab065f92e77a5f3
27.570732
120
0.583234
5.418131
false
false
false
false
hooman/swift
test/AutoDiff/Sema/derivative_attr_type_checking.swift
4
45841
// RUN: %target-swift-frontend-typecheck -verify -disable-availability-checking %s // RUN: %target-swift-frontend-typecheck -enable-testing -verify -disable-availability-checking %s // Swift.AdditiveArithmetic:3:17: note: cannot yet register derivative default implementation for protocol requirements import _Differentiation // Dummy `Differentiable`-conforming type. struct DummyTangentVector: Differentiable & AdditiveArithmetic { static var zero: Self { Self() } static func + (_: Self, _: Self) -> Self { Self() } static func - (_: Self, _: Self) -> Self { Self() } typealias TangentVector = Self } // Test top-level functions. func id(_ x: Float) -> Float { return x } @derivative(of: id) func jvpId(x: Float) -> (value: Float, differential: (Float) -> (Float)) { return (x, { $0 }) } @derivative(of: id, wrt: x) func vjpIdExplicitWrt(x: Float) -> (value: Float, pullback: (Float) -> Float) { return (x, { $0 }) } func generic<T: Differentiable>(_ x: T, _ y: T) -> T { return x } @derivative(of: generic) func jvpGeneric<T: Differentiable>(x: T, y: T) -> ( value: T, differential: (T.TangentVector, T.TangentVector) -> T.TangentVector ) { return (x, { $0 + $1 }) } @derivative(of: generic) func vjpGenericExtraGenericRequirements<T: Differentiable & FloatingPoint>( x: T, y: T ) -> (value: T, pullback: (T) -> (T, T)) where T == T.TangentVector { return (x, { ($0, $0) }) } // Test `wrt` parameter clauses. func add(x: Float, y: Float) -> Float { return x + y } @derivative(of: add, wrt: x) // ok func vjpAddWrtX(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) { return (x + y, { $0 }) } @derivative(of: add, wrt: (x, y)) // ok func vjpAddWrtXY(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x + y, { ($0, $0) }) } // Test index-based `wrt` parameters. func subtract(x: Float, y: Float) -> Float { return x - y } @derivative(of: subtract, wrt: (0, y)) // ok func vjpSubtractWrt0Y(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x - y, { ($0, $0) }) } @derivative(of: subtract, wrt: (1)) // ok func vjpSubtractWrt1(x: Float, y: Float) -> (value: Float, pullback: (Float) -> Float) { return (x - y, { $0 }) } // Test invalid original function. // expected-error @+1 {{cannot find 'nonexistentFunction' in scope}} @derivative(of: nonexistentFunction) func vjpOriginalFunctionNotFound(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // Test `@derivative` attribute where `value:` result does not conform to `Differentiable`. // Invalid original function should be diagnosed first. // expected-error @+1 {{cannot find 'nonexistentFunction' in scope}} @derivative(of: nonexistentFunction) func vjpOriginalFunctionNotFound2(_ x: Float) -> (value: Int, pullback: (Float) -> Float) { fatalError() } // Test incorrect `@derivative` declaration type. // expected-note @+2 {{'incorrectDerivativeType' defined here}} // expected-note @+1 {{candidate global function does not have expected type '(Int) -> Int'}} func incorrectDerivativeType(_ x: Float) -> Float { return x } // expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:' and second element must have label 'pullback:' or 'differential:'}} @derivative(of: incorrectDerivativeType) func jvpResultIncorrect(x: Float) -> Float { return x } // expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:'}} @derivative(of: incorrectDerivativeType) func vjpResultIncorrectFirstLabel(x: Float) -> (Float, (Float) -> Float) { return (x, { $0 }) } // expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; second element must have label 'pullback:' or 'differential:'}} @derivative(of: incorrectDerivativeType) func vjpResultIncorrectSecondLabel(x: Float) -> (value: Float, (Float) -> Float) { return (x, { $0 }) } // expected-error @+1 {{referenced declaration 'incorrectDerivativeType' could not be resolved}} @derivative(of: incorrectDerivativeType) func vjpResultNotDifferentiable(x: Int) -> ( value: Int, pullback: (Int) -> Int ) { return (x, { $0 }) } // expected-error @+2 {{function result's 'pullback' type does not match 'incorrectDerivativeType'}} // expected-note @+3 {{'pullback' does not have expected type '(Float.TangentVector) -> Float.TangentVector' (aka '(Float) -> Float')}} @derivative(of: incorrectDerivativeType) func vjpResultIncorrectPullbackType(x: Float) -> ( value: Float, pullback: (Double) -> Double ) { return (x, { $0 }) } // Test invalid `wrt:` differentiation parameters. func invalidWrtParam(_ x: Float, _ y: Float) -> Float { return x } // expected-error @+1 {{unknown parameter name 'z'}} @derivative(of: add, wrt: z) func vjpUnknownParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) { return (x + y, { $0 }) } // expected-error @+1 {{parameters must be specified in original order}} @derivative(of: invalidWrtParam, wrt: (y, x)) func vjpParamOrderNotIncreasing(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x + y, { ($0, $0) }) } // expected-error @+1 {{'self' parameter is only applicable to instance methods}} @derivative(of: invalidWrtParam, wrt: self) func vjpInvalidSelfParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x + y, { ($0, $0) }) } // expected-error @+1 {{parameter index is larger than total number of parameters}} @derivative(of: invalidWrtParam, wrt: 2) func vjpSubtractWrt2(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x - y, { ($0, $0) }) } // expected-error @+1 {{parameters must be specified in original order}} @derivative(of: invalidWrtParam, wrt: (1, x)) func vjpSubtractWrt1x(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x - y, { ($0, $0) }) } // expected-error @+1 {{parameters must be specified in original order}} @derivative(of: invalidWrtParam, wrt: (1, 0)) func vjpSubtractWrt10(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x - y, { ($0, $0) }) } func noParameters() -> Float { return 1 } // expected-error @+1 {{'vjpNoParameters()' has no parameters to differentiate with respect to}} @derivative(of: noParameters) func vjpNoParameters() -> (value: Float, pullback: (Float) -> Float) { return (1, { $0 }) } func noDifferentiableParameters(x: Int) -> Float { return 1 } // expected-error @+1 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}} @derivative(of: noDifferentiableParameters) func vjpNoDifferentiableParameters(x: Int) -> ( value: Float, pullback: (Float) -> Int ) { return (1, { _ in 0 }) } func functionParameter(_ fn: (Float) -> Float) -> Float { return fn(1) } // expected-error @+1 {{can only differentiate with respect to parameters that conform to 'Differentiable', but '(Float) -> Float' does not conform to 'Differentiable'}} @derivative(of: functionParameter, wrt: fn) func vjpFunctionParameter(_ fn: (Float) -> Float) -> ( value: Float, pullback: (Float) -> Float ) { return (functionParameter(fn), { $0 }) } // Test static methods. protocol StaticMethod: Differentiable { static func foo(_ x: Float) -> Float static func generic<T: Differentiable>(_ x: T) -> T } extension StaticMethod { static func foo(_ x: Float) -> Float { x } static func generic<T: Differentiable>(_ x: T) -> T { x } } extension StaticMethod { @derivative(of: foo) static func jvpFoo(x: Float) -> (value: Float, differential: (Float) -> Float) { return (x, { $0 }) } // Test qualified declaration name. @derivative(of: StaticMethod.foo) static func vjpFoo(x: Float) -> (value: Float, pullback: (Float) -> Float) { return (x, { $0 }) } @derivative(of: generic) static func vjpGeneric<T: Differentiable>(_ x: T) -> ( value: T, pullback: (T.TangentVector) -> (T.TangentVector) ) { return (x, { $0 }) } // expected-error @+1 {{'self' parameter is only applicable to instance methods}} @derivative(of: foo, wrt: (self, x)) static func vjpFooWrtSelf(x: Float) -> (value: Float, pullback: (Float) -> Float) { return (x, { $0 }) } } // Test instance methods. protocol InstanceMethod: Differentiable { func foo(_ x: Self) -> Self func generic<T: Differentiable>(_ x: T) -> Self } extension InstanceMethod { // expected-note @+1 {{'foo' defined here}} func foo(_ x: Self) -> Self { x } // expected-note @+1 {{'generic' defined here}} func generic<T: Differentiable>(_ x: T) -> Self { self } } extension InstanceMethod { @derivative(of: foo) func jvpFoo(x: Self) -> ( value: Self, differential: (TangentVector, TangentVector) -> (TangentVector) ) { return (x, { $0 + $1 }) } // Test qualified declaration name. @derivative(of: InstanceMethod.foo, wrt: x) func jvpFooWrtX(x: Self) -> ( value: Self, differential: (TangentVector) -> (TangentVector) ) { return (x, { $0 }) } @derivative(of: generic) func vjpGeneric<T: Differentiable>(_ x: T) -> ( value: Self, pullback: (TangentVector) -> (TangentVector, T.TangentVector) ) { return (self, { ($0, .zero) }) } @derivative(of: generic, wrt: (self, x)) func jvpGenericWrt<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) { return (self, { dself, dx in dself }) } // expected-error @+1 {{'self' parameter must come first in the parameter list}} @derivative(of: generic, wrt: (x, self)) func jvpGenericWrtSelf<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) { return (self, { dself, dx in dself }) } } extension InstanceMethod { // If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter. // expected-error @+2 {{function result's 'pullback' type does not match 'foo'}} // expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, Self.TangentVector)'}} @derivative(of: foo) func vjpFoo(x: Self) -> ( value: Self, pullback: (TangentVector) -> TangentVector ) { return (x, { $0 }) } // If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter. // expected-error @+2 {{function result's 'pullback' type does not match 'generic'}} // expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, T.TangentVector)'}} @derivative(of: generic) func vjpGeneric<T: Differentiable>(_ x: T) -> ( value: Self, pullback: (TangentVector) -> T.TangentVector ) { return (self, { _ in .zero }) } } // Test `@derivative` declaration with more constrained generic signature. func req1<T>(_ x: T) -> T { return x } @derivative(of: req1) func vjpExtraConformanceConstraint<T: Differentiable>(_ x: T) -> ( value: T, pullback: (T.TangentVector) -> T.TangentVector ) { return (x, { $0 }) } func req2<T, U>(_ x: T, _ y: U) -> T { return x } @derivative(of: req2) func vjpExtraConformanceConstraints<T: Differentiable, U: Differentiable>( _ x: T, _ y: U) -> ( value: T, pullback: (T) -> (T, U) ) where T == T.TangentVector, U == U.TangentVector, T: CustomStringConvertible { return (x, { ($0, .zero) }) } // Test `@derivative` declaration with extra same-type requirements. func req3<T>(_ x: T) -> T { return x } @derivative(of: req3) func vjpSameTypeRequirementsGenericParametersAllConcrete<T>(_ x: T) -> ( value: T, pullback: (T.TangentVector) -> T.TangentVector ) where T: Differentiable, T.TangentVector == Float { return (x, { $0 }) } struct Wrapper<T: Equatable>: Equatable { var x: T init(_ x: T) { self.x = x } } extension Wrapper: AdditiveArithmetic where T: AdditiveArithmetic { static var zero: Self { .init(.zero) } static func + (lhs: Self, rhs: Self) -> Self { .init(lhs.x + rhs.x) } static func - (lhs: Self, rhs: Self) -> Self { .init(lhs.x - rhs.x) } } extension Wrapper: Differentiable where T: Differentiable, T == T.TangentVector { typealias TangentVector = Wrapper<T.TangentVector> } extension Wrapper where T: Differentiable, T == T.TangentVector { @derivative(of: init(_:)) static func vjpInit(_ x: T) -> (value: Self, pullback: (Wrapper<T>.TangentVector) -> (T)) { fatalError() } } // Test class methods. class Super { @differentiable(reverse) // expected-note @+1 {{candidate instance method is not defined in the current type context}} func foo(_ x: Float) -> Float { return x } @derivative(of: foo) func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { return (foo(x), { v in v }) } } class Sub: Super { // TODO(TF-649): Enable `@derivative` to override derivatives for original // declaration defined in superclass. // expected-error @+1 {{referenced declaration 'foo' could not be resolved}} @derivative(of: foo) override func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { return (foo(x), { v in v }) } } // Test non-`func` original declarations. struct Struct<T> { var x: T } extension Struct: Equatable where T: Equatable {} extension Struct: Differentiable & AdditiveArithmetic where T: Differentiable & AdditiveArithmetic { static var zero: Self { fatalError() } static func + (lhs: Self, rhs: Self) -> Self { fatalError() } static func - (lhs: Self, rhs: Self) -> Self { fatalError() } typealias TangentVector = Struct<T.TangentVector> mutating func move(by offset: TangentVector) { x.move(by: offset.x) } } class Class<T> { var x: T init(_ x: T) { self.x = x } } extension Class: Differentiable where T: Differentiable {} // Test computed properties. extension Struct { var computedProperty: T { get { x } set { x = newValue } _modify { yield &x } } } extension Struct where T: Differentiable & AdditiveArithmetic { @derivative(of: computedProperty) func vjpProperty() -> (value: T, pullback: (T.TangentVector) -> TangentVector) { return (x, { v in .init(x: v) }) } @derivative(of: computedProperty.get) func jvpProperty() -> (value: T, differential: (TangentVector) -> T.TangentVector) { fatalError() } @derivative(of: computedProperty.set) mutating func vjpPropertySetter(_ newValue: T) -> ( value: (), pullback: (inout TangentVector) -> T.TangentVector ) { fatalError() } // expected-error @+1 {{cannot register derivative for _modify accessor}} @derivative(of: computedProperty._modify) mutating func vjpPropertyModify(_ newValue: T) -> ( value: (), pullback: (inout TangentVector) -> T.TangentVector ) { fatalError() } } // Test initializers. extension Struct { init(_ x: Float) {} init(_ x: T, y: Float) {} } extension Struct where T: Differentiable & AdditiveArithmetic { @derivative(of: init) static func vjpInit(_ x: Float) -> ( value: Struct, pullback: (TangentVector) -> Float ) { return (.init(x), { _ in .zero }) } @derivative(of: init(_:y:)) static func vjpInit2(_ x: T, _ y: Float) -> ( value: Struct, pullback: (TangentVector) -> (T.TangentVector, Float) ) { return (.init(x, y: y), { _ in (.zero, .zero) }) } } // Test subscripts. extension Struct { subscript() -> Float { get { 1 } set {} } subscript(float float: Float) -> Float { get { 1 } set {} } // expected-note @+1 {{candidate subscript does not have a setter}} subscript<T: Differentiable>(x: T) -> T { x } } extension Struct where T: Differentiable & AdditiveArithmetic { @derivative(of: subscript.get) func vjpSubscriptGetter() -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } // expected-error @+2 {{a derivative already exists for '_'}} // expected-note @-6 {{other attribute declared here}} @derivative(of: subscript) func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } @derivative(of: subscript().get) func jvpSubscriptGetter() -> (value: Float, differential: (TangentVector) -> Float) { return (1, { _ in .zero }) } @derivative(of: subscript(float:).get, wrt: self) func vjpSubscriptLabeledGetter(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } // expected-error @+2 {{a derivative already exists for '_'}} // expected-note @-6 {{other attribute declared here}} @derivative(of: subscript(float:), wrt: self) func vjpSubscriptLabeled(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } @derivative(of: subscript(float:).get) func jvpSubscriptLabeledGetter(float: Float) -> (value: Float, differential: (TangentVector, Float) -> Float) { return (1, { (_,_) in 1}) } @derivative(of: subscript(_:).get, wrt: self) func vjpSubscriptGenericGetter<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) { return (x, { _ in .zero }) } // expected-error @+2 {{a derivative already exists for '_'}} // expected-note @-6 {{other attribute declared here}} @derivative(of: subscript(_:), wrt: self) func vjpSubscriptGeneric<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) { return (x, { _ in .zero }) } @derivative(of: subscript.set) mutating func vjpSubscriptSetter(_ newValue: Float) -> ( value: (), pullback: (inout TangentVector) -> Float ) { fatalError() } @derivative(of: subscript().set) mutating func jvpSubscriptSetter(_ newValue: Float) -> ( value: (), differential: (inout TangentVector, Float) -> () ) { fatalError() } @derivative(of: subscript(float:).set) mutating func vjpSubscriptLabeledSetter(float: Float, newValue: Float) -> ( value: (), pullback: (inout TangentVector) -> (Float, Float) ) { fatalError() } @derivative(of: subscript(float:).set) mutating func jvpSubscriptLabeledSetter(float: Float, _ newValue: Float) -> ( value: (), differential: (inout TangentVector, Float, Float) -> Void ) { fatalError() } // Error: original subscript has no setter. // expected-error @+1 {{referenced declaration 'subscript(_:)' could not be resolved}} @derivative(of: subscript(_:).set, wrt: self) mutating func vjpSubscriptGeneric_NoSetter<T: Differentiable>(x: T) -> ( value: T, pullback: (T.TangentVector) -> TangentVector ) { return (x, { _ in .zero }) } } extension Class { subscript() -> Float { get { 1 } // expected-note @+1 {{'subscript()' declared here}} set {} } } extension Class where T: Differentiable { @derivative(of: subscript.get) func vjpSubscriptGetter() -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } // expected-error @+2 {{a derivative already exists for '_'}} // expected-note @-6 {{other attribute declared here}} @derivative(of: subscript) func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } // FIXME(SR-13096): Enable derivative registration for class property/subscript setters. // This requires changing derivative type calculation rules for functions with // class-typed parameters. We need to assume that all functions taking // class-typed operands may mutate those operands. // expected-error @+1 {{cannot yet register derivative for class property or subscript setters}} @derivative(of: subscript.set) func vjpSubscriptSetter(_ newValue: Float) -> ( value: (), pullback: (inout TangentVector) -> Float ) { fatalError() } } // Test duplicate `@derivative` attribute. func duplicate(_ x: Float) -> Float { x } // expected-note @+1 {{other attribute declared here}} @derivative(of: duplicate) func jvpDuplicate1(_ x: Float) -> (value: Float, differential: (Float) -> Float) { return (duplicate(x), { $0 }) } // expected-error @+1 {{a derivative already exists for 'duplicate'}} @derivative(of: duplicate) func jvpDuplicate2(_ x: Float) -> (value: Float, differential: (Float) -> Float) { return (duplicate(x), { $0 }) } // Test invalid original declaration kind. // expected-note @+1 {{candidate var does not have a getter}} var globalVariable: Float // expected-error @+1 {{referenced declaration 'globalVariable' could not be resolved}} @derivative(of: globalVariable) func invalidOriginalDeclaration(x: Float) -> ( value: Float, differential: (Float) -> (Float) ) { return (x, { $0 }) } // Test ambiguous original declaration. protocol P1 {} protocol P2 {} // expected-note @+1 {{candidate global function found here}} func ambiguous<T: P1>(_ x: T) -> T { x } // expected-note @+1 {{candidate global function found here}} func ambiguous<T: P2>(_ x: T) -> T { x } // expected-error @+1 {{referenced declaration 'ambiguous' is ambiguous}} @derivative(of: ambiguous) func jvpAmbiguous<T: P1 & P2 & Differentiable>(x: T) -> (value: T, differential: (T.TangentVector) -> (T.TangentVector)) { return (x, { $0 }) } // Test no valid original declaration. // Original declarations are invalid because they have extra generic // requirements unsatisfied by the `@derivative` function. // expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}} func invalid<T: BinaryFloatingPoint>(x: T) -> T { x } // expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}} func invalid<T: CustomStringConvertible>(x: T) -> T { x } // expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}} func invalid<T: FloatingPoint>(x: T) -> T { x } // expected-error @+1 {{referenced declaration 'invalid' could not be resolved}} @derivative(of: invalid) func jvpInvalid<T: Differentiable>(x: T) -> ( value: T, differential: (T.TangentVector) -> T.TangentVector ) { return (x, { $0 }) } // Test stored property original declaration. struct HasStoredProperty { // expected-note @+1 {{'stored' declared here}} var stored: Float } extension HasStoredProperty: Differentiable & AdditiveArithmetic { static var zero: Self { fatalError() } static func + (lhs: Self, rhs: Self) -> Self { fatalError() } static func - (lhs: Self, rhs: Self) -> Self { fatalError() } typealias TangentVector = Self } extension HasStoredProperty { // expected-error @+1 {{cannot register derivative for stored property 'stored'}} @derivative(of: stored) func vjpStored() -> (value: Float, pullback: (Float) -> TangentVector) { return (stored, { _ in .zero }) } } // Test derivative registration for protocol requirements. Currently unsupported. // TODO(TF-982): Lift this restriction and add proper support. protocol ProtocolRequirementDerivative { // expected-note @+1 {{cannot yet register derivative default implementation for protocol requirements}} func requirement(_ x: Float) -> Float } extension ProtocolRequirementDerivative { // expected-error @+1 {{referenced declaration 'requirement' could not be resolved}} @derivative(of: requirement) func vjpRequirement(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } } // Test `inout` parameters. func multipleSemanticResults(_ x: inout Float) -> Float { return x } // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @derivative(of: multipleSemanticResults) func vjpMultipleSemanticResults(x: inout Float) -> ( value: Float, pullback: (Float) -> Float ) { return (multipleSemanticResults(&x), { $0 }) } struct InoutParameters: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} } extension InoutParameters { // expected-note @+1 4 {{'staticMethod(_:rhs:)' defined here}} static func staticMethod(_ lhs: inout Self, rhs: Self) {} // Test wrt `inout` parameter. @derivative(of: staticMethod) static func vjpWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, pullback: (inout TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}} @derivative(of: staticMethod) static func vjpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> ( // expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}} value: Void, pullback: (TangentVector) -> TangentVector ) { fatalError() } @derivative(of: staticMethod) static func jvpWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, differential: (inout TangentVector, TangentVector) -> Void ) { fatalError() } // expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}} @derivative(of: staticMethod) static func jvpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> ( // expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}} value: Void, differential: (TangentVector, TangentVector) -> Void ) { fatalError() } // Test non-wrt `inout` parameter. @derivative(of: staticMethod, wrt: rhs) static func vjpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, pullback: (TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}} @derivative(of: staticMethod, wrt: rhs) static func vjpNotWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> ( // expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}} value: Void, pullback: (inout TangentVector) -> TangentVector ) { fatalError() } @derivative(of: staticMethod, wrt: rhs) static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, differential: (TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}} @derivative(of: staticMethod, wrt: rhs) static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( // expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}} value: Void, differential: (inout TangentVector) -> TangentVector ) { fatalError() } } extension InoutParameters { // expected-note @+1 4 {{'mutatingMethod' defined here}} mutating func mutatingMethod(_ other: Self) {} // Test wrt `inout` `self` parameter. @derivative(of: mutatingMethod) mutating func vjpWrtInout(_ other: Self) -> ( value: Void, pullback: (inout TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}} @derivative(of: mutatingMethod) mutating func vjpWrtInoutMismatch(_ other: Self) -> ( // expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}} value: Void, pullback: (TangentVector) -> TangentVector ) { fatalError() } @derivative(of: mutatingMethod) mutating func jvpWrtInout(_ other: Self) -> ( value: Void, differential: (inout TangentVector, TangentVector) -> Void ) { fatalError() } // expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}} @derivative(of: mutatingMethod) mutating func jvpWrtInoutMismatch(_ other: Self) -> ( // expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}} value: Void, differential: (TangentVector, TangentVector) -> Void ) { fatalError() } // Test non-wrt `inout` `self` parameter. @derivative(of: mutatingMethod, wrt: other) mutating func vjpNotWrtInout(_ other: Self) -> ( value: Void, pullback: (TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}} @derivative(of: mutatingMethod, wrt: other) mutating func vjpNotWrtInoutMismatch(_ other: Self) -> ( // expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}} value: Void, pullback: (inout TangentVector) -> TangentVector ) { fatalError() } @derivative(of: mutatingMethod, wrt: other) mutating func jvpNotWrtInout(_ other: Self) -> ( value: Void, differential: (TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}} @derivative(of: mutatingMethod, wrt: other) mutating func jvpNotWrtInoutMismatch(_ other: Self) -> ( // expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}} value: Void, differential: (TangentVector, TangentVector) -> Void ) { fatalError() } } // Test no semantic results. func noSemanticResults(_ x: Float) {} // expected-error @+1 {{cannot differentiate void function 'noSemanticResults'}} @derivative(of: noSemanticResults) func vjpNoSemanticResults(_ x: Float) -> (value: Void, pullback: Void) {} // Test multiple semantic results. extension InoutParameters { func multipleSemanticResults(_ x: inout Float) -> Float { x } // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @derivative(of: multipleSemanticResults) func vjpMultipleSemanticResults(_ x: inout Float) -> ( value: Float, pullback: (inout Float) -> Void ) { fatalError() } func inoutVoid(_ x: Float, _ void: inout Void) -> Float {} // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @derivative(of: inoutVoid) func vjpInoutVoidParameter(_ x: Float, _ void: inout Void) -> ( value: Float, pullback: (inout Float) -> Void ) { fatalError() } } // Test original/derivative function `inout` parameter mismatches. extension InoutParameters { // expected-note @+1 {{candidate instance method does not have expected type '(InoutParameters) -> (inout Float) -> Void'}} func inoutParameterMismatch(_ x: Float) {} // expected-error @+1 {{referenced declaration 'inoutParameterMismatch' could not be resolved}} @derivative(of: inoutParameterMismatch) func vjpInoutParameterMismatch(_ x: inout Float) -> (value: Void, pullback: (inout Float) -> Void) { fatalError() } // expected-note @+1 {{candidate instance method does not have expected type '(inout InoutParameters) -> (Float) -> Void'}} func mutatingMismatch(_ x: Float) {} // expected-error @+1 {{referenced declaration 'mutatingMismatch' could not be resolved}} @derivative(of: mutatingMismatch) mutating func vjpMutatingMismatch(_ x: Float) -> (value: Void, pullback: (inout Float) -> Void) { fatalError() } } // Test cross-file derivative registration. extension FloatingPoint where Self: Differentiable { @usableFromInline @derivative(of: rounded) func vjpRounded() -> ( value: Self, pullback: (Self.TangentVector) -> (Self.TangentVector) ) { fatalError() } } extension Differentiable where Self: AdditiveArithmetic { // expected-error @+1 {{referenced declaration '+' could not be resolved}} @derivative(of: +) static func vjpPlus(x: Self, y: Self) -> ( value: Self, pullback: (Self.TangentVector) -> (Self.TangentVector, Self.TangentVector) ) { return (x + y, { v in (v, v) }) } } extension AdditiveArithmetic where Self: Differentiable, Self == Self.TangentVector { // expected-error @+1 {{referenced declaration '+' could not be resolved}} @derivative(of: +) func vjpPlusInstanceMethod(x: Self, y: Self) -> ( value: Self, pullback: (Self) -> (Self, Self) ) { return (x + y, { v in (v, v) }) } } // Test derivatives of default implementations. protocol HasADefaultImplementation { func req(_ x: Float) -> Float } extension HasADefaultImplementation { func req(_ x: Float) -> Float { x } // ok @derivative(of: req) func req(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { (x, { 10 * $0 }) } } // Test default derivatives of requirements. protocol HasADefaultDerivative { // expected-note @+1 {{cannot yet register derivative default implementation for protocol requirements}} func req(_ x: Float) -> Float } extension HasADefaultDerivative { // TODO(TF-982): Support default derivatives for protocol requirements. // expected-error @+1 {{referenced declaration 'req' could not be resolved}} @derivative(of: req) func vjpReq(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { (x, { 10 * $0 }) } } // MARK: - Original function visibility = derivative function visibility public func public_original_public_derivative(_ x: Float) -> Float { x } @derivative(of: public_original_public_derivative) public func _public_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } public func public_original_usablefrominline_derivative(_ x: Float) -> Float { x } @usableFromInline @derivative(of: public_original_usablefrominline_derivative) func _public_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_internal_derivative(_ x: Float) -> Float { x } @derivative(of: internal_original_internal_derivative) func _internal_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_private_derivative(_ x: Float) -> Float { x } @derivative(of: private_original_private_derivative) private func _private_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } fileprivate func fileprivate_original_fileprivate_derivative(_ x: Float) -> Float { x } @derivative(of: fileprivate_original_fileprivate_derivative) fileprivate func _fileprivate_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_usablefrominline_derivative(_ x: Float) -> Float { x } @usableFromInline @derivative(of: internal_original_usablefrominline_derivative) func _internal_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_inlinable_derivative(_ x: Float) -> Float { x } @inlinable @derivative(of: internal_original_inlinable_derivative) func _internal_original_inlinable_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_alwaysemitintoclient_derivative(_ x: Float) -> Float { x } @_alwaysEmitIntoClient @derivative(of: internal_original_alwaysemitintoclient_derivative) func _internal_original_alwaysemitintoclient_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // MARK: - Original function visibility < derivative function visibility @usableFromInline func usablefrominline_original_public_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_usablefrominline_original_public_derivative' is public, but original function 'usablefrominline_original_public_derivative' is internal}} @derivative(of: usablefrominline_original_public_derivative) // expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}} public func _usablefrominline_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_public_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_public_derivative' is public, but original function 'internal_original_public_derivative' is internal}} @derivative(of: internal_original_public_derivative) // expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}} public func _internal_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_usablefrominline_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_usablefrominline_derivative' is internal, but original function 'private_original_usablefrominline_derivative' is private}} @derivative(of: private_original_usablefrominline_derivative) @usableFromInline // expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-1=private }} func _private_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_public_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_public_derivative' is public, but original function 'private_original_public_derivative' is private}} @derivative(of: private_original_public_derivative) // expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-7=private}} public func _private_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_internal_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_internal_derivative' is internal, but original function 'private_original_internal_derivative' is private}} @derivative(of: private_original_internal_derivative) // expected-note @+1 {{mark the derivative function as 'private' to match the original function}} func _private_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } fileprivate func fileprivate_original_private_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_fileprivate_original_private_derivative' is private, but original function 'fileprivate_original_private_derivative' is fileprivate}} @derivative(of: fileprivate_original_private_derivative) // expected-note @+1 {{mark the derivative function as 'fileprivate' to match the original function}} {{1-8=fileprivate}} private func _fileprivate_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_fileprivate_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_fileprivate_derivative' is fileprivate, but original function 'private_original_fileprivate_derivative' is private}} @derivative(of: private_original_fileprivate_derivative) // expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-12=private}} fileprivate func _private_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // MARK: - Original function visibility > derivative function visibility public func public_original_private_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_private_derivative' is fileprivate, but original function 'public_original_private_derivative' is public}} @derivative(of: public_original_private_derivative) // expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }} fileprivate func _public_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } public func public_original_internal_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_internal_derivative' is internal, but original function 'public_original_internal_derivative' is public}} @derivative(of: public_original_internal_derivative) // expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }} func _public_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_fileprivate_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_fileprivate_derivative' is fileprivate, but original function 'internal_original_fileprivate_derivative' is internal}} @derivative(of: internal_original_fileprivate_derivative) // expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-12=internal}} fileprivate func _internal_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // Test invalid reference to an accessor of a non-storage declaration. // expected-note @+1 {{candidate global function does not have a getter}} func function(_ x: Float) -> Float { x } // expected-error @+1 {{referenced declaration 'function' could not be resolved}} @derivative(of: function(_:).get) func vjpFunction(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // Test ambiguity that exists when Type function name is the same // as an accessor label. extension Float { // Original function name conflicts with an accessor name ("set"). func set() -> Float { self } // Original function name does not conflict with an accessor name. func method() -> Float { self } // Test ambiguous parse. // Expected: // - Base type: `Float` // - Declaration name: `set` // - Accessor kind: <none> // Actual: // - Base type: <none> // - Declaration name: `Float` // - Accessor kind: `set` // expected-error @+1 {{cannot find 'Float' in scope}} @derivative(of: Float.set) func jvpSet() -> (value: Float, differential: (Float) -> Float) { fatalError() } @derivative(of: Float.method) func jvpMethod() -> (value: Float, differential: (Float) -> Float) { fatalError() } } // Test original function with opaque result type. // expected-note @+1 {{candidate global function does not have expected type '(Float) -> Float'}} func opaqueResult(_ x: Float) -> some Differentiable { x } // expected-error @+1 {{referenced declaration 'opaqueResult' could not be resolved}} @derivative(of: opaqueResult) func vjpOpaqueResult(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // Test instance vs static method mismatch. struct StaticMismatch<T: Differentiable> { // expected-note @+1 {{original function 'init(_:)' is a 'static' method}} init(_ x: T) {} // expected-note @+1 {{original function 'instanceMethod' is an instance method}} func instanceMethod(_ x: T) -> T { x } // expected-note @+1 {{original function 'staticMethod' is a 'static' method}} static func staticMethod(_ x: T) -> T { x } // expected-error @+1 {{unexpected derivative function declaration; 'init(_:)' requires the derivative function 'vjpInit' to be a 'static' method}} @derivative(of: init) // expected-note @+1 {{make derivative function 'vjpInit' a 'static' method}}{{3-3=static }} func vjpInit(_ x: T) -> (value: Self, pullback: (T.TangentVector) -> T.TangentVector) { fatalError() } // expected-error @+1 {{unexpected derivative function declaration; 'instanceMethod' requires the derivative function 'jvpInstance' to be an instance method}} @derivative(of: instanceMethod) // expected-note @+1 {{make derivative function 'jvpInstance' an instance method}}{{3-10=}} static func jvpInstance(_ x: T) -> ( value: T, differential: (T.TangentVector) -> (T.TangentVector) ) { return (x, { $0 }) } // expected-error @+1 {{unexpected derivative function declaration; 'staticMethod' requires the derivative function 'jvpStatic' to be a 'static' method}} @derivative(of: staticMethod) // expected-note @+1 {{make derivative function 'jvpStatic' a 'static' method}}{{3-3=static }} func jvpStatic(_ x: T) -> ( value: T, differential: (T.TangentVector) -> (T.TangentVector) ) { return (x, { $0 }) } }
apache-2.0
0b965fdd9c0a682b015396d77eacde14
37.521849
256
0.688358
3.863874
false
false
false
false
jngd/advanced-ios10-training
T2E04/T2E04/ViewController.swift
1
870
// // ViewController.swift // T2E04 // // Created by jngd on 18/09/16. // Copyright © 2016 jngd. All rights reserved. // import UIKit class ViewController: UIViewController, UIViewControllerTransitioningDelegate { var bounce : BounceTransition! override func viewDidLoad() { self.bounce = BounceTransition() super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "showCustomTransition"){ let toVC : UIViewController = segue.destination as UIViewController toVC.transitioningDelegate = self } } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self.bounce } }
apache-2.0
41c0ece4a985b00334c7c531a479fdf5
21.868421
167
0.750288
4.388889
false
false
false
false
frootloops/swift
stdlib/public/core/Misc.swift
1
4430
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Extern C functions //===----------------------------------------------------------------------===// // FIXME: Once we have an FFI interface, make these have proper function bodies @_inlineable // FIXME(sil-serialize-all) @_transparent public // @testable func _countLeadingZeros(_ value: Int64) -> Int64 { return Int64(Builtin.int_ctlz_Int64(value._value, false._value)) } /// Returns if `x` is a power of 2. @_inlineable // FIXME(sil-serialize-all) @_transparent public // @testable func _isPowerOf2(_ x: UInt) -> Bool { if x == 0 { return false } // Note: use unchecked subtraction because we have checked that `x` is not // zero. return x & (x &- 1) == 0 } /// Returns if `x` is a power of 2. @_inlineable // FIXME(sil-serialize-all) @_transparent public // @testable func _isPowerOf2(_ x: Int) -> Bool { if x <= 0 { return false } // Note: use unchecked subtraction because we have checked that `x` is not // `Int.min`. return x & (x &- 1) == 0 } #if _runtime(_ObjC) @_inlineable // FIXME(sil-serialize-all) @_transparent public func _autorelease(_ x: AnyObject) { Builtin.retain(x) Builtin.autorelease(x) } #endif /// Invoke `body` with an allocated, but uninitialized memory suitable for a /// `String` value. /// /// This function is primarily useful to call various runtime functions /// written in C++. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _withUninitializedString<R>( _ body: (UnsafeMutablePointer<String>) -> R ) -> (R, String) { let stringPtr = UnsafeMutablePointer<String>.allocate(capacity: 1) let bodyResult = body(stringPtr) let stringResult = stringPtr.move() stringPtr.deallocate() return (bodyResult, stringResult) } // FIXME(ABI)#51 : this API should allow controlling different kinds of // qualification separately: qualification with module names and qualification // with type names that we are nested in. // But we can place it behind #if _runtime(_Native) and remove it from ABI on // Apple platforms, deferring discussions mentioned above. @_inlineable // FIXME(sil-serialize-all) @_silgen_name("swift_getTypeName") public func _getTypeName(_ type: Any.Type, qualified: Bool) -> (UnsafePointer<UInt8>, Int) /// Returns the demangled qualified name of a metatype. @_inlineable // FIXME(sil-serialize-all) public // @testable func _typeName(_ type: Any.Type, qualified: Bool = true) -> String { let (stringPtr, count) = _getTypeName(type, qualified: qualified) return ._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: stringPtr, count: count)) } @_silgen_name("") internal func _getTypeByName( _ name: UnsafePointer<UInt8>, _ nameLength: UInt) -> Any.Type? /// Lookup a class given a name. Until the demangled encoding of type /// names is stabilized, this is limited to top-level class names (Foo.bar). public // SPI(Foundation) func _typeByName(_ name: String) -> Any.Type? { let nameUTF8 = Array(name.utf8) return nameUTF8.withUnsafeBufferPointer { (nameUTF8) in let type = _getTypeByName(nameUTF8.baseAddress!, UInt(nameUTF8.endIndex)) return type } } /// Returns `floor(log(x))`. This equals to the position of the most /// significant non-zero bit, or 63 - number-of-zeros before it. /// /// The function is only defined for positive values of `x`. /// /// Examples: /// /// floorLog2(1) == 0 /// floorLog2(2) == floorLog2(3) == 1 /// floorLog2(9) == floorLog2(15) == 3 /// /// TODO: Implement version working on Int instead of Int64. @_inlineable // FIXME(sil-serialize-all) @_transparent public // @testable func _floorLog2(_ x: Int64) -> Int { _sanityCheck(x > 0, "_floorLog2 operates only on non-negative integers") // Note: use unchecked subtraction because we this expression cannot // overflow. return 63 &- Int(_countLeadingZeros(x)) }
apache-2.0
c1470317ba6d8a0b2d25ef8e280e3322
32.059701
80
0.656208
3.948307
false
false
false
false
umarF/MultiSelectHeaders
MultiSelectHeader/TeamModel.swift
1
1731
/* Copyright (c) 2017 Umar Farooque. 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 struct TeamModel{ var teamName: String = "" var teamValue: String = "" var founded: String = "" // MARK : TODO Check if nil is 0 or something else mutating func setEmptyObject() -> TeamModel { self.teamName = "" self.teamValue = "" self.founded = "" return self } mutating func setTeams(returnDict: [String:Any]) -> TeamModel { self.teamName = returnDict["teamName"] as? String ?? "" self.teamValue = returnDict["teamValue"] as? String ?? "" self.founded = returnDict["founded"] as? String ?? "" return self } }
mit
86fa4c7774dce99536c04b5c1276c0a8
34.326531
79
0.70364
4.507813
false
false
false
false
slavapestov/swift
test/ClangModules/availability_implicit_macosx.swift
2
4300
// RUN: %swift -parse -verify -target x86_64-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift // RUN: not %swift -parse -target x86_64-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift 2>&1 | FileCheck %s '--implicit-check-not=<unknown>:0' // REQUIRES: OS=macosx // This is a temporary test for checking of availability diagnostics (explicit unavailability, // deprecation, and potential unavailability) in synthesized code. After this checking // is fully staged in, the tests in this file will be moved. // import Foundation func useClassThatTriggersImportOfDeprecatedEnum() { // Check to make sure that the bodies of enum methods that are synthesized // when importing deprecated enums do not themselves trigger deprecation // warnings in the synthesized code. _ = NSClassWithDeprecatedOptionsInMethodSignature.sharedInstance() } func useClassThatTriggersImportOExplicitlyUnavailableOptions() { _ = NSClassWithPotentiallyUnavailableOptionsInMethodSignature.sharedInstance() } func useClassThatTriggersImportOfPotentiallyUnavailableOptions() { _ = NSClassWithExplicitlyUnavailableOptionsInMethodSignature.sharedInstance() } func directUseShouldStillTriggerDeprecationWarning() { _ = NSDeprecatedOptions.First // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.51: Use a different API}} _ = NSDeprecatedEnum.First // expected-warning {{'NSDeprecatedEnum' was deprecated in OS X 10.51: Use a different API}} } func useInSignature(options: NSDeprecatedOptions) { // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.51: Use a different API}} } class SuperClassWithDeprecatedInitializer { @available(OSX, introduced=10.9, deprecated=10.51) init() { } } class SubClassWithSynthesizedDesignedInitializerOverride : SuperClassWithDeprecatedInitializer { // The synthesized designated initializer override calls super.init(), which is // deprecated, so the synthesized initializer is marked as deprecated as well. // This does not generate a warning here (perhaps it should?) but any call // to Sub's initializer will cause a deprecation warning. } func callImplicitInitializerOnSubClassWithSynthesizedDesignedInitializerOverride() { _ = SubClassWithSynthesizedDesignedInitializerOverride() // expected-warning {{'init()' was deprecated in OS X 10.51}} } @available(OSX, introduced=10.9, deprecated=10.51) class DeprecatedSuperClass { var i : Int = 7 // Causes initializer to be synthesized } class NotDeprecatedSubClassOfDeprecatedSuperClass : DeprecatedSuperClass { // expected-warning {{'DeprecatedSuperClass' was deprecated in OS X 10.51}} } func callImplicitInitializerOnNotDeprecatedSubClassOfDeprecatedSuperClass() { // We do not expect a warning here because the synthesized initializer // in NotDeprecatedSubClassOfDeprecatedSuperClass is not itself marked // deprecated. _ = NotDeprecatedSubClassOfDeprecatedSuperClass() } @available(OSX, introduced=10.9, deprecated=10.51) class DeprecatedSubClassOfDeprecatedSuperClass : DeprecatedSuperClass { } // Tests synthesis of materializeForSet class ClassWithLimitedAvailabilityAccessors { var limitedGetter: Int { @available(OSX, introduced=10.52) get { return 10 } set(newVal) {} } var limitedSetter: Int { get { return 10 } @available(OSX, introduced=10.52) set(newVal) {} } } @available(*, unavailable) func unavailableFunction() -> Int { return 10 } // expected-note 3{{'unavailableFunction()' has been explicitly marked unavailable here}} class ClassWithReferencesLazyInitializers { var propWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} lazy var lazyPropWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} } @available(*, unavailable) func unavailableUseInUnavailableFunction() { // Diagnose references to unavailable functions in non-implicit code // as errors unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} } @available(OSX 10.52, *) func foo() { let _ = SubOfOtherWithInit() }
apache-2.0
58a7bf58d4c2672248edcf06f159209d
38.449541
215
0.775814
4.374364
false
false
false
false
xwu/swift
test/Constraints/ranking.swift
1
15615
// RUN: %target-swift-emit-silgen %s -verify -swift-version 5 | %FileCheck %s protocol P { var p: P { get set } var q: P? { get set } func p(_: P) func q(_: P) } struct S : P { var p: P var q: P? func p(_: P) {} func q(_: P) {} } class Base : P { var p: P var q: P? func p(_: P) {} func q(_: P) {} init(_ p: P) { self.p = p } } class Derived : Base { } func genericOverload<T>(_: T) {} func genericOverload<T>(_: T?) {} func genericOptional<T>(_: T?) {} func genericNoOptional<T>(_: T) {} // CHECK-LABEL: sil hidden [ossa] @$s7ranking22propertyVersusFunctionyyAA1P_p_xtAaCRzlF func propertyVersusFunction<T : P>(_ p: P, _ t: T) { // CHECK: witness_method $@opened("{{.*}}") P, #P.p!getter let _ = p.p // CHECK: witness_method $@opened("{{.*}}") P, #P.p!getter let _: P = p.p // CHECK: function_ref @$s7ranking22propertyVersusFunctionyyAA1P_p_xtAaCRzlFyAaC_pcAaC_pcfu_ : $@convention(thin) (@in_guaranteed P) -> @owned @callee_guaranteed (@in_guaranteed P) -> () let _: (P) -> () = p.p // CHECK: witness_method $@opened("{{.*}}") P, #P.p!getter let _: P? = p.p // CHECK: witness_method $@opened("{{.*}}") P, #P.p!getter let _: Any = p.p // CHECK: witness_method $@opened("{{.*}}") P, #P.p!getter let _: Any? = p.p // CHECK: witness_method $@opened("{{.*}}") P, #P.p!getter // CHECK: function_ref @$s7ranking15genericOverloadyyxlF genericOverload(p.p) // CHECK: witness_method $@opened("{{.*}}") P, #P.q!getter // CHECK: function_ref @$s7ranking15genericOverloadyyxSglF genericOverload(p.q) // CHECK: witness_method $@opened("{{.*}}") P, #P.p!getter // CHECK: function_ref @$s7ranking15genericOptionalyyxSglF genericOptional(p.p) // CHECK: witness_method $@opened("{{.*}}") P, #P.q!getter // CHECK: function_ref @$s7ranking15genericOptionalyyxSglF genericOptional(p.q) // CHECK: witness_method $@opened("{{.*}}") P, #P.p!getter // CHECK: function_ref @$s7ranking17genericNoOptionalyyxlF genericNoOptional(p.p) // CHECK: witness_method $@opened("{{.*}}") P, #P.q!getter // CHECK: function_ref @$s7ranking17genericNoOptionalyyxlF genericNoOptional(p.q) // CHECK: witness_method $T, #P.p!getter let _ = t.p // CHECK: witness_method $T, #P.p!getter let _: P = t.p // CHECK: function_ref @$s7ranking22propertyVersusFunctionyyAA1P_p_xtAaCRzlFyAaC_pcxcfu1_ : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed (@in_guaranteed P) -> () let _: (P) -> () = t.p // CHECK: witness_method $T, #P.p!getter let _: P? = t.p // CHECK: witness_method $T, #P.p!getter let _: Any = t.p // CHECK: witness_method $T, #P.p!getter let _: Any? = t.p // CHECK: witness_method $T, #P.p!getter // CHECK: function_ref @$s7ranking15genericOverloadyyxlF genericOverload(t.p) // CHECK: witness_method $T, #P.q!getter // CHECK: function_ref @$s7ranking15genericOverloadyyxSglF genericOverload(t.q) // CHECK: witness_method $T, #P.p!getter // CHECK: function_ref @$s7ranking15genericOptionalyyxSglF genericOptional(t.p) // CHECK: witness_method $T, #P.q!getter // CHECK: function_ref @$s7ranking15genericOptionalyyxSglF genericOptional(t.q) // CHECK: witness_method $T, #P.p!getter // CHECK: function_ref @$s7ranking17genericNoOptionalyyxlF genericNoOptional(t.p) // CHECK: witness_method $T, #P.q!getter // CHECK: function_ref @$s7ranking17genericNoOptionalyyxlF genericNoOptional(t.q) } extension P { func propertyVersusFunction() { // CHECK: witness_method $Self, #P.p!getter let _ = self.p // CHECK: witness_method $Self, #P.p!getter let _: P = self.p // CHECK: function_ref @$s7ranking1PPAAE22propertyVersusFunctionyyFyAaB_pcxcfu_ : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed (@in_guaranteed P) -> () let _: (P) -> () = self.p // CHECK: witness_method $Self, #P.p!getter let _: P? = self.p // CHECK: witness_method $Self, #P.p!getter let _: Any = self.p // CHECK: witness_method $Self, #P.p!getter let _: Any? = self.p // CHECK: witness_method $Self, #P.p!getter // CHECK: function_ref @$s7ranking15genericOverloadyyxlF genericOverload(self.p) // CHECK: witness_method $Self, #P.q!getter // CHECK: function_ref @$s7ranking15genericOverloadyyxSglF genericOverload(self.q) // CHECK: witness_method $Self, #P.p!getter // CHECK: function_ref @$s7ranking15genericOptionalyyxSglF genericOptional(self.p) // CHECK: witness_method $Self, #P.q!getter // CHECK: function_ref @$s7ranking15genericOptionalyyxSglF genericOptional(self.q) // CHECK: witness_method $Self, #P.p!getter // CHECK: function_ref @$s7ranking17genericNoOptionalyyxlF genericNoOptional(self.p) // CHECK: witness_method $Self, #P.q!getter // CHECK: function_ref @$s7ranking17genericNoOptionalyyxlF genericNoOptional(self.q) } } //-------------------------------------------------------------------- func f0<T>(_ x: T) {} // FIXME: Lookup breaks if these come after f1! class A { init() {} }; class B : A { override init() { super.init() } } func f1(_ a: A) -> A { return a } func f1(_ b: B) -> B { return b } func testDerived(b: B) { // CHECK-LABEL: sil hidden [ossa] @$s7ranking11testDerived1byAA1BC_tF // CHECK: function_ref @$s7ranking2f1yAA1BCADF // CHECK: function_ref @$s7ranking2f0yyxlF f0(f1(b)) // CHECK: end sil function '$s7ranking11testDerived1byAA1BC_tF' } protocol X { var foo: Int { get } var bar: Int { get } func baz() -> Int subscript(foo: String) -> Int { get } } class Y { var foo: Int = 0 func baz() -> Int { return foo } subscript(foo: String) -> Int { return 0 } } extension Y { var bar: Int { return foo } } protocol Z : Y { var foo: Int { get } var bar: Int { get } func baz() -> Int subscript(foo: String) -> Int { get } } class GenericClass<T> { var foo: T init(_ foo: T) { self.foo = foo } func baz() -> T { return foo } } extension GenericClass { var bar: T { return foo } subscript(foo: String) -> Int { return 0 } } // Make sure we favour the class implementation over the protocol requirement. // CHECK-LABEL: sil hidden [ossa] @$s7ranking32testGenericPropertyProtocolClassyyxAA1YCRbzAA1XRzlF func testGenericPropertyProtocolClass<T : X & Y>(_ t: T) { _ = t.foo // CHECK: class_method {{%.*}} : $Y, #Y.foo!getter _ = t.bar // CHECK: function_ref @$s7ranking1YC3barSivg _ = t.baz() // CHECK: class_method {{%.*}} : $Y, #Y.baz _ = t[""] // CHECK: class_method {{%.*}} : $Y, #Y.subscript!getter } // CHECK-LABEL: sil hidden [ossa] @$s7ranking36testExistentialPropertyProtocolClassyyAA1X_AA1YCXcF func testExistentialPropertyProtocolClass(_ t: X & Y) { _ = t.foo // CHECK: class_method {{%.*}} : $Y, #Y.foo!getter _ = t.bar // CHECK: function_ref @$s7ranking1YC3barSivg _ = t.baz() // CHECK: class_method {{%.*}} : $Y, #Y.baz _ = t[""] // CHECK: class_method {{%.*}} : $Y, #Y.subscript!getter } // CHECK-LABEL: sil hidden [ossa] @$s7ranking46testGenericPropertySubclassConstrainedProtocolyyxAA1ZRzlF func testGenericPropertySubclassConstrainedProtocol<T : Z>(_ t: T) { _ = t.foo // CHECK: class_method {{%.*}} : $Y, #Y.foo!getter _ = t.bar // CHECK: function_ref @$s7ranking1YC3barSivg _ = t.baz() // CHECK: class_method {{%.*}} : $Y, #Y.baz _ = t[""] // CHECK: class_method {{%.*}} : $Y, #Y.subscript!getter } // CHECK-LABEL: sil hidden [ossa] @$s7ranking50testExistentialPropertySubclassConstrainedProtocolyyAA1Z_pF func testExistentialPropertySubclassConstrainedProtocol(_ t: Z) { _ = t.foo // CHECK: class_method {{%.*}} : $Y, #Y.foo!getter _ = t.bar // CHECK: function_ref @$s7ranking1YC3barSivg _ = t.baz() // CHECK: class_method {{%.*}} : $Y, #Y.baz _ = t[""] // CHECK: class_method {{%.*}} : $Y, #Y.subscript!getter } // CHECK-LABEL: sil hidden [ossa] @$s7ranking43testExistentialPropertyProtocolGenericClassyyAA1X_AA0fG0CySiGXcF func testExistentialPropertyProtocolGenericClass(_ t: GenericClass<Int> & X) { _ = t.foo // CHECK: class_method {{%.*}} : $GenericClass<Int>, #GenericClass.foo!getter _ = t.bar // CHECK: function_ref @$s7ranking12GenericClassC3barxvg _ = t.baz() // CHECK: class_method {{%.*}} : $GenericClass<Int>, #GenericClass.baz _ = t[""] // CHECK: function_ref @$s7ranking12GenericClassCySiSScig } // CHECK-LABEL: sil hidden [ossa] @$s7ranking43testExistentialPropertyProtocolGenericClassyyAA1X_AA0fG0CySSGXcF func testExistentialPropertyProtocolGenericClass(_ t: GenericClass<String> & X) { _ = t.foo // CHECK: class_method {{%.*}} : $GenericClass<String>, #GenericClass.foo!getter _ = t.bar // CHECK: function_ref @$s7ranking12GenericClassC3barxvg _ = t.baz() // CHECK: class_method {{%.*}} : $GenericClass<String>, #GenericClass.baz _ = t[""] // CHECK: function_ref @$s7ranking12GenericClassCySiSScig } extension X where Self : Y { // CHECK-LABEL: sil hidden [ossa] @$s7ranking1XPA2A1YCRbzrlE32testGenericPropertyProtocolClassyyxF func testGenericPropertyProtocolClass(_ x: Self) { _ = self.foo // CHECK: class_method {{%.*}} : $Y, #Y.foo!getter _ = self.bar // CHECK: function_ref @$s7ranking1YC3barSivg _ = self.baz() // CHECK: class_method {{%.*}} : $Y, #Y.baz _ = self[""] // CHECK: class_method {{%.*}} : $Y, #Y.subscript!getter } } extension X where Self : GenericClass<Int> { // CHECK-LABEL: sil hidden [ossa] @$s7ranking1XPA2A12GenericClassCySiGRbzrlE04testb16PropertyProtocolbC0yyxF func testGenericPropertyProtocolGenericClass(_ x: Self) { _ = self.foo // CHECK: class_method {{%.*}} : $GenericClass<Int>, #GenericClass.foo!getter _ = self.bar // CHECK: function_ref @$s7ranking12GenericClassC3barxvg _ = self.baz() // CHECK: class_method {{%.*}} : $GenericClass<Int>, #GenericClass.baz _ = self[""] // CHECK: function_ref @$s7ranking12GenericClassCySiSScig } } extension X where Self : GenericClass<String> { // CHECK-LABEL: sil hidden [ossa] @$s7ranking1XPA2A12GenericClassCySSGRbzrlE04testb16PropertyProtocolbC0yyxF func testGenericPropertyProtocolGenericClass(_ x: Self) { _ = self.foo // CHECK: class_method {{%.*}} : $GenericClass<String>, #GenericClass.foo!getter _ = self.bar // CHECK: function_ref @$s7ranking12GenericClassC3barxvg _ = self.baz() // CHECK: class_method {{%.*}} : $GenericClass<String>, #GenericClass.baz _ = self[""] // CHECK: function_ref @$s7ranking12GenericClassCySiSScig } } //-------------------------------------------------------------------- // Constructor-specific ranking //-------------------------------------------------------------------- // We have a special ranking rule that only currently applies to constructors, // and compares the concrete parameter types. protocol Q { init() } struct S1<T : Q> { // We want to prefer the non-optional init over the optional init here. init(_ x: T = .init()) {} init(_ x: T? = nil) {} // CHECK-LABEL: sil hidden [ossa] @$s7ranking2S1V11testRankingACyxGyt_tcfC init(testRanking: Void) { // CHECK: function_ref @$s7ranking2S1VyACyxGxcfC : $@convention(method) <τ_0_0 where τ_0_0 : Q> (@in τ_0_0, @thin S1<τ_0_0>.Type) -> S1<τ_0_0> self.init() } // CHECK-LABEL: sil hidden [ossa] @$s7ranking2S1V15testInitRankingyyF func testInitRanking() { // CHECK: function_ref @$s7ranking2S1VyACyxGxcfC : $@convention(method) <τ_0_0 where τ_0_0 : Q> (@in τ_0_0, @thin S1<τ_0_0>.Type) -> S1<τ_0_0> _ = S1<T>() } } protocol R {} extension Array : R {} extension Int : R {} struct S2 { init(_ x: R) {} init(_ x: Int...) {} // CHECK-LABEL: sil hidden [ossa] @$s7ranking2S2V15testInitRankingyyF func testInitRanking() { // We currently prefer the non-variadic init due to having // "less effective parameters", and we don't compare the types for ranking due // to the difference in variadic-ness. // CHECK: function_ref @$s7ranking2S2VyAcA1R_pcfC : $@convention(method) (@in R, @thin S2.Type) -> S2 _ = S2(0) } } // Very cursed: As a holdover from how we used to represent function inputs, // we rank these as tuples and consider (x:x:) to be a subtype of (x:y:). Seems // unlikely this is being relied on in the real world, but let's at least have // it as a test case to track its behavior. struct S3 { init(x _: Int = 0, y _: Int = 0) {} init(x _: Int = 0, x _: Int = 0) {} func testInitRanking() { // CHECK: function_ref @$s7ranking2S3V1xAdCSi_SitcfC : $@convention(method) (Int, Int, @thin S3.Type) -> S3 _ = S3() } } // Also another consequence of having ranked as tuples: we prefer the unlabeled // init here. struct S4 { init(x: Int = 0, y: Int = 0) {} init(_ x: Int = 0, _ y: Int = 0) {} // CHECK-LABEL: sil hidden [ossa] @$s7ranking2S4V15testInitRankingyyF func testInitRanking() { // CHECK: function_ref @$s7ranking2S4VyACSi_SitcfC : $@convention(method) (Int, Int, @thin S4.Type) -> S4 _ = S4() } } // rdar://84279742 – Make sure we prefer the unlabeled init here. struct S5 { init(x: Int...) {} init(_ x: Int...) {} // CHECK-LABEL: sil hidden [ossa] @$s7ranking2S5V15testInitRankingyyF func testInitRanking() { // CHECK: function_ref @$s7ranking2S5VyACSid_tcfC : $@convention(method) (@owned Array<Int>, @thin S5.Type) -> S5 _ = S5() } } // We should also prefer the unlabeled case here. struct S6 { init(_: Int = 0, x: Int...) {} init(_: Int = 0, _: Int...) {} // CHECK-LABEL: sil hidden [ossa] @$s7ranking2S6V15testInitRankingyyF func testInitRanking() { // CHECK: function_ref @$s7ranking2S6VyACSi_SidtcfC : $@convention(method) (Int, @owned Array<Int>, @thin S6.Type) -> S6 _ = S6() } } // However subtyping rules take precedence over labeling rules, so we should // prefer the labeled init here. struct S7 { init(x: Int...) {} init(_: Int?...) {} // CHECK-LABEL: sil hidden [ossa] @$s7ranking2S7V15testInitRankingyyF func testInitRanking() { // CHECK: function_ref @$s7ranking2S7V1xACSid_tcfC : $@convention(method) (@owned Array<Int>, @thin S7.Type) -> S7 _ = S7() } } // Subtyping rules also let us prefer the Int... init here. struct S8 { init(_: Int?...) {} init(_: Int...) {} // CHECK-LABEL: sil hidden [ossa] @$s7ranking2S8V15testInitRankingyyF func testInitRanking() { // CHECK: function_ref @$s7ranking2S8VyACSid_tcfC : $@convention(method) (@owned Array<Int>, @thin S8.Type) -> S8 _ = S8() } } //-------------------------------------------------------------------- // Pointer conversions //-------------------------------------------------------------------- struct UnsafePointerStruct { // CHECK-LABEL: sil hidden [ossa] @$s7ranking19UnsafePointerStructVyACSPyxGSgclufC : $@convention(method) <U> (Optional<UnsafePointer<U>>, @thin UnsafePointerStruct.Type) -> UnsafePointerStruct init<U>(_ from: UnsafePointer<U>) {} init<U>(_ from: UnsafePointer<U>?) { // CHECK: function_ref @$s7ranking19UnsafePointerStructVyACSPyxGclufC : $@convention(method) <τ_0_0> (UnsafePointer<τ_0_0>, @thin UnsafePointerStruct.Type) -> UnsafePointerStruct self.init(from!) } } // CHECK-LABEL: sil hidden [ossa] @$s7ranking22useUnsafePointerStructyySPyxGlF : $@convention(thin) <U> (UnsafePointer<U>) -> () func useUnsafePointerStruct<U>(_ ptr: UnsafePointer<U>) { // CHECK: function_ref @$s7ranking19UnsafePointerStructVyACSPyxGclufC : $@convention(method) <τ_0_0> (UnsafePointer<τ_0_0>, @thin UnsafePointerStruct.Type) -> UnsafePointerStruct let _: UnsafePointerStruct = UnsafePointerStruct(ptr) }
apache-2.0
0a9e21da5a5417c6c7f5c2211bb1cf14
36.847087
213
0.639838
3.305703
false
true
false
false
danielhour/DINC
DINC WatchKit Extension/StringExtensions.swift
1
2558
// // StringExtensions.swift // DINC // // Created by dhour on 4/15/16. // Copyright © 2016 DHour. All rights reserved. // import Foundation extension String { /** Currency w/o decimals */ var currencyNoDecimals: String { let converter = NumberFormatter() converter.decimalSeparator = "." let styler = NumberFormatter() styler.minimumFractionDigits = 0 styler.maximumFractionDigits = 0 styler.currencySymbol = "$" styler.numberStyle = .currency if let result = converter.number(from: self) { return styler.string(from: result)! } else { converter.decimalSeparator = "," if let result = converter.number(from: self) { return styler.string(from: result)! } } return "" } /** Converts a raw string to a string currency w/ 2 decimals */ var currencyFromString: String { let converter = NumberFormatter() converter.decimalSeparator = "." let styler = NumberFormatter() styler.minimumFractionDigits = 2 styler.maximumFractionDigits = 2 styler.currencySymbol = "$" styler.numberStyle = .currency if let result = converter.number(from: self) { let realNumber = Double(result) return styler.string(from: NSNumber(value: realNumber))! } else { converter.decimalSeparator = "," if let result = converter.number(from: self) { return styler.string(from: result)! } } return self } /** Converts a raw string to a string currency w/ 2 decimals */ var currencyAppend: String { let converter = NumberFormatter() converter.decimalSeparator = "." let styler = NumberFormatter() styler.minimumFractionDigits = 2 styler.maximumFractionDigits = 2 styler.currencySymbol = "$" styler.numberStyle = .currency if let result = converter.number(from: self) { let realNumber = Double(result)/100 return styler.string(from: NSNumber(value: realNumber))! } else { converter.decimalSeparator = "," if let result = converter.number(from: self) { return styler.string(from: result)! } } return "" } }
mit
ad891a473ac9b1b3ce7f2d9595400692
25.915789
68
0.545952
5.360587
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/RightSide/Search/Controllers/SearchDetailViewController.swift
1
7719
// // SearchDetailViewController.swift // zhuishushenqi // // Created by Nory Cao on 2017/3/11. // Copyright © 2017年 QS. All rights reserved. // import UIKit //import YTKKeyValueStore class SearchDetailViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate,SearchViewDelegate { var books = [Book]() var searchWords:String = "" var store:YTKKeyValueStore? let storeKey = "SearchHistory" var historyList:[String]? lazy var searchView:SearchView = { let searchView = SearchView(frame: CGRect(x: 0, y: 108, width: ScreenWidth, height: ScreenHeight - 108)) searchView.delegate = self return searchView }() fileprivate lazy var tableView:UITableView = { let tableView = UITableView(frame: CGRect(x: 0, y:108, width: ScreenWidth, height: ScreenHeight - 108), style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.sectionHeaderHeight = CGFloat.leastNormalMagnitude tableView.sectionFooterHeight = CGFloat.leastNormalMagnitude tableView.rowHeight = 93 tableView.qs_registerCellNib(TopDetailCell.self) return tableView }() fileprivate lazy var searchController:UISearchController = { let searchVC:UISearchController = UISearchController(searchResultsController: nil) searchVC.searchBar.placeholder = "输入书名或作者名" searchVC.searchResultsUpdater = self searchVC.delegate = self searchVC.searchBar.delegate = self searchVC.hidesNavigationBarDuringPresentation = true searchVC.searchBar.sizeToFit() searchVC.searchBar.backgroundColor = UIColor.darkGray return searchVC }() override func viewDidLoad() { super.viewDidLoad() title = "搜索" self.automaticallyAdjustsScrollViewInsets = false requestHot() initSubview() let store = YTKKeyValueStore(dbWithName: dbName) if store?.isTableExists(searchHistory) == false { store?.createTable(withName: searchHistory) } self.store = store self.historyList = store?.getObjectById(storeKey, fromTable: searchHistory) as? [String] searchView.historyList = historyList } func searchViewClearButtonClicked() { store?.clearTable(searchHistory) self.historyList = store?.getObjectById(storeKey, fromTable: searchHistory) as? [String] searchView.historyList = historyList } func searchViewHotWordClick(index: Int){ searchController.dismiss(animated: true, completion: nil) searchController.searchBar.text = searchView.hotWords[index] self.saveHistoryList(searchBar: searchController.searchBar) self.searchWords = searchController.searchBar.text ?? "" requestData() } func requestData(){ // http://api.zhuishushenqi.com/book/fuzzy-search?query=偷&start=0&limit=100 let urlString = "\(BASEURL)/book/fuzzy-search" let param = ["query":self.searchWords,"start":"0","limit":"100"] zs_get(urlString, parameters: param) { (response) in QSLog(response) if let books = response?["books"] { if let models = [Book].deserialize(from: books as? [Any]) as? [Book] { self.books = models } } DispatchQueue.main.async { self.view.addSubview(self.tableView) self.tableView.reloadData() } } } func requestHot() -> Void { // http://api.zhuishushenqi.com/book/hot-word let urlString = "\(BASEURL)/book/hot-word" zs_get(urlString, parameters: nil) { (response) in QSLog(response) if let json = response { DispatchQueue.main.async { self.searchView.hotWords = json["hotWords"] as? [String] ?? [""] self.view.addSubview(self.searchView) } } } } func initSubview(){ let bgView = UIView() // [UIColor colorWithRed:0.94f green:0.94f blue:0.96f alpha:1.00f]; bgView.backgroundColor = UIColor(red: 0.94, green: 0.94, blue: 0.96, alpha: 1.0) bgView.frame = CGRect(x: 0, y: 64, width: self.view.bounds.width, height: 44) bgView.addSubview(self.searchController.searchBar) view.addSubview(bgView) } func isExistSearchWord(key:String)->Bool{ var isExist = false if let list = historyList { for item in list { if item == key { isExist = true } } } return isExist } func willPresentSearchController(_ searchController: UISearchController){ UIView.animate(withDuration: 0.35) { self.searchView.frame = CGRect(x: 0, y: 64, width: ScreenWidth, height: ScreenHeight - 64) self.view.addSubview(self.searchView) } } func willDismissSearchController(_ searchController: UISearchController) { UIView.animate(withDuration: 0.35) { self.searchView.frame = CGRect(x: 0, y: 108, width: ScreenWidth, height: ScreenHeight - 108) } } func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { return true }// return NO to not become first responder func saveHistoryList(searchBar:UISearchBar){ let exist = self.isExistSearchWord(key: searchBar.text ?? "") if exist == false { if let text = searchBar.text ,searchBar.text?.trimmingCharacters(in: CharacterSet(charactersIn: " ")) != "" { if historyList == nil { historyList = [text] } else { historyList?.append(text) } store?.put(historyList, withId: storeKey, intoTable: searchHistory) searchView.historyList = historyList } } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar){ self.saveHistoryList(searchBar: searchBar) self.searchWords = searchBar.text ?? "" searchController.dismiss(animated: true, completion: nil) searchView.removeFromSuperview() requestData() }// called when keyboard search button pressed func searchBarCancelButtonClicked(_ searchBar: UISearchBar){ }// called when cancel button pressed func updateSearchResults(for searchController: UISearchController){ self.searchWords = self.searchController.searchBar.text ?? "" } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.books.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:TopDetailCell? = tableView.qs_dequeueReusableCell(TopDetailCell.self) cell?.backgroundColor = UIColor.white cell?.selectionStyle = .none cell!.model = self.books.count > indexPath.row ? books[indexPath.row]:nil return cell! } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return tableView.sectionHeaderHeight } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
d04485106f1c897a1f516487d3ef320d
36.169082
186
0.626852
5.018917
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/TableViewFooterSelfSizing.swift
1
2748
// // ViewController.swift // RunTime // // Created by 伯驹 黄 on 2016/10/19. // Copyright © 2016年 伯驹 黄. All rights reserved. // import UIKit class TableViewFooterSelfSizing: UIViewController { fileprivate lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.frame, style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") return tableView }() lazy var data: [[UIViewController.Type]] = [ [ FriendTableViewController.self, PagingEnabled.self, InfiniteScrollViewController.self, ScrollViewController.self ], [ SignInController.self ] ] let textLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() title = "CycleViewController" view.addSubview(tableView) let footerView = UIView() footerView.backgroundColor = .red tableView.tableFooterView = footerView textLabel.text = "作为开发人员,理解HTTPS的原理和应用算是一项基本技能。HTTPS目前来说是非常安全的,但仍然有大量的公司还在使用HTTP。其实HTTPS也并不是很贵啊。" textLabel.numberOfLines = 0 footerView.addSubview(textLabel) textLabel.snp.makeConstraints { (make) in make.top.height.equalToSuperview() make.width.equalTo(tableView) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.sizeFooterToFit() } } extension TableViewFooterSelfSizing: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return data.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) } } extension TableViewFooterSelfSizing: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.textLabel?.text = "\(data[indexPath.section][indexPath.row].classForCoder())" } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { textLabel.text! += "在网上可以找到大把的介绍HTTTPS的文章,在阅读ServerTrustPolicy.swfit代码前,我们先简单的讲一下HTTPS请求的过程:" } }
mit
47f97fa6fdc4c88e781289ec7fad2ef5
29.22619
112
0.667192
4.799622
false
false
false
false
MengQuietly/MQDouYuTV
MQDouYuTV/MQDouYuTV/Classes/Home/ViewModel/MQRecommentViewModel.swift
1
6145
// // MQRecommentViewModel.swift // MQDouYuTV // // Created by mengmeng on 16/12/22. // Copyright © 2016年 mengQuietly. All rights reserved. // 推荐界面 ViewModel import UIKit class MQRecommentViewModel : MQBaseAnchorViewModel{ // MARK:- 懒加载 /// banners List lazy var bannerLists:[MQBannerModel] = [MQBannerModel]() // 热门组 fileprivate lazy var hotGroup:MQAnchorGroupModel = MQAnchorGroupModel() // 颜值组 fileprivate lazy var perttyGroup:MQAnchorGroupModel = MQAnchorGroupModel() } // MARK:- 网络请求 extension MQRecommentViewModel{ // MARK: 获取banner 数据 func getBannerListData(_ finishCallBack:@escaping ()->()) { let bannerUrl = HOST_URL.appending(RECOMMEND_GET_BANNER_LIST) let bannerDict = ["version":"2.421"] MQNetworkingTool.sendRequest(url:bannerUrl, parameters: bannerDict, succeed: { [unowned self] (responseObject, isBadNet) in // MQLog("responseObject=\(responseObject),isBadNet=\(isBadNet)") guard let resultDict = responseObject as? [String:NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String:NSObject]] else {return} for dict in dataArray { let bannerModel = MQBannerModel(dict: dict) self.bannerLists.append(bannerModel) } finishCallBack() }) { (error, isBadNet) in MQLog("error=\(error),isBadNet=\(isBadNet)") } let time = Date.getCurrentDateNumber() let firUrl = "http://capi.douyucdn.cn/lapi/sign/appapi/getinfo" let firDict = ["aid":"ios","time":"\(time)","token":"58329051_11_c896fb45d9451c3b_2_75461464","auth":"086ed96a32bcb3a4868e19d3e286421d","posid":"800002,800003,800015","roomid":"0"] MQNetworkingTool.sendRequest(type: MQMethodType.post, url:firUrl, parameters: firDict,succeed: { (responseObject, isBadNet) in // MQLog("responseObject=\(responseObject),isBadNet=\(isBadNet)") /* adid = 1000002435; adtype = 0; ec = "<null>"; level = 0; link = "http://act.jl.ztgame.com/landing/index.html?zttag=douyujiaodiantu"; posid = 800002; proid = 1000000884; proname = "\U8857\U7bee"; showtime = 5; srcid = "http://staticlive.douyucdn.cn/upload/signs/201612291838263960.jpg"; */ }) { (error, isBadNet) in MQLog("error=\(error),isBadNet=\(isBadNet)") } } // MARK: 获取热门组数据 (1-热门,2-颜值,3-剩余其它2-12组热门) func getRoomGroupListData(_ finishCallBack:@escaping ()->()) { // 创建group let netGroup = DispatchGroup() //dispatch_group_create() // 将当前网络操作添加到组中 netGroup.enter() //dispatch_group_enter(netGroup) // MARK:获取最热排行数据 let hotUrl = HOST_URL.appending(RECOMMEND_POST_HOTTEST_ROMM_LIST) MQNetworkingTool.sendRequest(type: MQMethodType.post, url:hotUrl, succeed: { [unowned self] (responseObject, isBadNet) in // MQLog("responseObject=\(responseObject),isBadNet=\(isBadNet)") guard let resultDict = responseObject as? [String:NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String:NSObject]] else {return} // 创建颜值组 self.hotGroup.tag_name = "热门" self.hotGroup.icon_name = "home_header_hot" for dict in dataArray{ let anchor = MQAnchorModel(dict: dict) self.hotGroup.anchorList.append(anchor) } // 离开组 netGroup.leave() //dispatch_group_leave(netGroup) }) { (error, isBadNet) in MQLog("error=\(error),isBadNet=\(isBadNet)") } // 将当前网络操作添加到组中 netGroup.enter() // MARK:获取颜值排行数据 let perttyUrl = HOST_URL.appending(RECOMMEND_GET_PERTTY_ROMM_LIST) let perttyDict = ["limit":"4","offset":"0"] MQNetworkingTool.sendRequest(url:perttyUrl, parameters: perttyDict, succeed: { [unowned self] (responseObject, isBadNet) in // MQLog("responseObject=\(responseObject),isBadNet=\(isBadNet)") guard let resultDict = responseObject as? [String:NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String:NSObject]] else {return} self.perttyGroup.tag_name = "颜值" self.perttyGroup.icon_name = "home_header_pretty" for dict in dataArray{ let anchor = MQAnchorModel(dict: dict) self.perttyGroup.anchorList.append(anchor) } // 离开组 netGroup.leave() }) { (error, isBadNet) in MQLog("error=\(error),isBadNet=\(isBadNet)") } // 将当前网络操作添加到组中 netGroup.enter() // MARK:获取2-12其它热门排行数据 let otherHotUrl = HOST_URL.appending(RECOMMEND_POST_HOT_ROMM_LIST) let time = Date.getCurrentDateNumber() let otherHotDict = ["aid":"ios","time":"\(time)","auth":"ddc8cda0a77453f40bf3b26926a15aba"] getAnchorData(urlString: otherHotUrl, parameters: otherHotDict) { // 离开组 netGroup.leave() } // 网络组完成后,执行 // dispatch_group_notify(netGroup, dispatch_get_main_queue()) { () -> Void in} netGroup.notify(queue: DispatchQueue.main) { [unowned self] in // 插入热门、颜值到group self.anchorGroupList.insert(self.perttyGroup, at: 0) self.anchorGroupList.insert(self.hotGroup, at: 0) finishCallBack() } } }
mit
5f283daa88b2f98d6b468063fb374ac9
37.794702
188
0.573745
4.187277
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/ReaderDetailViewController.swift
1
41318
import Foundation import CocoaLumberjack import WordPressShared import QuartzCore open class ReaderDetailViewController: UIViewController, UIViewControllerRestoration { static let restorablePostObjectURLhKey: String = "RestorablePostObjectURLKey" // Structs for Constants fileprivate struct DetailConstants { static let LikeCountKeyPath = "likeCount" static let MarginOffset = CGFloat(8.0) } fileprivate struct DetailAnalyticsConstants { static let TypeKey = "post_detail_type" static let TypeNormal = "normal" static let TypePreviewSite = "preview_site" static let OfflineKey = "offline_view" static let PixelStatReferrer = "https://wordpress.com/" } // MARK: - Properties & Accessors // Footer views @IBOutlet fileprivate weak var footerView: UIView! @IBOutlet fileprivate weak var tagButton: UIButton! @IBOutlet fileprivate weak var commentButton: UIButton! @IBOutlet fileprivate weak var likeButton: UIButton! @IBOutlet fileprivate weak var footerViewHeightConstraint: NSLayoutConstraint! // Wrapper views @IBOutlet fileprivate weak var textHeaderStackView: UIStackView! @IBOutlet fileprivate weak var textFooterStackView: UIStackView! fileprivate weak var textFooterTopConstraint: NSLayoutConstraint! // Header realated Views @IBOutlet fileprivate weak var headerView: UIView! @IBOutlet fileprivate weak var blavatarImageView: UIImageView! @IBOutlet fileprivate weak var blogNameButton: UIButton! @IBOutlet fileprivate weak var blogURLLabel: UILabel! @IBOutlet fileprivate weak var menuButton: UIButton! // Content views @IBOutlet fileprivate weak var featuredImageView: UIImageView! @IBOutlet fileprivate weak var titleLabel: UILabel! @IBOutlet fileprivate weak var bylineView: UIView! @IBOutlet fileprivate weak var avatarImageView: CircularImageView! @IBOutlet fileprivate weak var bylineLabel: UILabel! @IBOutlet fileprivate weak var textView: WPRichContentView! @IBOutlet fileprivate weak var attributionView: ReaderCardDiscoverAttributionView! // Spacers @IBOutlet fileprivate weak var featuredImageBottomPaddingView: UIView! @IBOutlet fileprivate weak var titleBottomPaddingView: UIView! @IBOutlet fileprivate weak var bylineBottomPaddingView: UIView! open var shouldHideComments = false fileprivate var didBumpStats = false fileprivate var didBumpPageViews = false fileprivate var footerViewHeightConstraintConstant = CGFloat(0.0) fileprivate let sharingController = PostSharingController() var currentPreferredStatusBarStyle = UIStatusBarStyle.lightContent { didSet { setNeedsStatusBarAppearanceUpdate() } } override open var preferredStatusBarStyle: UIStatusBarStyle { return currentPreferredStatusBarStyle } open var post: ReaderPost? { didSet { oldValue?.removeObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath) oldValue?.inUse = false if let newPost = post, let context = newPost.managedObjectContext { newPost.inUse = true ContextManager.sharedInstance().save(context) newPost.addObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath, options: .new, context: nil) } if isViewLoaded { configureView() } } } fileprivate var isLoaded: Bool { return post != nil } // MARK: - Convenience Factories /// Convenience method for instantiating an instance of ReaderDetailViewController /// for a particular topic. /// /// - Parameters: /// - topic: The reader topic for the list. /// /// - Return: A ReaderListViewController instance. /// open class func controllerWithPost(_ post: ReaderPost) -> ReaderDetailViewController { let storyboard = UIStoryboard(name: "Reader", bundle: Bundle.main) let controller = storyboard.instantiateViewController(withIdentifier: "ReaderDetailViewController") as! ReaderDetailViewController controller.post = post return controller } open class func controllerWithPostID(_ postID: NSNumber, siteID: NSNumber) -> ReaderDetailViewController { let storyboard = UIStoryboard(name: "Reader", bundle: Bundle.main) let controller = storyboard.instantiateViewController(withIdentifier: "ReaderDetailViewController") as! ReaderDetailViewController controller.setupWithPostID(postID, siteID: siteID) return controller } // MARK: - State Restoration open static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? { guard let path = coder.decodeObject(forKey: restorablePostObjectURLhKey) as? String else { return nil } let context = ContextManager.sharedInstance().mainContext guard let url = URL(string: path), let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: url) else { return nil } guard let post = (try? context.existingObject(with: objectID)) as? ReaderPost else { return nil } return controllerWithPost(post) } open override func encodeRestorableState(with coder: NSCoder) { if let post = post { coder.encode(post.objectID.uriRepresentation().absoluteString, forKey: type(of: self).restorablePostObjectURLhKey) } super.encodeRestorableState(with: coder) } // MARK: - LifeCycle Methods deinit { if let post = post, let context = post.managedObjectContext { post.inUse = false ContextManager.sharedInstance().save(context) post.removeObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath) } NotificationCenter.default.removeObserver(self) } open override func awakeAfter(using aDecoder: NSCoder) -> Any? { restorationClass = type(of: self) return super.awakeAfter(using: aDecoder) } open override func viewDidLoad() { super.viewDidLoad() setupContentHeaderAndFooter() textView.alpha = 0 footerView.isHidden = true // Hide the featured image and its padding until we know there is one to load. featuredImageView.isHidden = true featuredImageBottomPaddingView.isHidden = true // Styles applyStyles() setupNavBar() if let _ = post { configureView() } } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // The UIApplicationDidBecomeActiveNotification notification is broadcast // when the app is resumed as a part of split screen multitasking on the iPad. NotificationCenter.default.addObserver(self, selector: #selector(ReaderDetailViewController.handleApplicationDidBecomeActive(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) bumpStats() bumpPageViewsForPost() } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) setBarsHidden(false, animated: animated) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // This is something we do to help with the resizing that can occur with // split screen multitasking on the iPad. view.layoutIfNeeded() } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let y = textView.contentOffset.y let position = textView.closestPosition(to: CGPoint(x: 0.0, y: y)) coordinator.animate( alongsideTransition: { (_) in if let position = position, let textRange = self.textView.textRange(from: position, to: position) { let rect = self.textView.firstRect(for: textRange) self.textView.setContentOffset(CGPoint(x: 0.0, y: rect.origin.y), animated: false) } }, completion: { (_) in self.updateContentInsets() self.updateTextViewMargins() }) // Make sure that the bars are visible after switching from landscape // to portrait orientation. The content might have been scrollable in landscape // orientation, but it might not be in portrait orientation. We'll assume the bars // should be visible for safety sake and for performance since WPRichTextView updates // its intrinsicContentSize too late for get an accurate scrollWiew.contentSize // in the completion handler below. if size.height > size.width { self.setBarsHidden(false) } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if (object! as! NSObject == post!) && (keyPath! == DetailConstants.LikeCountKeyPath) { // Note: The intent here is to update the action buttons, specifically the // like button, *after* both likeCount and isLiked has changed. The order // of the properties is important. configureLikeActionButton(true) } } // MARK: - Multitasking Splitview Support func handleApplicationDidBecomeActive(_ notification: Foundation.Notification) { view.layoutIfNeeded() } // MARK: - Setup open func setupWithPostID(_ postID: NSNumber, siteID: NSNumber) { let title = NSLocalizedString("Loading Post...", comment: "Text displayed while loading a post.") WPNoResultsView.displayAnimatedBox(withTitle: title, message: nil, view: view) textView.alpha = 0.0 let context = ContextManager.sharedInstance().mainContext let service = ReaderPostService(managedObjectContext: context) service.fetchPost( postID.uintValue, forSite: siteID.uintValue, success: {[weak self] (post: ReaderPost?) in WPNoResultsView.remove(from: self?.view) self?.textView.alpha = 1.0 self?.post = post }, failure: {[weak self] (error: Error?) in DDLogError("Error fetching post for detail: \(String(describing: error?.localizedDescription))") let title = NSLocalizedString("Error Loading Post", comment: "Text displayed when load post fails.") WPNoResultsView.displayAnimatedBox(withTitle: title, message: nil, view: self?.view) } ) } /// Composes the views for the post header and Discover attribution. fileprivate func setupContentHeaderAndFooter() { // Add the footer first so its behind the header. This way the header // obscures the footer until its properly positioned. textView.addSubview(textFooterStackView) textView.addSubview(textHeaderStackView) textHeaderStackView.topAnchor.constraint(equalTo: textView.topAnchor).isActive = true textFooterTopConstraint = NSLayoutConstraint(item: textFooterStackView, attribute: .top, relatedBy: .equal, toItem: textView, attribute: .top, multiplier: 1.0, constant: 0.0) textView.addConstraint(textFooterTopConstraint) textFooterTopConstraint.constant = textFooterYOffset() textView.setContentOffset(CGPoint.zero, animated: false) } /// Sets the left and right textContainerInset to preserve readable content margins. fileprivate func updateContentInsets() { var insets = textView.textContainerInset let margin = view.readableContentGuide.layoutFrame.origin.x insets.left = margin - DetailConstants.MarginOffset insets.right = margin - DetailConstants.MarginOffset textView.textContainerInset = insets textView.layoutIfNeeded() } /// Returns the y position for the textfooter. Assign to the textFooter's top /// constraint constant to correctly position the view. fileprivate func textFooterYOffset() -> CGFloat { let length = textView.textStorage.length if length == 0 { return textView.contentSize.height - textFooterStackView.frame.height } let range = NSRange(location: length - 1, length: 0) let frame = textView.frameForTextInRange(range) if frame.minY == CGFloat.infinity { // A value of infinity can occur when a device is rotated 180 degrees. // It will sort it self out as the rotation aniation progresses, // so just return the existing constant. return textFooterTopConstraint.constant } return frame.minY } /// Updates the bounds of the placeholder top and bottom text attachments so /// there is enough vertical space for the text header and footer views. fileprivate func updateTextViewMargins() { textView.topMargin = textHeaderStackView.frame.height textView.bottomMargin = textFooterStackView.frame.height textFooterTopConstraint.constant = textFooterYOffset() } fileprivate func setupNavBar() { configureNavTitle() // Don't show 'Reader' in the next-view back button navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) } // MARK: - Configuration /** Applies the default styles to the cell's subviews */ fileprivate func applyStyles() { WPStyleGuide.applyReaderCardSiteButtonStyle(blogNameButton) WPStyleGuide.applyReaderCardBylineLabelStyle(bylineLabel) WPStyleGuide.applyReaderCardBylineLabelStyle(blogURLLabel) WPStyleGuide.applyReaderCardTitleLabelStyle(titleLabel) WPStyleGuide.applyReaderCardTagButtonStyle(tagButton) WPStyleGuide.applyReaderCardActionButtonStyle(commentButton) WPStyleGuide.applyReaderCardActionButtonStyle(likeButton) } fileprivate func configureView() { textView.alpha = 1 configureNavTitle() configureShareButton() configureHeader() configureFeaturedImage() configureTitle() configureByLine() configureRichText() configureDiscoverAttribution() configureTag() configureActionButtons() configureFooterIfNeeded() adjustInsetsForTextDirection() bumpStats() bumpPageViewsForPost() NotificationCenter.default.addObserver(self, selector: #selector(ReaderDetailViewController.handleBlockSiteNotification(_:)), name: NSNotification.Name(rawValue: ReaderPostMenu.BlockSiteNotification), object: nil) view.layoutIfNeeded() textView.setContentOffset(CGPoint.zero, animated: false) } fileprivate func configureNavTitle() { let placeholder = NSLocalizedString("Post", comment: "Placeholder title for ReaderPostDetails.") self.title = post?.postTitle ?? placeholder } fileprivate func configureShareButton() { // Share button. let image = UIImage(named: "icon-posts-share")!.withRenderingMode(UIImageRenderingMode.alwaysTemplate) let button = CustomHighlightButton(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) button.setImage(image, for: UIControlState()) button.addTarget(self, action: #selector(ReaderDetailViewController.didTapShareButton(_:)), for: .touchUpInside) let shareButton = UIBarButtonItem(customView: button) shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Spoken accessibility label") WPStyleGuide.setRightBarButtonItemWithCorrectSpacing(shareButton, for: navigationItem) } fileprivate func configureHeader() { // Blavatar let placeholder = UIImage(named: "post-blavatar-placeholder") blavatarImageView.image = placeholder let size = blavatarImageView.frame.size.width * UIScreen.main.scale if let url = post?.siteIconForDisplay(ofSize: Int(size)) { blavatarImageView.setImageWith(url, placeholderImage: placeholder) } // Site name let blogName = post?.blogNameForDisplay() blogNameButton.setTitle(blogName, for: UIControlState()) blogNameButton.setTitle(blogName, for: .highlighted) blogNameButton.setTitle(blogName, for: .disabled) // Enable button only if not previewing a site. if let topic = post!.topic { blogNameButton.isEnabled = !ReaderHelpers.isTopicSite(topic) } // If the button is enabled also listen for taps on the avatar. if blogNameButton.isEnabled { let tgr = UITapGestureRecognizer(target: self, action: #selector(ReaderDetailViewController.didTapHeaderAvatar(_:))) blavatarImageView.addGestureRecognizer(tgr) } if let siteURL: NSString = post!.siteURLForDisplay() as NSString? { blogURLLabel.text = siteURL.components(separatedBy: "//").last } } fileprivate func configureFeaturedImage() { var url = post!.featuredImageURLForDisplay() guard url != nil else { return } // Do not display the featured image if it exists in the content. if post!.contentIncludesFeaturedImage() { return } var request: URLRequest if !(post!.isPrivate()) { let size = CGSize(width: featuredImageView.frame.width, height: 0) url = PhotonImageURLHelper.photonURL(with: size, forImageURL: url) request = URLRequest(url: url!) } else if (url?.host != nil) && (url?.host!.hasSuffix("wordpress.com"))! { // private wpcom image needs special handling. request = requestForURL(url!) } else { // private but not a wpcom hosted image request = URLRequest(url: url!) } // Define a success block to make the image visible and update its aspect ratio constraint let successBlock: ((URLRequest, HTTPURLResponse?, UIImage) -> Void) = { [weak self] (request: URLRequest, response: HTTPURLResponse?, image: UIImage) in guard self != nil else { return } self!.configureFeaturedImageWithImage(image) } featuredImageView.setImageWith(request, placeholderImage: nil, success: successBlock, failure: nil) } open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updateContentInsets() updateTextViewMargins() } fileprivate func configureFeaturedImageWithImage(_ image: UIImage) { // Unhide the views featuredImageView.isHidden = false featuredImageBottomPaddingView.isHidden = false // Now that we have the image, create an aspect ratio constraint for // the featuredImageView let ratio = image.size.height / image.size.width let constraint = NSLayoutConstraint(item: featuredImageView, attribute: .height, relatedBy: .equal, toItem: featuredImageView, attribute: .width, multiplier: ratio, constant: 0) constraint.priority = UILayoutPriorityDefaultHigh featuredImageView.addConstraint(constraint) featuredImageView.setNeedsUpdateConstraints() featuredImageView.image = image // Listen for taps so we can display the image detail let tgr = UITapGestureRecognizer(target: self, action: #selector(ReaderDetailViewController.didTapFeaturedImage(_:))) featuredImageView.addGestureRecognizer(tgr) view.layoutIfNeeded() updateTextViewMargins() } fileprivate func requestForURL(_ url: URL) -> URLRequest { var requestURL = url let absoluteString = requestURL.absoluteString if !absoluteString.hasPrefix("https") { let sslURL = absoluteString.replacingOccurrences(of: "http", with: "https") requestURL = URL(string: sslURL)! } let request = NSMutableURLRequest(url: requestURL) let acctServ = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext) if let account = acctServ.defaultWordPressComAccount() { let token = account.authToken let headerValue = String(format: "Bearer %@", token!) request.addValue(headerValue, forHTTPHeaderField: "Authorization") } return request as URLRequest } fileprivate func configureTitle() { if let title = post?.titleForDisplay() { titleLabel.attributedText = NSAttributedString(string: title, attributes: WPStyleGuide.readerDetailTitleAttributes()) titleLabel.isHidden = false } else { titleLabel.attributedText = nil titleLabel.isHidden = true } } fileprivate func configureByLine() { // Avatar let placeholder = UIImage(named: "gravatar") if let avatarURLString = post?.authorAvatarURL, let url = URL(string: avatarURLString) { avatarImageView.setImageWith(url, placeholderImage: placeholder) } // Byline let author = post?.authorForDisplay() let dateAsString = post?.dateForDisplay()?.mediumString() let byline: String if let author = author, let date = dateAsString { byline = author + " · " + date } else { byline = author ?? dateAsString ?? String() } bylineLabel.text = byline } fileprivate func configureRichText() { guard let post = post else { return } textView.isPrivate = post.isPrivate() textView.content = post.contentForDisplay() updateTextViewMargins() } fileprivate func configureDiscoverAttribution() { if post?.sourceAttributionStyle() == SourceAttributionStyle.none { attributionView.isHidden = true } else { attributionView.configureViewWithVerboseSiteAttribution(post!) attributionView.delegate = self } } fileprivate func configureTag() { var tag = "" if let rawTag = post?.primaryTag { if rawTag.count > 0 { tag = "#\(rawTag)" } } tagButton.isHidden = tag.count == 0 tagButton.setTitle(tag, for: UIControlState()) tagButton.setTitle(tag, for: .highlighted) } fileprivate func configureActionButtons() { resetActionButton(likeButton) resetActionButton(commentButton) guard let post = post else { assertionFailure() return } // Show likes if logged in, or if likes exist, but not if external if (ReaderHelpers.isLoggedIn() || post.likeCount.intValue > 0) && !post.isExternal { configureLikeActionButton() } // Show comments if logged in and comments are enabled, or if comments exist. // But only if it is from wpcom (jetpack and external is not yet supported). // Nesting this conditional cos it seems clearer that way if post.isWPCom && !shouldHideComments { let commentCount = post.commentCount?.intValue ?? 0 if (ReaderHelpers.isLoggedIn() && post.commentsOpen) || commentCount > 0 { configureCommentActionButton() } } } fileprivate func resetActionButton(_ button: UIButton) { button.setTitle(nil, for: UIControlState()) button.setTitle(nil, for: .highlighted) button.setTitle(nil, for: .disabled) button.setImage(nil, for: UIControlState()) button.setImage(nil, for: .highlighted) button.setImage(nil, for: .disabled) button.isSelected = false button.isHidden = true button.isEnabled = true } fileprivate func configureActionButton(_ button: UIButton, title: String?, image: UIImage?, highlightedImage: UIImage?, selected: Bool) { button.setTitle(title, for: UIControlState()) button.setTitle(title, for: .highlighted) button.setTitle(title, for: .disabled) button.setImage(image, for: UIControlState()) button.setImage(highlightedImage, for: .highlighted) button.setImage(image, for: .disabled) button.isSelected = selected button.isHidden = false } fileprivate func configureLikeActionButton(_ animated: Bool = false) { likeButton.isEnabled = ReaderHelpers.isLoggedIn() let title = post!.likeCountForDisplay() let imageName = post!.isLiked ? "icon-reader-liked" : "icon-reader-like" let image = UIImage(named: imageName) let highlightImage = UIImage(named: "icon-reader-like-highlight") let selected = post!.isLiked configureActionButton(likeButton, title: title, image: image, highlightedImage: highlightImage, selected: selected) if animated { playLikeButtonAnimation() } } fileprivate func playLikeButtonAnimation() { let likeImageView = likeButton.imageView! let frame = likeButton.convert(likeImageView.frame, from: likeImageView) let imageView = UIImageView(image: UIImage(named: "icon-reader-liked")) imageView.frame = frame likeButton.addSubview(imageView) let animationDuration = 0.3 if likeButton.isSelected { // Prep a mask to hide the likeButton's image, since changes to visiblility and alpha are ignored let mask = UIView(frame: frame) mask.backgroundColor = view.backgroundColor likeButton.addSubview(mask) likeButton.bringSubview(toFront: imageView) // Configure starting state imageView.alpha = 0.0 let angle = (-270.0 * CGFloat.pi) / 180.0 let rotate = CGAffineTransform(rotationAngle: angle) let scale = CGAffineTransform(scaleX: 3.0, y: 3.0) imageView.transform = rotate.concatenating(scale) // Perform the animations UIView.animate(withDuration: animationDuration, animations: { () in let angle = (1.0 * CGFloat.pi) / 180.0 let rotate = CGAffineTransform(rotationAngle: angle) let scale = CGAffineTransform(scaleX: 0.75, y: 0.75) imageView.transform = rotate.concatenating(scale) imageView.alpha = 1.0 imageView.center = likeImageView.center // In case the button's imageView shifted position }, completion: { (_) in UIView.animate(withDuration: animationDuration, animations: { () in imageView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }, completion: { (_) in mask.removeFromSuperview() imageView.removeFromSuperview() }) }) } else { UIView .animate(withDuration: animationDuration, animations: { () -> Void in let angle = (120.0 * CGFloat.pi) / 180.0 let rotate = CGAffineTransform(rotationAngle: angle) let scale = CGAffineTransform(scaleX: 3.0, y: 3.0) imageView.transform = rotate.concatenating(scale) imageView.alpha = 0 }, completion: { (_) in imageView.removeFromSuperview() }) } } fileprivate func configureCommentActionButton() { let title = post!.commentCount.stringValue let image = UIImage(named: "icon-reader-comment") let highlightImage = UIImage(named: "icon-reader-comment-highlight") configureActionButton(commentButton, title: title, image: image, highlightedImage: highlightImage, selected: false) } fileprivate func configureFooterIfNeeded() { self.footerView.isHidden = tagButton.isHidden && likeButton.isHidden && commentButton.isHidden if self.footerView.isHidden { footerViewHeightConstraint.constant = 0 } footerViewHeightConstraintConstant = footerViewHeightConstraint.constant } fileprivate func adjustInsetsForTextDirection() { let buttonsToAdjust: [UIButton] = [ likeButton, commentButton] for button in buttonsToAdjust { button.flipInsetsForRightToLeftLayoutDirection() } } // MARK: - Instance Methods func presentWebViewControllerWithURL(_ url: URL) { var url = url if url.host == nil { if let postURLString = post?.permaLink { let postURL = URL(string: postURLString) url = URL(string: url.absoluteString, relativeTo: postURL)! } } let configuration = WebViewControllerConfiguration(url: url) configuration.authenticateWithDefaultAccount() configuration.addsWPComReferrer = true let controller = WebViewControllerFactory.controller(configuration: configuration) let navController = UINavigationController(rootViewController: controller) present(navController, animated: true, completion: nil) } func previewSite() { let controller = ReaderStreamViewController.controllerWithSiteID(post!.siteID, isFeed: post!.isExternal) navigationController?.pushViewController(controller, animated: true) let properties = ReaderHelpers.statsPropertiesForPost(post!, andValue: post!.blogURL as AnyObject?, forKey: "URL") WPAppAnalytics.track(.readerSitePreviewed, withProperties: properties) } func setBarsHidden(_ hidden: Bool, animated: Bool = true) { if navigationController?.isNavigationBarHidden == hidden { return } if hidden { // Hides the navbar and footer view navigationController?.setNavigationBarHidden(true, animated: animated) currentPreferredStatusBarStyle = .default footerViewHeightConstraint.constant = 0.0 UIView.animate(withDuration: animated ? 0.2 : 0, delay: 0.0, options: [.beginFromCurrentState, .allowUserInteraction], animations: { self.view.layoutIfNeeded() }, completion: nil) } else { // Shows the navbar and footer view let pinToBottom = isScrollViewAtBottom() currentPreferredStatusBarStyle = .lightContent footerViewHeightConstraint.constant = footerViewHeightConstraintConstant UIView.animate(withDuration: animated ? 0.2 : 0, delay: 0.0, options: [.beginFromCurrentState, .allowUserInteraction], animations: { self.view.layoutIfNeeded() self.navigationController?.setNavigationBarHidden(false, animated: animated) if pinToBottom { let y = self.textView.contentSize.height - self.textView.frame.height self.textView.setContentOffset(CGPoint(x: 0, y: y), animated: false) } }, completion: nil) } } func isScrollViewAtBottom() -> Bool { return textView.contentOffset.y + textView.frame.height == textView.contentSize.height } // MARK: - Analytics fileprivate func bumpStats() { if didBumpStats { return } guard let readerPost = post, isViewLoaded && view.window != nil else { return } didBumpStats = true let isOfflineView = ReachabilityUtils.isInternetReachable() ? "no" : "yes" let detailType = readerPost.topic?.type == ReaderSiteTopic.TopicType ? DetailAnalyticsConstants.TypePreviewSite : DetailAnalyticsConstants.TypeNormal var properties = ReaderHelpers.statsPropertiesForPost(readerPost, andValue: nil, forKey: nil) properties[DetailAnalyticsConstants.TypeKey] = detailType properties[DetailAnalyticsConstants.OfflineKey] = isOfflineView WPAppAnalytics.track(.readerArticleOpened, withProperties: properties) // We can remove the nil check and use `if let` when `ReaderPost` adopts nullibility. let railcar = readerPost.railcarDictionary() if railcar != nil { WPAppAnalytics.trackTrainTracksInteraction(.readerArticleOpened, withProperties: railcar) } } fileprivate func bumpPageViewsForPost() { if didBumpPageViews { return } guard let readerPost = post, isViewLoaded && view.window != nil else { return } didBumpPageViews = true ReaderHelpers.bumpPageViewForPost(readerPost) } // MARK: - Actions @IBAction func didTapTagButton(_ sender: UIButton) { if !isLoaded { return } let controller = ReaderStreamViewController.controllerWithTagSlug(post!.primaryTagSlug) navigationController?.pushViewController(controller, animated: true) let properties = ReaderHelpers.statsPropertiesForPost(post!, andValue: post!.primaryTagSlug as AnyObject?, forKey: "tag") WPAppAnalytics.track(.readerTagPreviewed, withProperties: properties) } @IBAction func didTapCommentButton(_ sender: UIButton) { if !isLoaded { return } let controller = ReaderCommentsViewController(post: post) navigationController?.pushViewController(controller!, animated: true) } @IBAction func didTapLikeButton(_ sender: UIButton) { if !isLoaded { return } guard let post = post else { return } if !post.isLiked { UINotificationFeedbackGenerator().notificationOccurred(.success) } let service = ReaderPostService(managedObjectContext: post.managedObjectContext!) service.toggleLiked(for: post, success: nil, failure: { (error: Error?) in if let anError = error { DDLogError("Error (un)liking post: \(anError.localizedDescription)") } }) } func didTapHeaderAvatar(_ gesture: UITapGestureRecognizer) { if gesture.state != .ended { return } previewSite() } @IBAction func didTapBlogNameButton(_ sender: UIButton) { previewSite() } @IBAction func didTapMenuButton(_ sender: UIButton) { ReaderPostMenu.showMenuForPost(post!, fromView: menuButton, inViewController: self) } func didTapFeaturedImage(_ gesture: UITapGestureRecognizer) { if gesture.state != .ended { return } let controller = WPImageViewController(image: featuredImageView.image) controller?.modalTransitionStyle = .crossDissolve controller?.modalPresentationStyle = .fullScreen present(controller!, animated: true, completion: nil) } func didTapDiscoverAttribution() { if post?.sourceAttribution == nil { return } if let blogID = post?.sourceAttribution.blogID { let controller = ReaderStreamViewController.controllerWithSiteID(blogID, isFeed: false) navigationController?.pushViewController(controller, animated: true) return } var path: String? if post?.sourceAttribution.attributionType == SourcePostAttributionTypePost { path = post?.sourceAttribution.permalink } else { path = post?.sourceAttribution.blogURL } if let linkURL = URL(string: path!) { presentWebViewControllerWithURL(linkURL) } } func didTapShareButton(_ sender: UIButton) { sharingController.shareReaderPost(post!, fromView: sender, inViewController: self) } func handleBlockSiteNotification(_ notification: Foundation.Notification) { if let userInfo = notification.userInfo, let aPost = userInfo["post"] as? NSObject { if aPost == post! { _ = navigationController?.popViewController(animated: true) } } } } // MARK: - ReaderCardDiscoverAttributionView Delegate Methods extension ReaderDetailViewController: ReaderCardDiscoverAttributionViewDelegate { public func attributionActionSelectedForVisitingSite(_ view: ReaderCardDiscoverAttributionView) { didTapDiscoverAttribution() } } // MARK: - UITextView/WPRichContentView Delegate Methods extension ReaderDetailViewController: WPRichContentViewDelegate { public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { presentWebViewControllerWithURL(URL) return false } @available(iOS 10, *) public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { if interaction == .presentActions { // show let frame = textView.frameForTextInRange(characterRange) let shareController = PostSharingController() shareController.shareURL(url: URL as NSURL, fromRect: frame, inView: textView, inViewController: self) } else { presentWebViewControllerWithURL(URL) } return false } func richContentView(_ richContentView: WPRichContentView, didReceiveImageAction image: WPRichTextImage) { var controller: WPImageViewController if WPImageViewController.isUrlSupported(image.linkURL as URL!) { controller = WPImageViewController(image: image.imageView.image, andURL: image.linkURL as URL!) } else if let linkURL = image.linkURL { presentWebViewControllerWithURL(linkURL as URL) return } else { controller = WPImageViewController(image: image.imageView.image) } controller.modalTransitionStyle = .crossDissolve controller.modalPresentationStyle = .fullScreen present(controller, animated: true, completion: nil) } } // MARK: - UIScrollView Delegate Methods extension ReaderDetailViewController: UIScrollViewDelegate { public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if UIDevice.isPad() || footerView.isHidden || !isLoaded { return } // The threshold for hiding the bars is twice the height of the hidden bars. // This ensures that once the bars are hidden the view can still be scrolled // and thus can unhide the bars. var threshold = footerViewHeightConstraintConstant if let navHeight = navigationController?.navigationBar.frame.height { threshold += navHeight } threshold *= 2.0 let y = targetContentOffset.pointee.y if y > scrollView.contentOffset.y && y > threshold { setBarsHidden(true) } else { // Velocity will be 0,0 if the user taps to stop an in progress scroll. // If the bars are already visible its fine but if the bars are hidden // we don't want to jar the user by having them reappear. if !velocity.equalTo(CGPoint.zero) { setBarsHidden(false) } } } public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) { setBarsHidden(false) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if isScrollViewAtBottom() { setBarsHidden(false) } } } // Expand this view controller to full screen if possible extension ReaderDetailViewController: PrefersFullscreenDisplay {} // Let's the split view know this vc changes the status bar style. extension ReaderDetailViewController: DefinesVariableStatusBarStyle {}
gpl-2.0
aba43dd2d31190b56ca67b47395564a2
35.531388
207
0.647482
5.602305
false
false
false
false
Maaimusic/BTree
Tests/BTreeTests/BTreeCursorTests.swift
3
22397
// // BTreeCursorTests.swift // BTree // // Created by Károly Lőrentey on 2016-02-19. // Copyright © 2015–2017 Károly Lőrentey. // import Foundation import XCTest @testable import BTree class BTreeCursorTests: XCTestCase { typealias Tree = BTree<Int, String> func testCursorWithEmptyTree() { func checkEmpty(_ cursor: BTreeCursor<Int, String>) { XCTAssertTrue(cursor.isValid) XCTAssertTrue(cursor.isAtStart) XCTAssertTrue(cursor.isAtEnd) XCTAssertEqual(cursor.count, 0) let node = cursor.finish() assertEqualElements(node, []) } var tree = Tree() tree.withCursorAtStart(checkEmpty) tree.withCursorAtEnd(checkEmpty) tree.withCursor(atOffset: 0, body: checkEmpty) tree.withCursor(onKey: 42, choosing: .first, body: checkEmpty) tree.withCursor(onKey: 42, choosing: .last, body: checkEmpty) tree.withCursor(onKey: 42, choosing: .after, body: checkEmpty) tree.withCursor(onKey: 42, choosing: .any, body: checkEmpty) } func testCursorAtStart() { var tree = maximalTree(depth: 2, order: 5) tree.withCursorAtStart { cursor in XCTAssertTrue(cursor.isAtStart) XCTAssertFalse(cursor.isAtEnd) XCTAssertEqual(cursor.offset, 0) XCTAssertEqual(cursor.key, 0) XCTAssertEqual(cursor.value, "0") } } func testCursorAtEnd() { var tree = maximalTree(depth: 2, order: 5) let count = tree.count tree.withCursorAtEnd { cursor in XCTAssertFalse(cursor.isAtStart) XCTAssertTrue(cursor.isAtEnd) XCTAssertEqual(cursor.offset, count) } } func testCursorAtOffset() { var tree = maximalTree(depth: 3, order: 4) let c = tree.count for p in 0 ..< c { tree.withCursor(atOffset: p) { cursor in XCTAssertEqual(cursor.offset, p) XCTAssertEqual(cursor.key, p) XCTAssertEqual(cursor.value, String(p)) } } tree.withCursor(atOffset: c) { cursor in XCTAssertTrue(cursor.isAtEnd) } } func testCursorAtKeyFirst() { let count = 42 var tree = Tree(order: 3) for k in (0 ..< count).map({ 2 * $0 }) { tree.insert((k, String(k) + "/1")) tree.insert((k, String(k) + "/2")) tree.insert((k, String(k) + "/3")) } tree.assertValid() for i in 0 ..< count { tree.withCursor(onKey: 2 * i + 1, choosing: .first) { cursor in XCTAssertEqual(cursor.offset, 3 * (i + 1)) } tree.withCursor(onKey: 2 * i, choosing: .first) { cursor in XCTAssertEqual(cursor.offset, 3 * i) XCTAssertEqual(cursor.key, 2 * i) XCTAssertEqual(cursor.value, String(2 * i) + "/1") } } } func testCursorAtKeyLast() { let count = 42 var tree = Tree(order: 3) for k in (0 ..< count).map({ 2 * $0 }) { tree.insert((k, String(k) + "/1")) tree.insert((k, String(k) + "/2")) tree.insert((k, String(k) + "/3")) } tree.assertValid() for i in 0 ..< count { tree.withCursor(onKey: 2 * i + 1, choosing: .last) { cursor in XCTAssertEqual(cursor.offset, 3 * (i + 1)) } tree.withCursor(onKey: 2 * i, choosing: .last) { cursor in XCTAssertEqual(cursor.offset, 3 * i + 2) XCTAssertEqual(cursor.key, 2 * i) XCTAssertEqual(cursor.value, String(2 * i) + "/3") } } } func testCursorAtKeyAfter() { let count = 42 var tree = Tree(order: 3) for k in (0 ... count).map({ 2 * $0 }) { tree.insert((k, String(k) + "/1")) tree.insert((k, String(k) + "/2")) tree.insert((k, String(k) + "/3")) } tree.assertValid() for i in 0 ..< count { tree.withCursor(onKey: 2 * i + 1, choosing: .after) { cursor in XCTAssertEqual(cursor.offset, 3 * (i + 1)) } tree.withCursor(onKey: 2 * i, choosing: .after) { cursor in XCTAssertEqual(cursor.offset, 3 * (i + 1)) XCTAssertEqual(cursor.key, 2 * (i + 1)) XCTAssertEqual(cursor.value, String(2 * (i + 1)) + "/1") } } } func testCursorAtKeyAny() { let count = 42 var tree = Tree(order: 3) for k in (0 ..< count).map({ 2 * $0 }) { tree.insert((k, String(k) + "/1")) tree.insert((k, String(k) + "/2")) tree.insert((k, String(k) + "/3")) } tree.assertValid() for i in 0 ..< count { tree.withCursor(onKey: 2 * i + 1) { cursor in XCTAssertEqual(cursor.offset, 3 * (i + 1)) } tree.withCursor(onKey: 2 * i) { cursor in XCTAssertGreaterThanOrEqual(cursor.offset, 3 * i) XCTAssertLessThan(cursor.offset, 3 * (i + 1)) XCTAssertEqual(cursor.key, 2 * i) XCTAssertTrue(cursor.value.hasPrefix(String(2 * i) + "/"), cursor.value) } } } func testCursorAtIndex() { var tree = maximalTree(depth: 3, order: 3) let count = tree.count for i in 0 ... count { let index = tree.index(tree.startIndex, offsetBy: i) tree.withCursor(at: index) { cursor in XCTAssertEqual(cursor.offset, i) if i != count { XCTAssertEqual(cursor.key, i) } } } } func testMoveForward() { var tree = maximalTree(depth: 2, order: 5) let count = tree.count tree.withCursorAtStart { cursor in var i = 0 while !cursor.isAtEnd { XCTAssertEqual(cursor.offset, i) XCTAssertEqual(cursor.key, i) XCTAssertEqual(cursor.value, String(i)) XCTAssertEqual(cursor.element.0, i) XCTAssertEqual(cursor.element.1, String(i)) cursor.moveForward() i += 1 } XCTAssertEqual(i, count) } } func testMoveBackward() { var tree = maximalTree(depth: 2, order: 5) tree.withCursorAtEnd { cursor in var i = cursor.count while !cursor.isAtStart { XCTAssertEqual(cursor.offset, i) cursor.moveBackward() i -= 1 XCTAssertEqual(cursor.key, i) XCTAssertEqual(cursor.value, String(i)) } XCTAssertEqual(i, 0) } } func testMoveToEnd() { var tree = maximalTree(depth: 2, order: 5) let c = tree.count for i in 0 ... c { tree.withCursor(atOffset: i) { cursor in cursor.moveToEnd() XCTAssertTrue(cursor.isAtEnd) XCTAssertEqual(cursor.offset, c) } } } func testMoveToOffset() { var tree = maximalTree(depth: 2, order: 5) tree.withCursorAtStart { cursor in var i = 0 var j = cursor.count - 1 var toggle = false while i < j { if toggle { cursor.offset = i XCTAssertEqual(cursor.offset, i) XCTAssertEqual(cursor.key, i) i += 1 toggle = false } else { cursor.move(toOffset: j) XCTAssertEqual(cursor.offset, j) XCTAssertEqual(cursor.key, j) j -= 1 toggle = true } } cursor.move(toOffset: cursor.count) XCTAssertTrue(cursor.isAtEnd) cursor.moveBackward() XCTAssertEqual(cursor.key, cursor.count - 1) } } func testMoveToKey() { let count = 42 var tree = BTree((0..<count).map { (2 * $0, String(2 * $0)) }, order: 3) tree.withCursorAtStart() { cursor in var start = 0 var end = count - 1 while start < end { cursor.move(to: 2 * end) XCTAssertEqual(cursor.offset, end) XCTAssertEqual(cursor.key, 2 * end) cursor.move(to: 2 * start + 1) XCTAssertEqual(cursor.offset, start + 1) XCTAssertEqual(cursor.key, 2 * start + 2) start += 1 end -= 1 } start = 0 end = count - 1 while start < end { cursor.move(to: 2 * end - 1) XCTAssertEqual(cursor.offset, end) XCTAssertEqual(cursor.key, 2 * end) cursor.move(to: 2 * start) XCTAssertEqual(cursor.offset, start) XCTAssertEqual(cursor.key, 2 * start) start += 1 end -= 1 } } } func testReplacingElement() { var tree = maximalTree(depth: 2, order: 5) tree.withCursorAtStart { cursor in while !cursor.isAtEnd { let k = cursor.key cursor.element = (2 * k, String(2 * k)) cursor.moveForward() } let node = cursor.finish() node.assertValid() var i = 0 for (key, value) in node { XCTAssertEqual(key, 2 * i) XCTAssertEqual(value, String(2 * i)) i += 1 } } } func testReplacingKeyAndValue() { var tree = maximalTree(depth: 2, order: 5) tree.withCursorAtStart { cursor in while !cursor.isAtEnd { cursor.key = 2 * cursor.key cursor.value = String(cursor.key) cursor.moveForward() } let node = cursor.finish() node.assertValid() var i = 0 for (key, value) in node { XCTAssertEqual(key, 2 * i) XCTAssertEqual(value, String(2 * i)) i += 1 } } } func testSetValue() { var tree = maximalTree(depth: 2, order: 5) tree.withCursorAtStart { cursor in var i = 0 while !cursor.isAtEnd { XCTAssertEqual(cursor.setValue("Hello"), String(i)) cursor.moveForward() i += 1 } } tree.assertValid() for (_, value) in tree { XCTAssertEqual(value, "Hello") } } func testBuildingATreeUsingInsertBefore() { var tree = Tree(order: 3) tree.withCursorAtEnd { cursor in XCTAssertTrue(cursor.isAtEnd) for i in 0..<30 { cursor.insert((i, String(i))) XCTAssertTrue(cursor.isAtEnd) } } tree.assertValid() assertEqualElements(tree, (0..<30).map { ($0, String($0)) }) } func testBuildingATreeInTwoPassesUsingInsertBefore() { var tree = Tree(order: 5) let c = 30 tree.withCursorAtStart() { cursor in XCTAssertTrue(cursor.isAtEnd) for i in 0..<c { cursor.insert((2 * i + 1, String(2 * i + 1))) XCTAssertTrue(cursor.isAtEnd) } cursor.moveToStart() XCTAssertEqual(cursor.offset, 0) for i in 0..<c { XCTAssertEqual(cursor.key, 2 * i + 1) XCTAssertEqual(cursor.offset, 2 * i) XCTAssertEqual(cursor.count, c + i) cursor.insert((2 * i, String(2 * i))) XCTAssertEqual(cursor.key, 2 * i + 1) XCTAssertEqual(cursor.offset, 2 * i + 1) XCTAssertEqual(cursor.count, c + i + 1) cursor.moveForward() } } tree.assertValid() assertEqualElements(tree, (0 ..< 2 * c).map { ($0, String($0)) }) } func testBuildingATreeUsingInsertAfter() { var tree = Tree(order: 5) let c = 30 tree.withCursorAtStart() { cursor in cursor.insert((0, "0")) cursor.moveToStart() for i in 1 ..< c { cursor.insertAfter((i, String(i))) XCTAssertEqual(cursor.offset, i) XCTAssertEqual(cursor.key, i) } } tree.assertValid() assertEqualElements(tree, (0..<30).map { ($0, String($0)) }) } func testBuildingATreeInTwoPassesUsingInsertAfter() { var tree = Tree(order: 5) let c = 30 tree.withCursorAtStart() { cursor in XCTAssertTrue(cursor.isAtEnd) for i in 0..<c { cursor.insert((2 * i, String(2 * i))) } cursor.moveToStart() XCTAssertEqual(cursor.offset, 0) for i in 0..<c { XCTAssertEqual(cursor.key, 2 * i) XCTAssertEqual(cursor.offset, 2 * i) XCTAssertEqual(cursor.count, c + i) cursor.insertAfter((2 * i + 1, String(2 * i + 1))) XCTAssertEqual(cursor.key, 2 * i + 1) XCTAssertEqual(cursor.offset, 2 * i + 1) XCTAssertEqual(cursor.count, c + i + 1) cursor.moveForward() } } tree.assertValid() assertEqualElements(tree, (0 ..< 2 * c).map { ($0, String($0)) }) } func testBuildingATreeBackward() { var tree = Tree(order: 5) let c = 30 tree.withCursorAtStart() { cursor in XCTAssertTrue(cursor.isAtEnd) for i in stride(from: c - 1, through: 0, by: -1) { cursor.insert((i, String(i))) XCTAssertEqual(cursor.count, c - i) XCTAssertEqual(cursor.offset, 1) cursor.moveBackward() XCTAssertEqual(cursor.offset, 0) XCTAssertEqual(cursor.key, i) } } tree.assertValid() assertEqualElements(tree, (0 ..< c).map { ($0, String($0)) }) } func testInsertAtEveryOffset() { let c = 100 let reference = (0 ..< c).map { ($0, String($0)) } let tree = Tree(sortedElements: reference, order: 5) for i in 0 ... c { var test = tree test.withCursor(atOffset: i) { cursor in cursor.insert((i, "*\(i)")) } var expected = reference expected.insert((i, "*\(i)"), at: i) test.assertValid() assertEqualElements(test, expected) assertEqualElements(tree, reference) } } func testInsertSequence() { var tree = Tree(order: 3) tree.withCursorAtStart { cursor in cursor.insert((10 ..< 20).map { ($0, String($0)) }) XCTAssertEqual(cursor.count, 10) XCTAssertEqual(cursor.offset, 10) cursor.insert([]) XCTAssertEqual(cursor.count, 10) XCTAssertEqual(cursor.offset, 10) cursor.insert((20 ..< 30).map { ($0, String($0)) }) XCTAssertEqual(cursor.count, 20) XCTAssertEqual(cursor.offset, 20) cursor.move(toOffset: 0) cursor.insert((0 ..< 5).map { ($0, String($0)) }) XCTAssertEqual(cursor.count, 25) XCTAssertEqual(cursor.offset, 5) cursor.insert((5 ..< 9).map { ($0, String($0)) }) XCTAssertEqual(cursor.count, 29) XCTAssertEqual(cursor.offset, 9) cursor.insert([(9, "9")]) XCTAssertEqual(cursor.count, 30) XCTAssertEqual(cursor.offset, 10) } tree.assertValid() assertEqualElements(tree, (0 ..< 30).map { ($0, String($0)) }) } func testRemoveAllElementsInOrder() { var tree = maximalTree(depth: 2, order: 5) tree.withCursorAtStart { cursor in var i = 0 while cursor.count > 0 { let (key, value) = cursor.remove() XCTAssertEqual(key, i) XCTAssertEqual(value, String(i)) XCTAssertEqual(cursor.offset, 0) i += 1 } } tree.assertValid() assertEqualElements(tree, []) } func testRemoveEachElement() { let tree = maximalTree(depth: 2, order: 5) for i in 0..<tree.count { var copy = tree copy.withCursor(atOffset: i) { cursor in let removed = cursor.remove() XCTAssertEqual(removed.0, i) XCTAssertEqual(removed.1, String(i)) } copy.assertValid() assertEqualElements(copy, (0..<tree.count).filter{$0 != i}.map{ ($0, String($0)) }) } } func testRemoveRangeFromMaximalTree() { let tree = maximalTree(depth: 2, order: 3) let count = tree.count for i in 0 ..< count { for n in 0 ... count - i { var copy = tree copy.withCursor(atOffset: i) { cursor in cursor.remove(n) } copy.assertValid() let keys = Array(0..<i) + Array(i + n ..< count) assertEqualElements(copy, keys.map { ($0, String($0)) }) } } tree.assertValid() assertEqualElements(tree, (0..<count).map { ($0, String($0)) }) } func testExtractRangeFromMaximalTree() { let tree = maximalTree(depth: 2, order: 3) let count = tree.count for i in 0 ..< count { for n in 0 ... count - i { var copy = tree copy.withCursor(atOffset: i) { cursor in let extracted = cursor.extract(n) extracted.assertValid() assertEqualElements(extracted, (i ..< i + n).map { ($0, String($0)) }) } copy.assertValid() let keys = Array(0..<i) + Array(i + n ..< count) assertEqualElements(copy, keys.map { ($0, String($0)) }) } } tree.assertValid() assertEqualElements(tree, (0..<count).map { ($0, String($0)) }) } func testRemoveAll() { var tree = maximalTree(depth: 2, order: 3) tree.withCursorAtStart { cursor in cursor.removeAll() XCTAssertEqual(cursor.count, 0) XCTAssertTrue(cursor.isAtEnd) } XCTAssertTrue(tree.isEmpty) } func testRemoveAllBefore() { var t1 = maximalTree(depth: 2, order: 3) let c = t1.count t1.withCursorAtEnd { cursor in cursor.removeAllBefore(includingCurrent: false) } XCTAssertTrue(t1.isEmpty) var t2 = maximalTree(depth: 2, order: 3) t2.withCursor(atOffset: c - 1) { cursor in cursor.removeAllBefore(includingCurrent: true) } XCTAssertTrue(t2.isEmpty) var t3 = maximalTree(depth: 2, order: 3) t3.withCursor(atOffset: c - 1) { cursor in cursor.removeAllBefore(includingCurrent: false) } assertEqualElements(t3, [(c - 1, String(c - 1))]) var t4 = maximalTree(depth: 2, order: 3) t4.withCursor(atOffset: c - 10) { cursor in cursor.removeAllBefore(includingCurrent: true) } assertEqualElements(t4, (c - 9 ..< c).map { ($0, String($0)) }) var t5 = maximalTree(depth: 2, order: 3) t5.withCursor(atOffset: c - 10) { cursor in cursor.removeAllBefore(includingCurrent: false) } assertEqualElements(t5, (c - 10 ..< c).map { ($0, String($0)) }) var t6 = maximalTree(depth: 2, order: 3) t6.withCursorAtStart { cursor in cursor.removeAllBefore(includingCurrent: false) } assertEqualElements(t6, (0 ..< c).map { ($0, String($0)) }) var t7 = maximalTree(depth: 2, order: 3) t7.withCursorAtStart { cursor in cursor.removeAllBefore(includingCurrent: true) } assertEqualElements(t7, (1 ..< c).map { ($0, String($0)) }) } func testRemoveAllAfter() { var t1 = maximalTree(depth: 2, order: 3) t1.withCursorAtStart { cursor in cursor.removeAllAfter(includingCurrent: true) } XCTAssertTrue(t1.isEmpty) var t2 = maximalTree(depth: 2, order: 3) t2.withCursorAtStart { cursor in cursor.removeAllAfter(includingCurrent: false) } assertEqualElements(t2, [(0, "0")]) var t3 = maximalTree(depth: 2, order: 3) t3.withCursor(atOffset: 1) { cursor in cursor.removeAllAfter(includingCurrent: true) } assertEqualElements(t3, [(0, "0")]) var t4 = maximalTree(depth: 2, order: 3) t4.withCursor(atOffset: 1) { cursor in cursor.removeAllAfter(includingCurrent: false) } assertEqualElements(t4, [(0, "0"), (1, "1")]) var t5 = maximalTree(depth: 2, order: 3) t5.withCursor(atOffset: 10) { cursor in cursor.removeAllAfter(includingCurrent: true) } assertEqualElements(t5, (0 ..< 10).map { ($0, String($0)) }) var t6 = maximalTree(depth: 2, order: 3) t6.withCursor(atOffset: 10) { cursor in cursor.removeAllAfter(includingCurrent: false) } assertEqualElements(t6, (0 ... 10).map { ($0, String($0)) }) var t7 = maximalTree(depth: 2, order: 3) let c = t7.count t7.withCursor(atOffset: c - 1) { cursor in cursor.removeAllAfter(includingCurrent: false) } assertEqualElements(t7, (0 ..< c).map { ($0, String($0)) }) var t8 = maximalTree(depth: 2, order: 3) t8.withCursorAtEnd { cursor in cursor.removeAllAfter(includingCurrent: false) } assertEqualElements(t8, maximalTree(depth: 2, order: 3)) } }
mit
9b9d37b8babf0bf0a2cf960b9c39dde1
32.770739
95
0.503662
4.413562
false
true
false
false
pauljohanneskraft/Algorithms-and-Data-structures
AlgorithmsDataStructures/Classes/Lists/SinglyLinkedList.swift
1
3805
// // SinglyLinkedList.swift // Algorithms&DataStructures // // Created by Paul Kraft on 09.08.16. // Copyright © 2016 pauljohanneskraft. All rights reserved. // // swiftlint:disable trailing_whitespace public struct SinglyLinkedList<Element> { internal var root: Item? public init() { root = nil } } extension SinglyLinkedList { final class Item { public let data: Element public var next: Item? public init(data: Element, next: Item?) { self.data = data self.next = next } public convenience init(data: Element) { self.init(data: data, next: nil) } } } extension SinglyLinkedList.Item: ListItem { var description: String { guard let next = next else { return "\(data)" } return "\(data) -> \(next.description)" } func pushBack(_ newData: Element) { guard let next = next else { self.next = SinglyLinkedList.Item(data: newData) return } next.pushBack(newData) } } extension SinglyLinkedList: InternalList { typealias Node = Item mutating public func pushBack(_ element: Element) { guard let root = self.root else { self.root = Item(data: element) return } root.pushBack(element) } public mutating func popBack() -> Element? { guard root?.next != nil else { let tmp = root?.data; root = nil; return tmp } return root!.popBack() } public subscript(index: Int) -> Element? { get { guard index >= 0 else { return nil } var current = root for _ in 0..<index { current = current?.next } return current?.data } set { guard let newValue = newValue else { return } guard root != nil else { precondition(index == 0, "Index out of bounds. \(index) > 0.") root = Item(data: newValue) return } if index == 0 { root = Item(data: newValue, next: root?.next) return } var current = root var index = index - 1 while index > 0 { current = current?.next precondition(current != nil, "Index out of bounds.") index -= 1 } current!.next = Item(data: newValue, next: current?.next?.next) } } public mutating func insert(_ data: Element, at index: Int) throws { guard root != nil else { guard index == 0 else { throw ListError.indexOutOfRange } root = Item(data: data) return } var current = root var index = index - 1 while index > 0 { current = current?.next index -= 1 } guard current != nil else { throw ListError.indexOutOfRange } current!.next = Item(data: data, next: current?.next) } public mutating func remove(at index: Int) throws -> Element { guard index >= 0 else { throw ListError.indexOutOfRange } if index == 0 { let tmp = root!.data self.root = root?.next return tmp } var current = root var index = index - 1 while index > 0 { current = current?.next index -= 1 } guard current != nil else { throw ListError.indexOutOfRange } let next = current?.next let tmp = next!.data current!.next = next?.next return tmp } public var count: Int { if root == nil { return 0 } return root!.count } public init(arrayLiteral: Element...) { self.init() self.array = arrayLiteral } public var array: [Element] { get { return root?.array ?? [] } set { guard newValue.count > 0 else { return } self.root = Item(data: newValue.first!) for e in newValue.dropFirst() { self.root!.pushBack(e) } } } public var description: String { if root == nil { return "[]" } return "[" + root!.description + "]" } }
mit
8ae6f79bf8722d64b66eb07d7849a5a3
20.862069
79
0.584122
3.740413
false
false
false
false
eure/ReceptionApp
iOS/ReceptionApp/Transitions/PurposeSelectToConfirmOtherPresetTransitionController.swift
1
6358
// // PurposeSelectToConfirmOtherPresetTransitionController.swift // ReceptionApp // // Created by Hiroshi Kimura on 8/30/15. // Copyright © 2016 eureka, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import UIKit // MARK: - PurposeSelectToConfirmOtherPresetTransitionController final class PurposeSelectToConfirmOtherPresetTransitionController: NSObject, UIViewControllerAnimatedTransitioning { // MARK: Internal required init(operation: UINavigationControllerOperation) { self.operation = operation super.init() } // MARK: UIViewControllerAnimatedTransitioning @objc dynamic func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.8 } @objc dynamic func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView()! let offset = UIScreen.mainScreen().bounds.width switch self.operation { case .Push: let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! OtherPurposeSelectViewController let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ConfirmOtherPresetViewController let submitButton = toVC.submitButton let messageJaLabel = toVC.messageJaLabel let messageEnLabel = toVC.messageEnLabel let iconImageView = toVC.iconImageView submitButton.alpha = 0 messageJaLabel.alpha = 0 messageEnLabel.alpha = 0 iconImageView.alpha = 0 UIView.animateAndChainWithDuration( 0.4, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: .BeginFromCurrentState, animations: { fromVC.selectView.layer.transform = CATransform3DMakeTranslation(-offset, 0, 0) }, completion: { _ in containerView.addSubview(toVC.view) UIView.animateWithDuration( 0.3, delay: 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .BeginFromCurrentState, animations: { messageJaLabel.alpha = 1 messageEnLabel.alpha = 1 submitButton.alpha = 1 iconImageView.alpha = 1 }, completion: { _ in transitionContext.completeTransition(true) } ) } ) case .Pop: let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ConfirmOtherPresetViewController let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! OtherPurposeSelectViewController let submitButton = fromVC.submitButton let messageJaLabel = fromVC.messageJaLabel let messageEnLabel = fromVC.messageEnLabel let iconImageView = fromVC.iconImageView toVC.selectView.layer.transform = CATransform3DMakeTranslation(-offset, 0, 0) containerView.insertSubview(toVC.view, atIndex: 0) UIView.animateWithDuration( 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .BeginFromCurrentState, animations: { submitButton.alpha = 0 messageJaLabel.alpha = 0 messageEnLabel.alpha = 0 iconImageView.alpha = 0 }, completion: { _ in fromVC.view.removeFromSuperview() UIView.animateAndChainWithDuration( 0.4, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: .BeginFromCurrentState, animations: { toVC.selectView.layer.transform = CATransform3DIdentity }, completion: { _ in transitionContext.completeTransition(true) } ) } ) default: return } } // MARK: Private private let operation: UINavigationControllerOperation }
mit
d7bd282f745f1f5157ac069a14a5e432
37.762195
142
0.555608
6.748408
false
false
false
false
VeinGuo/VGPlayer
VGPlayer/Classes/MediaCache/VGPlayerResourceLoader.swift
1
2568
// // VGPlayerResourceLoader.swift // Pods // // Created by Vein on 2017/6/23. // // import Foundation import AVFoundation public protocol VGPlayerResourceLoaderDelegate: class { func resourceLoader(_ resourceLoader: VGPlayerResourceLoader, didFailWithError error:Error?) } open class VGPlayerResourceLoader: NSObject { open fileprivate(set) var url: URL open weak var delegate: VGPlayerResourceLoaderDelegate? fileprivate var downloader: VGPlayerDownloader fileprivate var pendingRequestWorkers = Dictionary<String ,VGPlayerResourceLoadingRequest>() fileprivate var isCancelled: Bool = false deinit { downloader.invalidateAndCancel() } public init(url: URL) { self.url = url downloader = VGPlayerDownloader(url: url) super.init() } open func add(_ request: AVAssetResourceLoadingRequest) { for (_, value) in pendingRequestWorkers { value.cancel() value.finish() } pendingRequestWorkers.removeAll() startWorker(request) } open func remove(_ request: AVAssetResourceLoadingRequest) { let key = self.key(forRequest: request) let loadingRequest = VGPlayerResourceLoadingRequest(downloader, request) loadingRequest.finish() pendingRequestWorkers.removeValue(forKey: key) } open func cancel() { downloader.cancel() } internal func startWorker(_ request: AVAssetResourceLoadingRequest) { let key = self.key(forRequest: request) let loadingRequest = VGPlayerResourceLoadingRequest(downloader, request) loadingRequest.delegate = self pendingRequestWorkers[key] = loadingRequest loadingRequest.startWork() } internal func key(forRequest request: AVAssetResourceLoadingRequest) -> String { if let range = request.request.allHTTPHeaderFields!["Range"]{ return String(format: "%@%@", (request.request.url?.absoluteString)!, range) } return String(format: "%@", (request.request.url?.absoluteString)!) } } // MARK: - VGPlayerResourceLoadingRequestDelegate extension VGPlayerResourceLoader: VGPlayerResourceLoadingRequestDelegate { public func resourceLoadingRequest(_ resourceLoadingRequest: VGPlayerResourceLoadingRequest, didCompleteWithError error: Error?) { remove(resourceLoadingRequest.request) if error != nil { delegate?.resourceLoader(self, didFailWithError: error) } } }
mit
badf9a84536dc13c7fe202417a7fc159
30.317073
134
0.681464
5.582609
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Views/MenuButton.swift
1
3067
// // MenuButton.swift // breadwallet // // Created by Adrian Corscadden on 2018-04-27. // Copyright © 2018-2019 Breadwinner AG. All rights reserved. // import UIKit class MenuButton: UIControl { private let container = UIView(color: .grayBackground) private let iconView = UIImageView() private let label = UILabel(font: .customBody(size: 16.0), color: .darkGray) private let arrow = UIImageView(image: #imageLiteral(resourceName: "RightArrow").withRenderingMode(.alwaysTemplate)) init(title: String, icon: UIImage) { label.text = title iconView.image = icon.withRenderingMode(.alwaysTemplate) super.init(frame: .zero) setup() } private func setup() { addSubviews() addConstraints() setupStyle() } private func addSubviews() { container.isUserInteractionEnabled = false label.isUserInteractionEnabled = false addSubview(container) container.addSubview(iconView) container.addSubview(label) container.addSubview(arrow) } private func addConstraints() { container.constrain(toSuperviewEdges: UIEdgeInsets(top: C.padding[1], left: C.padding[2], bottom: 0.0, right: -C.padding[2])) iconView.constrain([ iconView.heightAnchor.constraint(equalToConstant: 16.0), iconView.heightAnchor.constraint(equalTo: iconView.widthAnchor), iconView.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: C.padding[2]), iconView.centerYAnchor.constraint(equalTo: container.centerYAnchor) ]) label.constrain([ label.leadingAnchor.constraint(equalTo: iconView.trailingAnchor, constant: C.padding[1]), label.trailingAnchor.constraint(equalTo: arrow.leadingAnchor, constant: C.padding[1]), label.centerYAnchor.constraint(equalTo: container.centerYAnchor) ]) arrow.constrain([ arrow.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -C.padding[2]), arrow.widthAnchor.constraint(equalToConstant: 3.5), arrow.heightAnchor.constraint(equalToConstant: 6.0), arrow.centerYAnchor.constraint(equalTo: container.centerYAnchor) ]) } private func setupStyle() { container.layer.cornerRadius = C.Sizes.roundedCornerRadius container.clipsToBounds = true iconView.tintColor = .darkGray arrow.tintColor = .darkGray } override var isHighlighted: Bool { didSet { if isHighlighted { container.backgroundColor = .lightGray } else { container.backgroundColor = .grayBackground } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
a7696cdfb3a905eed00ef775d0a4a712
34.651163
120
0.614808
5.277108
false
false
false
false
iCrany/iOSExample
iOSExample/Module/CoreTextExample/View/RaywenderlichExample/CTSettings.swift
1
1600
// // CTSettings.swift // iOSExample // // Created by iCrany on 2017/11/1. // Copyright © 2017 iCrany. All rights reserved. // import Foundation class CTSettings: NSObject { // MARK: - Properties //The properties will determine the page margin (default of 20 for this tutorial); the number of columns per page; //the frame of each page containing the columns; and the frame size of each column per page. let margin: CGFloat = 20 var columnsPerPage: CGFloat! var pageRect: CGRect! var columnRect: CGRect! // MARK: - Initializers override init() { //2 Since this magazine serves both iPhone and iPad carrying zombies, //show two columns on iPad and one column on iPhone so the number of columns is appropriate for each screen size. columnsPerPage = UIDevice.current.userInterfaceIdiom == .phone ? 1 : 2 NSLog("CTSettings columnsPerPage: \(columnsPerPage)") //3 Inset the entire bounds of the page by the size of the margin to calculate pageRect. //默认设置为有 NavigationBar 的情况,高度为 64 let viewInsets: CGRect = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64) pageRect = viewInsets.insetBy(dx: margin, dy: margin) //4 Divide pageRect's width by the number of columns per page and inset that new frame with the margin for columnRect. columnRect = CGRect(x: 0, y: 0, width: pageRect.width / columnsPerPage, height: pageRect.height).insetBy(dx: margin, dy: margin) } }
mit
c652bc0c931dac6c7818a9ebccff14ef
39.333333
133
0.678957
4.251351
false
false
false
false
jjatie/Charts
Source/Charts/Data/ChartData/RadarChartData.swift
1
1276
// // RadarChartData.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import CoreGraphics import Foundation open class RadarChartData: ChartData { open var highlightColor = NSUIColor(red: 255.0 / 255.0, green: 187.0 / 255.0, blue: 115.0 / 255.0, alpha: 1.0) open var highlightLineWidth = CGFloat(1.0) open var highlightLineDashPhase = CGFloat(0.0) open var highlightLineDashLengths: [CGFloat]? /// Sets labels that should be drawn around the RadarChart at the end of each web line. open var labels = [String]() /// Sets the labels that should be drawn around the RadarChart at the end of each web line. open func setLabels(_ labels: String...) { self.labels = labels } public required init() { super.init() } override public init(dataSets: [ChartDataSet]) { super.init(dataSets: dataSets) } public required init(arrayLiteral elements: ChartDataSet...) { super.init(dataSets: elements) } override open func entry(for highlight: Highlight) -> ChartDataEntry? { self[highlight.dataSetIndex][Int(highlight.x)] } }
apache-2.0
6339dbcb152e0316e932e9c62541dd7c
28
114
0.675549
4.183607
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureKYC/Sources/FeatureKYCUI/Views/ValidationFields/ValidationTextField/ValidationTextField.swift
1
8724
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit import UIKit enum ValidationError: Error { case unknown case invalidSelection case minimumDateRequirement } enum ValidationResult { case valid case invalid(ValidationError?) } extension ValidationResult { static func == (lhs: ValidationResult, rhs: ValidationResult) -> Bool { switch (lhs, rhs) { case (.valid, .valid): return true case (.valid, .invalid): return false case (.invalid, .valid): return false case (.invalid, .invalid): return true } } } typealias ValidationBlock = (String?) -> ValidationResult @IBDesignable class ValidationTextField: NibBasedView { // MARK: Private Class Properties fileprivate static let primaryFont = UIFont( name: Constants.FontNames.montserratRegular, size: Constants.FontSizes.Small ) ?? UIFont.systemFont(ofSize: 16) // MARK: Private Properties fileprivate var validity: ValidationResult = .valid override var bundle: Bundle { .module } // MARK: IBInspectable Properties @IBInspectable var baselineFillColor = UIColor.gray3 { didSet { baselineView.backgroundColor = baselineFillColor } } @IBInspectable var supportsAutoCorrect: Bool = false { didSet { textField.autocorrectionType = supportsAutoCorrect == false ? .no : .yes } } /// Fill color for placeholder text. @IBInspectable var placeholderFillColor = UIColor.gray3 /// If the field is optional than this should be `true`. /// This prevents you from having to check the field for /// any input in the `validationBlock`. The `validationBlock` /// should only be used for custom validation logic. @IBInspectable var optionalField: Bool = true @IBInspectable var placeholder: String = "" { didSet { let font = UIFont( name: Constants.FontNames.montserratRegular, size: Constants.FontSizes.Small ) ?? UIFont.systemFont(ofSize: 16) let value = NSAttributedString( string: placeholder, attributes: [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: placeholderFillColor ] ) textField.attributedPlaceholder = value } } @IBInspectable var textColor = UIColor.darkGray { didSet { textField.textColor = textColor } } // MARK: Public Properties var accessoryView: UIView? { didSet { textField.inputAccessoryView = accessoryView } } var autocapitalizationType: UITextAutocapitalizationType = .words { didSet { textField.autocapitalizationType = autocapitalizationType } } var font: UIFont = ValidationTextField.primaryFont { didSet { textField.font = font } } var returnKeyType: UIReturnKeyType = .default { didSet { textField.returnKeyType = returnKeyType } } var keyboardType: UIKeyboardType = .default { didSet { textField.keyboardType = keyboardType } } var contentType: UITextContentType? { didSet { textField.textContentType = contentType } } var text: String? { get { textField.text } set { textField.text = newValue } } var textFieldInputView: UIView? { didSet { textField.inputView = textFieldInputView } } var isEnabled: Bool { get { textField.isEnabled } set { textField.isEnabled = newValue updateBackgroundColor() } } override var accessibilityIdentifier: String? { didSet { textField.accessibilityIdentifier = accessibilityIdentifier } } /// This closure is called when the user taps `next` /// or `done` etc. and the `textField` resigns. var returnTappedBlock: (() -> Void)? /// This closure is called when a field is in /// focus. You can use it to handle scrolling to /// the particular textField. var becomeFirstResponderBlock: ((ValidationTextField) -> Void)? /// This closure is responsible for validation. /// If the return value is invalid, the error state /// is shown. var validationBlock: ValidationBlock? /// This closure is called whenever the text is changed /// inside the contained UITextField var textChangedBlock: ((String?) -> Void)? /// This closure is called before the text in the text field is replaced. /// You can use this replacement block if you wish to format the text /// before it gets replaced. var textReplacementBlock: ((String) -> String)? // MARK: Private IBOutlets @IBOutlet fileprivate var textField: UITextField! @IBOutlet fileprivate var baselineView: UIView! @IBOutlet fileprivate var textFieldTrailingConstraint: NSLayoutConstraint! @IBOutlet fileprivate var errorImageView: UIImageView! // MARK: Public Functions func isFocused() -> Bool { textField.isFirstResponder } func becomeFocused() { textField.becomeFirstResponder() } func resignFocus() { textField.resignFirstResponder() } func validate(withStyling: Bool = false) -> ValidationResult { if let block = validationBlock { validity = block(textField.text) } else { if textField.text?.count == 0 || textField.text == nil { validity = optionalField ? .valid : .invalid(nil) } else { validity = .valid } } guard withStyling == true else { return validity } applyValidity(animated: true) return validity } // MARK: Private IBActions @IBAction fileprivate func onTextFieldChanged(_ sender: Any) { textChangedBlock?(textField.text) } // MARK: Private Functions private func updateBackgroundColor() { backgroundColor = isEnabled ? .white : .disabled textField.backgroundColor = backgroundColor } fileprivate func applyValidity(animated: Bool) { switch validity { case .valid: guard textFieldTrailingConstraint.constant != 0 else { return } textFieldTrailingConstraint.constant = 0 baselineFillColor = .gray2 case .invalid: guard textFieldTrailingConstraint.constant != errorImageView.bounds.width else { return } textFieldTrailingConstraint.constant = errorImageView.bounds.width baselineFillColor = .red } setNeedsLayout() guard animated == true else { layoutIfNeeded() return } UIView.animate( withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .curveEaseOut], animations: { self.layoutIfNeeded() }, completion: nil ) } } extension ValidationTextField: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } guard let textReplacementBlock = textReplacementBlock else { return true } let replacedString = (text as NSString).replacingCharacters(in: range, with: string) textField.text = textReplacementBlock(replacedString) return false } func textFieldDidBeginEditing(_ textField: UITextField) { if let responderBlock = becomeFirstResponderBlock { responderBlock(self) } } func textFieldDidEndEditing(_ textField: UITextField) { if let block = validationBlock { validity = block(textField.text) applyValidity(animated: true) return } if textField.text?.count == 0 || textField.text == nil { validity = optionalField ? .valid : .invalid(nil) } else { validity = .valid } applyValidity(animated: true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let block = returnTappedBlock { block() } else { textField.resignFirstResponder() } return true } }
lgpl-3.0
bda5cb511cbcc0add32e317e2fa5d033
26.780255
129
0.606557
5.531389
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Foundation/Extensions/UITabBarItem+Conveniences.swift
1
845
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct TabItemContent { let title: String let image: String let selectedImage: String let accessibility: Accessibility public init( title: String, image: String, selectedImage: String, accessibility: Accessibility ) { self.title = title self.image = image self.selectedImage = selectedImage self.accessibility = accessibility } } extension UITabBarItem { public convenience init(with content: TabItemContent) { self.init( title: content.title, image: UIImage(named: content.image), selectedImage: UIImage(named: content.selectedImage) ) accessibilityIdentifier = content.accessibility.id } }
lgpl-3.0
8378206830ef1de4e5e58202b90a40d8
24.575758
64
0.645735
5.146341
false
false
false
false
LeLuckyVint/MessageKit
Sources/Models/MessageStyle.swift
1
3873
/* MIT License Copyright (c) 2017 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public enum MessageStyle { // MARK: - TailCorner public enum TailCorner { case topLeft case bottomLeft case topRight case bottomRight var imageOrientation: UIImageOrientation { switch self { case .bottomRight: return .up case .bottomLeft: return .upMirrored case .topLeft: return .down case .topRight: return .downMirrored } } } // MARK: - TailStyle public enum TailStyle { case curved case pointedEdge var imageNameSuffix: String { switch self { case .curved: return "_tail_v2" case .pointedEdge: return "_tail_v1" } } } // MARK: - MessageStyle case none case bubble case bubbleOutline(UIColor) case bubbleTail(TailCorner, TailStyle) case bubbleTailOutline(UIColor, TailCorner, TailStyle) case custom((MessageContainerView) -> Void) // MARK: - Public public var image: UIImage? { guard let path = imagePath else { return nil } guard var image = UIImage(contentsOfFile: path) else { return nil } switch self { case .none, .custom: return nil case .bubble, .bubbleOutline: break case .bubbleTail(let corner, _), .bubbleTailOutline(_, let corner, _): guard let cgImage = image.cgImage else { return nil } image = UIImage(cgImage: cgImage, scale: image.scale, orientation: corner.imageOrientation) } return stretch(image).withRenderingMode(.alwaysTemplate) } // MARK: - Private private var imageName: String? { switch self { case .bubble: return "bubble_full" case .bubbleOutline: return "bubble_outlined" case .bubbleTail(_, let tailStyle): return "bubble_full" + tailStyle.imageNameSuffix case .bubbleTailOutline(_, _, let tailStyle): return "bubble_outlined" + tailStyle.imageNameSuffix case .none, .custom: return nil } } private var imagePath: String? { guard let imageName = imageName else { return nil } let assetBundle = Bundle.messageKitAssetBundle() return assetBundle.path(forResource: imageName, ofType: "png", inDirectory: "Images") } private func stretch(_ image: UIImage) -> UIImage { let center = CGPoint(x: image.size.width / 2, y: image.size.height / 2) let capInsets = UIEdgeInsets(top: center.y, left: center.x, bottom: center.y, right: center.x) return image.resizableImage(withCapInsets: capInsets, resizingMode: .stretch) } }
mit
b1f4f774b7913497759354f563b5e6bb
30.233871
103
0.645494
4.781481
false
false
false
false
danielsaidi/iExtra
iExtra/UI/Extensions/UIColor/UIColor+Hex.swift
1
3359
// // UIColor+Hex.swift // iExtra // // Created by Daniel Saidi on 2015-01-22. // Copyright © 2018 Daniel Saidi. All rights reserved. // import UIKit public extension UIColor { // MARK: - Initialization convenience init(hex: Int, alpha: CGFloat = 1.0) { let red = CGFloat((hex >> 16) & 0xff) / 255 let green = CGFloat((hex >> 08) & 0xff) / 255 let blue = CGFloat((hex >> 00) & 0xff) / 255 self.init(red: red, green: green, blue: blue, alpha: alpha) } convenience init(hexString hex: String) { var hex = hex if hex.hasPrefix("#") { let index = hex.index(hex.startIndex, offsetBy: 1) hex = String(hex.suffix(from: index)) } var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch hex.count { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: break } } self.init(red: red, green: green, blue: blue, alpha: alpha) } // MARK: - Public Properties var hexString: String { return hexString(withAlpha: false) } // MARK: - Public Functions func hexString(withAlpha: Bool) -> String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let red = Int(r * 255) let green = Int(g * 255) let blue = Int(b * 255) let alpha = Int(a * 255) let alphaFormat = "#%02X%02X%02X%02X" let nonAlphaFormat = "#%02X%02X%02X" return withAlpha ? String(format: alphaFormat, red, green, blue, alpha) : String(format: nonAlphaFormat, red, green, blue) } } // MARK: - Private Functions private extension UIColor { func removeHash(in string: String) -> String { guard string.hasPrefix("#") else { return string } let index = string.index(string.startIndex, offsetBy: 1) return String(string.suffix(from: index)) } }
mit
ec07035a208d3c95d24d80775073ca66
30.679245
70
0.497915
3.868664
false
false
false
false
juliantejera/JTDataStructures
JTDataStructures/Queues/Queue.swift
1
1003
// // Queue.swift // JTDataStructures // // Created by Julian Tejera-Frias on 7/10/16. // Copyright © 2016 Julian Tejera. All rights reserved. // import Foundation public struct Queue<T> { private var head: Node<T>? private var tail: Node<T>? public private(set) var count: Int public var isEmpty: Bool { return head == nil } public init() { self.count = 0 } public mutating func enqueue(value: T) { let node = Node(value: value) if head == nil { head = node tail = head } else { tail?.next = node tail = node } count += 1 } public mutating func dequeue() -> T? { if head == nil { return nil } let value = head?.value head = head?.next if head == nil { tail = nil } count -= 1 return value } }
mit
55ea0d378f1ca4d8705bae24b6d0c11d
17.555556
56
0.46507
4.318966
false
false
false
false
myhyazid/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Views/NoteUndoOverlayView.swift
12
1614
import Foundation /** * @class NoteUndoOverlayView * @brief This class renders a simple overlay view, with a Legend Label on its right, and an undo button on its * right side. * @details The purpose of this helper view is to act as a simple drop-in overlay, to be used by NoteTableViewCell. * By doing this, we avoid the need of having yet another UITableViewCell subclass, and thus, * we don't need to duplicate any of the mechanisms already available in NoteTableViewCell, such as * custom cell separators and Height Calculation. */ @objc public class NoteUndoOverlayView : UIView { // MARK: - NSCoder public override func awakeFromNib() { super.awakeFromNib() backgroundColor = Style.noteUndoBackgroundColor // Legend legendLabel.text = NSLocalizedString("Comment has been deleted", comment: "Displayed when a Comment is removed") legendLabel.textColor = Style.noteUndoTextColor legendLabel.font = Style.noteUndoTextFont // Button undoButton.titleLabel?.font = Style.noteUndoTextFont undoButton.setTitle(NSLocalizedString("Undo", comment: "Revert an operation"), forState: .Normal) undoButton.setTitleColor(Style.noteUndoTextColor, forState: .Normal) } // MARK: - Private Alias private typealias Style = WPStyleGuide.Notifications // MARK: - Private Outlets @IBOutlet private weak var legendLabel: UILabel! @IBOutlet private weak var undoButton: UIButton! }
gpl-2.0
8c0d1724d7916192220f9489158c3225
39.35
127
0.667906
5.12381
false
false
false
false
lorentey/swift
validation-test/stdlib/SwiftNativeNSBase.swift
5
3609
//===--- SwiftNativeNSBase.swift - Test __SwiftNativeNS*Base classes -------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %empty-directory(%t) // // RUN: %target-clang %S/Inputs/SwiftNativeNSBase/SwiftNativeNSBase.m -c -o %t/SwiftNativeNSBase.o -g // RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o // RUN: echo '#sourceLocation(file: "%s", line: 1)' > "%t/main.swift" && cat "%s" >> "%t/main.swift" && chmod -w "%t/main.swift" // RUN: %target-build-swift -Xfrontend -disable-access-control %t/main.swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift -I %S/Inputs/SwiftNativeNSBase/ -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -Xlinker %t/SwiftNativeNSBase.o -o %t/SwiftNativeNSBase -swift-version 4.2 // RUN: %target-codesign %t/SwiftNativeNSBase // RUN: %target-run %t/SwiftNativeNSBase // REQUIRES: executable_test // REQUIRES: objc_interop // The oldest ABI-stable stdlibs don't have a __SwiftNativeNSMutableArrayBase // class, so they can't run the UnwantedCdtors test. // FIXME: This should be based on a runtime library version check. // UNSUPPORTED: use_os_stdlib import Foundation import StdlibUnittest @_silgen_name("TestSwiftNativeNSBase_UnwantedCdtors") func TestSwiftNativeNSBase_UnwantedCdtors() -> Bool @_silgen_name("TestSwiftNativeNSBase_RetainCount") func TestSwiftNativeNSBase_RetainCount(_: UnsafeMutableRawPointer) -> Bool func classChain(of cls: AnyClass) -> [String] { var chain: [String] = [] var cls: AnyClass? = cls while cls != nil { chain.append(NSStringFromClass(cls!)) cls = class_getSuperclass(cls) } return chain } var SwiftNativeNSBaseTestSuite = TestSuite("SwiftNativeNSBase") SwiftNativeNSBaseTestSuite.test("UnwantedCdtors") { expectTrue(TestSwiftNativeNSBase_UnwantedCdtors()) } SwiftNativeNSBaseTestSuite.test("__SwiftNativeNSArrayBase.retainCount") { let bridged = getBridgedNSArrayOfRefTypeVerbatimBridged() assert(classChain(of: type(of: bridged)).contains("__SwiftNativeNSArrayBase")) expectTrue(TestSwiftNativeNSBase_RetainCount( Unmanaged.passUnretained(bridged).toOpaque())) _fixLifetime(bridged) } SwiftNativeNSBaseTestSuite.test("__SwiftNativeNSDictionaryBase.retainCount") { let bridged = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() assert(classChain(of: type(of: bridged)) .contains("__SwiftNativeNSDictionaryBase")) expectTrue(TestSwiftNativeNSBase_RetainCount( Unmanaged.passUnretained(bridged).toOpaque())) _fixLifetime(bridged) } SwiftNativeNSBaseTestSuite.test("__SwiftNativeNSSetBase.retainCount") { let bridged = Set([10, 20, 30].map{ TestObjCKeyTy($0) })._bridgeToObjectiveC() assert(classChain(of: type(of: bridged)).contains("__SwiftNativeNSSetBase")) expectTrue(TestSwiftNativeNSBase_RetainCount( Unmanaged.passUnretained(bridged).toOpaque())) _fixLifetime(bridged) } SwiftNativeNSBaseTestSuite.setUp { resetLeaksOfDictionaryKeysValues() resetLeaksOfObjCDictionaryKeysValues() } SwiftNativeNSBaseTestSuite.tearDown { expectNoLeaksOfDictionaryKeysValues() expectNoLeaksOfObjCDictionaryKeysValues() } runAllTests()
apache-2.0
3fbf3b7d196286677c85ffaf203ac329
39.550562
338
0.747298
4.422794
false
true
false
false
lorentey/swift
test/decl/protocol/req/recursion.swift
5
3194
// RUN: %target-typecheck-verify-swift protocol SomeProtocol { associatedtype T } extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}} // rdar://problem/19840527 class X<T> where T == X { // expected-error{{same-type constraint 'T' == 'X<T>' is recursive}} // expected-error@-1{{same-type requirement makes generic parameter 'T' non-generic}} var type: T { return Swift.type(of: self) } // expected-error{{cannot convert return expression of type 'X<T>.Type' to return type 'T'}} } // FIXME: The "associated type 'Foo' is not a member type of 'Self'" diagnostic // should also become "associated type 'Foo' references itself" protocol CircularAssocTypeDefault { associatedtype Z = Z // expected-error{{associated type 'Z' references itself}} // expected-note@-1{{type declared here}} // expected-note@-2{{protocol requires nested type 'Z'; do you want to add it?}} associatedtype Z2 = Z3 // expected-note@-1{{protocol requires nested type 'Z2'; do you want to add it?}} associatedtype Z3 = Z2 // expected-note@-1{{protocol requires nested type 'Z3'; do you want to add it?}} associatedtype Z4 = Self.Z4 // expected-error{{associated type 'Z4' references itself}} // expected-note@-1{{type declared here}} // expected-note@-2{{protocol requires nested type 'Z4'; do you want to add it?}} associatedtype Z5 = Self.Z6 // expected-note@-1{{protocol requires nested type 'Z5'; do you want to add it?}} associatedtype Z6 = Self.Z5 // expected-note@-1{{protocol requires nested type 'Z6'; do you want to add it?}} } struct ConformsToCircularAssocTypeDefault : CircularAssocTypeDefault { } // expected-error@-1 {{type 'ConformsToCircularAssocTypeDefault' does not conform to protocol 'CircularAssocTypeDefault'}} // rdar://problem/20000145 public protocol P { associatedtype T } public struct S<A: P> where A.T == S<A> { // expected-error {{circular reference}} // expected-note@-1 {{type declared here}} // expected-error@-2 {{generic struct 'S' references itself}} func f(a: A.T) { g(a: id(t: a)) // expected-error@-1 {{cannot convert value of type 'A.T' to expected argument type 'S<A>'}} _ = A.T.self } func g(a: S<A>) { f(a: id(t: a)) // expected-error@-1 {{cannot convert value of type 'S<A>' to expected argument type 'A.T'}} _ = S<A>.self } func id<T>(t: T) -> T { return t } } protocol I { init() } protocol PI { associatedtype T : I } struct SI<A: PI> : I where A : I, A.T == SI<A> { // expected-error {{circular reference}} // expected-note@-1 {{type declared here}} // expected-error@-2 {{generic struct 'SI' references itself}} func ggg<T : I>(t: T.Type) -> T { return T() } func foo() { _ = A() _ = A.T() _ = SI<A>() _ = ggg(t: A.self) _ = ggg(t: A.T.self) _ = self.ggg(t: A.self) _ = self.ggg(t: A.T.self) } } // Used to hit infinite recursion struct S4<A: PI> : I where A : I { } struct S5<A: PI> : I where A : I, A.T == S4<A> { } // Used to hit ArchetypeBuilder assertions struct SU<A: P> where A.T == SU { } struct SIU<A: PI> : I where A : I, A.T == SIU { }
apache-2.0
32b61133153007f5ecad448e9a62f83a
29.132075
140
0.646525
3.21005
false
false
false
false
jkascend/free-blur
free-blur/GaussMat.swift
1
1408
// // GaussMat.swift // free-blur // // Created by Justin Kambic on 6/8/17. // import Foundation struct GaussMat { private var _mat : [[Float]] var mat : [[Float]] { return self._mat } var matWidth : Int { if self._mat.count > 0 { return self._mat[0].count } return -1 } var matHeight : Int { return self._mat.count } var matCenterX : Int { return self.matWidth / 2 + 1 } var matCenterY : Int { return self.matHeight / 2 + 1 } init(diameter: Int, weight: Float) { self._mat = Array(repeating: Array(repeating: Float(), count:diameter), count: diameter) var matSum : Float = 0 let e = 1.0 / (2.0 * Float.pi * pow(weight, 2)) let radius = Int(diameter / 2) for y in -radius ... radius { for x in -radius ... radius { let distance = (Float((x * x) + (y * y))) / (2 * pow(weight, 2)) self._mat[y + radius][x + radius] = e * exp(-distance) matSum += self._mat[y + radius][x + radius] } } for y in 0 ..< self._mat.count { for x in 0 ..< self._mat.count { self._mat[y][x] *= (1.0 / matSum) } } } }
mit
7b345eb799b9e7628058bff2702e8029
22.081967
96
0.4375
3.815718
false
false
false
false
nobre84/DTIActivityIndicatorView-Swift
Source/DTIAnimWanderingCubes.swift
5
5332
// // DTIAnimWanderingCubes.swift // SampleObjc // // Created by dtissera on 20/08/2014. // Copyright (c) 2014 o--O--o. All rights reserved. // import UIKit import QuartzCore class DTIAnimWanderingCubes: DTIAnimProtocol { /** private properties */ private let owner: DTIActivityIndicatorView private let spinnerView = UIView() private let animationDuration = CFTimeInterval(1.8) private let cubeCount = 2 /** ctor */ init(indicatorView: DTIActivityIndicatorView) { self.owner = indicatorView for var index = 0; index < cubeCount; ++index { let cubeLayer = CALayer() self.spinnerView.layer.addSublayer(cubeLayer) } } // ------------------------------------------------------------------------- // DTIAnimProtocol // ------------------------------------------------------------------------- func needLayoutSubviews() { self.spinnerView.frame = self.owner.bounds let cubeSize = CGFloat(floor(self.owner.bounds.width / 3.5)) for var index = 0; index < cubeCount; ++index { let layer = self.spinnerView.layer.sublayers[index] as! CALayer layer.frame = CGRect(x: 0.0, y: 0.0, width: cubeSize, height: cubeSize) } } func needUpdateColor() { // Debug stuff // self.spinnerView.backgroundColor = UIColor.grayColor() for var index = 0; index < cubeCount; ++index { let cubeLayer = self.spinnerView.layer.sublayers[index] as! CALayer cubeLayer.backgroundColor = self.owner.indicatorColor.CGColor } } func setUp() { //self.spinnerView.layer.shouldRasterize = true } func startActivity() { self.owner.addSubview(self.spinnerView) let beginTime = CACurrentMediaTime(); for var index = 0; index < cubeCount; ++index { let cubeLayer = self.spinnerView.layer.sublayers[index] as! CALayer let translation = self.spinnerView.bounds.size.width-cubeLayer.bounds.size.width let aniTransform = CAKeyframeAnimation(keyPath: "transform") aniTransform.removedOnCompletion = false aniTransform.repeatCount = HUGE aniTransform.duration = self.animationDuration aniTransform.beginTime = beginTime - CFTimeInterval(CGFloat(index)*CGFloat(self.animationDuration)/CGFloat(cubeCount)); aniTransform.keyTimes = [0.0, 0.25, 0.5, 0.75, 1.0]; aniTransform.timingFunctions = [ CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) ] var transform0 = CATransform3DIdentity; // -90° var transform1 = CATransform3DMakeTranslation(translation, 0.0, 0.0); transform1 = CATransform3DRotate(transform1, -CGFloat(M_PI/2), 0.0, 0.0, 1.0); transform1 = CATransform3DScale(transform1, 0.5, 0.5, 1.0); // -180° var transform2 = CATransform3DMakeTranslation(translation, translation, 0.0); transform2 = CATransform3DRotate(transform2, -CGFloat(M_PI), 0.0, 0.0, 1.0); transform2 = CATransform3DScale(transform2, 1.0, 1.0, 1.0); // -270° var transform3 = CATransform3DMakeTranslation(0.0, translation, 0.0); transform3 = CATransform3DRotate(transform3, -CGFloat(M_PI*9/6), 0.0, 0.0, 1.0); transform3 = CATransform3DScale(transform3, 0.5, 0.5, 1.0); // -360° var transform4 = CATransform3DMakeTranslation(0.0, 0.0, 0.0); transform4 = CATransform3DRotate(transform4, -CGFloat(2*M_PI), 0.0, 0.0, 1.0); transform4 = CATransform3DScale(transform4, 1.0, 1.0, 1.0); aniTransform.values = [ NSValue(CATransform3D: transform0), NSValue(CATransform3D: transform1), NSValue(CATransform3D: transform2), NSValue(CATransform3D: transform3), NSValue(CATransform3D: transform4) ] cubeLayer.shouldRasterize = true cubeLayer.addAnimation(aniTransform, forKey: "DTIAnimWanderingCubes~transform\(index)") } } func stopActivity(animated: Bool) { func removeAnimations() { self.spinnerView.layer.removeAllAnimations() for var index = 0; index < cubeCount; ++index { let layer = self.spinnerView.layer.sublayers[index] as! CALayer layer.removeAllAnimations() } self.spinnerView.removeFromSuperview() } if (animated) { self.spinnerView.layer.dismissAnimated(removeAnimations) } else { removeAnimations() } } }
mit
d14a0589614cd2fb7aa2b025b9caf013
37.890511
131
0.576952
4.947075
false
false
false
false
pixelmaid/piper
Pods/Starscream/Source/SSLSecurity.swift
2
8934
////////////////////////////////////////////////////////////////////////////////////////////////// // // SSLSecurity.swift // Starscream // // Created by Dalton Cherry on 5/16/15. // Copyright (c) 2014-2015 Dalton Cherry. // // 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 Security public class SSLCert { var certData: NSData? var key: SecKeyRef? /** Designated init for certificates - parameter data: is the binary data of the certificate - returns: a representation security object to be used with */ public init(data: NSData) { self.certData = data } /** Designated init for public keys - parameter key: is the public key to be used - returns: a representation security object to be used with */ public init(key: SecKeyRef) { self.key = key } } public class SSLSecurity { public var validatedDN = true //should the domain name be validated? var isReady = false //is the key processing done? var certificates: [NSData]? //the certificates var pubKeys: [SecKeyRef]? //the public keys var usePublicKeys = false //use public keys or certificate validation? /** Use certs from main app bundle - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public convenience init(usePublicKeys: Bool = false) { let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".") let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in var certs = certs if let data = NSData(contentsOfFile: path) { certs.append(SSLCert(data: data)) } return certs } self.init(certs: certs, usePublicKeys: usePublicKeys) } /** Designated init - parameter keys: is the certificates or public keys to use - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public init(certs: [SSLCert], usePublicKeys: Bool) { self.usePublicKeys = usePublicKeys if self.usePublicKeys { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) { let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in var pubKeys = pubKeys if let data = cert.certData where cert.key == nil { cert.key = self.extractPublicKey(data) } if let key = cert.key { pubKeys.append(key) } return pubKeys } self.pubKeys = pubKeys self.isReady = true } } else { let certificates = certs.reduce([NSData]()) { (certificates: [NSData], cert: SSLCert) -> [NSData] in var certificates = certificates if let data = cert.certData { certificates.append(data) } return certificates } self.certificates = certificates self.isReady = true } } /** Valid the trust and domain name. - parameter trust: is the serverTrust to validate - parameter domain: is the CN domain to validate - returns: if the key was successfully validated */ public func isValid(trust: SecTrustRef, domain: String?) -> Bool { var tries = 0 while(!self.isReady) { usleep(1000) tries += 1 if tries > 5 { return false //doesn't appear it is going to ever be ready... } } var policy: SecPolicyRef if self.validatedDN { policy = SecPolicyCreateSSL(true, domain) } else { policy = SecPolicyCreateBasicX509() } SecTrustSetPolicies(trust,policy) if self.usePublicKeys { if let keys = self.pubKeys { let serverPubKeys = publicKeyChainForTrust(trust) for serverKey in serverPubKeys as [AnyObject] { for key in keys as [AnyObject] { if serverKey.isEqual(key) { return true } } } } } else if let certs = self.certificates { let serverCerts = certificateChainForTrust(trust) var collect = [SecCertificate]() for cert in certs { collect.append(SecCertificateCreateWithData(nil,cert)!) } SecTrustSetAnchorCertificates(trust,collect) var result = SecTrustResultType(rawValue: 0) SecTrustEvaluate(trust,&result!) let r = result if r == SecTrustResultType.Unspecified || r == SecTrustResultType.Proceed { var trustedCount = 0 for serverCert in serverCerts { for cert in certs { if cert == serverCert { trustedCount += 1 break } } } if trustedCount == serverCerts.count { return true } } } return false } /** Get the public key from a certificate data - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKey(data: NSData) -> SecKeyRef? { guard let cert = SecCertificateCreateWithData(nil, data) else { return nil } return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509()) } /** Get the public key from a certificate - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? { var possibleTrust: SecTrust? SecTrustCreateWithCertificates(cert, policy, &possibleTrust) guard let trust = possibleTrust else { return nil } var result = SecTrustResultType(rawValue: 0) SecTrustEvaluate(trust, &result!) return SecTrustCopyPublicKey(trust) } /** Get the certificate chain for the trust - parameter trust: is the trust to lookup the certificate chain for - returns: the certificate chain for the trust */ func certificateChainForTrust(trust: SecTrustRef) -> [NSData] { let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (certificates: [NSData], index: Int) -> [NSData] in var certificates = certificates let cert = SecTrustGetCertificateAtIndex(trust, index) certificates.append(SecCertificateCopyData(cert!)) return certificates } return certificates } /** Get the public key chain for the trust - parameter trust: is the trust to lookup the certificate chain and extract the public keys - returns: the public keys from the certifcate chain for the trust */ func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] { let policy = SecPolicyCreateBasicX509() let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (keys: [SecKeyRef], index: Int) -> [SecKeyRef] in var keys = keys let cert = SecTrustGetCertificateAtIndex(trust, index) if let key = extractPublicKeyFromCert(cert!, policy: policy) { keys.append(key) } return keys } return keys } }
mit
700f6166c862ef2e9e64991cb676da4c
32.969582
140
0.556414
5.538748
false
false
false
false
tjw/swift
stdlib/public/core/HeapBuffer.swift
2
2436
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims typealias _HeapObject = SwiftShims.HeapObject @usableFromInline internal protocol _HeapBufferHeader_ { associatedtype Value init(_ value: Value) var value: Value { get set } } @_fixed_layout // FIXME(sil-serialize-all) @usableFromInline internal struct _HeapBufferHeader<T> : _HeapBufferHeader_ { internal typealias Value = T @inlinable // FIXME(sil-serialize-all) internal init(_ value: T) { self.value = value } @usableFromInline // FIXME(sil-serialize-all) internal var value: T } internal typealias _HeapBuffer<Value,Element> = ManagedBufferPointer<_HeapBufferHeader<Value>, Element> internal typealias _HeapBufferStorage<Value,Element> = ManagedBuffer<_HeapBufferHeader<Value>, Element> extension ManagedBufferPointer where Header : _HeapBufferHeader_ { internal typealias Value = Header.Value @inlinable // FIXME(sil-serialize-all) internal init( _ storageClass: AnyClass, _ initializer: Value, _ capacity: Int ) { self.init( _uncheckedBufferClass: storageClass, minimumCapacity: capacity) self.withUnsafeMutablePointerToHeader { $0.initialize(to: Header(initializer)) } } @inlinable // FIXME(sil-serialize-all) internal var value: Value { @inline(__always) get { return header.value } @inline(__always) set { return header.value = newValue } } @inlinable // FIXME(sil-serialize-all) internal subscript(i: Int) -> Element { @inline(__always) get { return withUnsafeMutablePointerToElements { $0[i] } } } @inlinable // FIXME(sil-serialize-all) internal var baseAddress: UnsafeMutablePointer<Element> { @inline(__always) get { return withUnsafeMutablePointerToElements { $0 } } } @inlinable // FIXME(sil-serialize-all) internal var storage: AnyObject? { @inline(__always) get { return buffer } } }
apache-2.0
33301ee50fa7edda5a49fc4cbd243817
26.066667
80
0.650657
4.544776
false
false
false
false
nathawes/swift
stdlib/public/Darwin/Foundation/UUID.swift
9
6185
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import Darwin.uuid @_implementationOnly import _SwiftCoreFoundationOverlayShims /// Represents UUID strings, which can be used to uniquely identify types, interfaces, and other items. @available(macOS 10.8, iOS 6.0, *) public struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConvertible { public typealias ReferenceType = NSUUID public private(set) var uuid: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) /* Create a new UUID with RFC 4122 version 4 random bytes */ public init() { withUnsafeMutablePointer(to: &uuid) { $0.withMemoryRebound(to: UInt8.self, capacity: 16) { uuid_generate_random($0) } } } private init(reference: __shared NSUUID) { var bytes: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) withUnsafeMutablePointer(to: &bytes) { $0.withMemoryRebound(to: UInt8.self, capacity: 16) { reference.getBytes($0) } } uuid = bytes } /// Create a UUID from a string such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F". /// /// Returns nil for invalid strings. public init?(uuidString string: __shared String) { let res = withUnsafeMutablePointer(to: &uuid) { $0.withMemoryRebound(to: UInt8.self, capacity: 16) { return uuid_parse(string, $0) } } if res != 0 { return nil } } /// Create a UUID from a `uuid_t`. public init(uuid: uuid_t) { self.uuid = uuid } /// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" public var uuidString: String { var bytes: uuid_string_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) return withUnsafePointer(to: uuid) { $0.withMemoryRebound(to: UInt8.self, capacity: 16) { val in withUnsafeMutablePointer(to: &bytes) { $0.withMemoryRebound(to: Int8.self, capacity: 37) { str in uuid_unparse(val, str) return String(cString: UnsafePointer(str), encoding: .utf8)! } } } } } public func hash(into hasher: inout Hasher) { withUnsafeBytes(of: uuid) { buffer in hasher.combine(bytes: buffer) } } public var description: String { return uuidString } public var debugDescription: String { return description } // MARK: - Bridging Support private var reference: NSUUID { return withUnsafePointer(to: uuid) { $0.withMemoryRebound(to: UInt8.self, capacity: 16) { return NSUUID(uuidBytes: $0) } } } public static func ==(lhs: UUID, rhs: UUID) -> Bool { return withUnsafeBytes(of: rhs.uuid) { (rhsPtr) -> Bool in return withUnsafeBytes(of: lhs.uuid) { (lhsPtr) -> Bool in let lhsFirstChunk = lhsPtr.load(fromByteOffset: 0, as: UInt64.self) let lhsSecondChunk = lhsPtr.load(fromByteOffset: MemoryLayout<UInt64>.size, as: UInt64.self) let rhsFirstChunk = rhsPtr.load(fromByteOffset: 0, as: UInt64.self) let rhsSecondChunk = rhsPtr.load(fromByteOffset: MemoryLayout<UInt64>.size, as: UInt64.self) return ((lhsFirstChunk ^ rhsFirstChunk) | (lhsSecondChunk ^ rhsSecondChunk)) == 0 } } } } extension UUID : CustomReflectable { public var customMirror: Mirror { let c : [(label: String?, value: Any)] = [] let m = Mirror(self, children:c, displayStyle: Mirror.DisplayStyle.struct) return m } } extension UUID : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSUUID { return reference } public static func _forceBridgeFromObjectiveC(_ x: NSUUID, result: inout UUID?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSUUID, result: inout UUID?) -> Bool { result = UUID(reference: input) return true } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: NSUUID?) -> UUID { var result: UUID? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension NSUUID : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as UUID) } } extension UUID : Codable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let uuidString = try container.decode(String.self) guard let uuid = UUID(uuidString: uuidString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Attempted to decode UUID from invalid UUID string.")) } self = uuid } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.uuidString) } }
apache-2.0
bd579b4c9dece89ac8937d7aebe92eb2
34.959302
146
0.583508
4.349508
false
false
false
false
nathawes/swift
stdlib/public/Darwin/Foundation/NSObject.swift
9
16748
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2017 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import ObjectiveC @_implementationOnly import _SwiftFoundationOverlayShims // This exists to allow for dynamic dispatch on KVO methods added to NSObject. // Extending NSObject with these methods would disallow overrides. public protocol _KeyValueCodingAndObserving {} extension NSObject : _KeyValueCodingAndObserving {} public struct NSKeyValueObservedChange<Value> { public typealias Kind = NSKeyValueChange public let kind: Kind ///newValue and oldValue will only be non-nil if .new/.old is passed to `observe()`. In general, get the most up to date value by accessing it directly on the observed object instead. public let newValue: Value? public let oldValue: Value? ///indexes will be nil unless the observed KeyPath refers to an ordered to-many property public let indexes: IndexSet? ///'isPrior' will be true if this change observation is being sent before the change happens, due to .prior being passed to `observe()` public let isPrior:Bool } ///Conforming to NSKeyValueObservingCustomization is not required to use Key-Value Observing. Provide an implementation of these functions if you need to disable auto-notifying for a key, or add dependent keys public protocol NSKeyValueObservingCustomization : NSObjectProtocol { static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath> static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool } private extension NSObject { @objc class func __old_unswizzled_automaticallyNotifiesObservers(forKey key: String?) -> Bool { fatalError("Should never be reached") } @objc class func __old_unswizzled_keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> { fatalError("Should never be reached") } } // NOTE: older overlays called this _KVOKeyPathBridgeMachinery. The two // must coexist, so it was renamed. The old name must not be used in the // new runtime. @objc private class __KVOKeyPathBridgeMachinery : NSObject { @nonobjc static let swizzler: () = { /* Move all our methods into place. We want the following: __KVOKeyPathBridgeMachinery's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replaces NSObject's versions of them NSObject's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replace NSObject's __old_unswizzled_* methods NSObject's _old_unswizzled_* methods replace __KVOKeyPathBridgeMachinery's methods, and are never invoked */ threeWaySwizzle(#selector(NSObject.keyPathsForValuesAffectingValue(forKey:)), with: #selector(NSObject.__old_unswizzled_keyPathsForValuesAffectingValue(forKey:))) threeWaySwizzle(#selector(NSObject.automaticallyNotifiesObservers(forKey:)), with: #selector(NSObject.__old_unswizzled_automaticallyNotifiesObservers(forKey:))) }() /// Performs a 3-way swizzle between `NSObject` and `__KVOKeyPathBridgeMachinery`. /// /// The end result of this swizzle is the following: /// * `NSObject.selector` contains the IMP from `__KVOKeyPathBridgeMachinery.selector` /// * `NSObject.unswizzledSelector` contains the IMP from the original `NSObject.selector`. /// * __KVOKeyPathBridgeMachinery.selector` contains the (useless) IMP from `NSObject.unswizzledSelector`. /// /// This swizzle is done in a manner that modifies `NSObject.selector` last, in order to ensure thread safety /// (by the time `NSObject.selector` is swizzled, `NSObject.unswizzledSelector` will contain the original IMP) @nonobjc private static func threeWaySwizzle(_ selector: Selector, with unswizzledSelector: Selector) { let rootClass: AnyClass = NSObject.self let bridgeClass: AnyClass = __KVOKeyPathBridgeMachinery.self // Swap bridge.selector <-> NSObject.unswizzledSelector let unswizzledMethod = class_getClassMethod(rootClass, unswizzledSelector)! let bridgeMethod = class_getClassMethod(bridgeClass, selector)! method_exchangeImplementations(unswizzledMethod, bridgeMethod) // Swap NSObject.selector <-> NSObject.unswizzledSelector // NSObject.unswizzledSelector at this point contains the bridge IMP let rootMethod = class_getClassMethod(rootClass, selector)! method_exchangeImplementations(rootMethod, unswizzledMethod) } private class BridgeKey : NSObject, NSCopying { let value: String init(_ value: String) { self.value = value } func copy(with zone: NSZone? = nil) -> Any { return self } override func isEqual(_ object: Any?) -> Bool { return value == (object as? BridgeKey)?.value } override var hash: Int { var hasher = Hasher() hasher.combine(ObjectIdentifier(BridgeKey.self)) hasher.combine(value) return hasher.finalize() } } /// Temporarily maps a `String` to an `AnyKeyPath` that can be retrieved with `_bridgeKeyPath(_:)`. /// /// This uses a per-thread storage so key paths on other threads don't interfere. @nonobjc static func _withBridgeableKeyPath(from keyPathString: String, to keyPath: AnyKeyPath, block: () -> Void) { _ = __KVOKeyPathBridgeMachinery.swizzler let key = BridgeKey(keyPathString) let oldValue = Thread.current.threadDictionary[key] Thread.current.threadDictionary[key] = keyPath defer { Thread.current.threadDictionary[key] = oldValue } block() } @nonobjc static func _bridgeKeyPath(_ keyPath:String?) -> AnyKeyPath? { guard let keyPath = keyPath else { return nil } return Thread.current.threadDictionary[BridgeKey(keyPath)] as? AnyKeyPath } @objc override class func automaticallyNotifiesObservers(forKey key: String) -> Bool { //This is swizzled so that it's -[NSObject automaticallyNotifiesObserversForKey:] if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = __KVOKeyPathBridgeMachinery._bridgeKeyPath(key) { return customizingSelf.automaticallyNotifiesObservers(for: path) } else { return self.__old_unswizzled_automaticallyNotifiesObservers(forKey: key) //swizzled to be NSObject's original implementation } } @objc override class func keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> { //This is swizzled so that it's -[NSObject keyPathsForValuesAffectingValueForKey:] if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = __KVOKeyPathBridgeMachinery._bridgeKeyPath(key!) { let resultSet = customizingSelf.keyPathsAffectingValue(for: path) return Set(resultSet.lazy.map { guard let str = $0._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \($0)") } return str }) } else { return self.__old_unswizzled_keyPathsForValuesAffectingValue(forKey: key) //swizzled to be NSObject's original implementation } } } func _bridgeKeyPathToString(_ keyPath:AnyKeyPath) -> String { guard let keyPathString = keyPath._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \(keyPath)") } return keyPathString } // NOTE: older overlays called this NSKeyValueObservation. We now use // that name in the source code, but add an underscore to the runtime // name to avoid conflicts when both are loaded into the same process. @objc(_NSKeyValueObservation) public class NSKeyValueObservation : NSObject { // We use a private helper class as the actual observer. This lets us attach the helper as an associated object // to the object we're observing, thus ensuring the helper will still be alive whenever a KVO change notification // is broadcast, even on a background thread. // // For the associated object, we use the Helper instance itself as its own key. This guarantees key uniqueness. private class Helper : NSObject { @nonobjc weak var object : NSObject? @nonobjc let path: String @nonobjc let callback : (NSObject, NSKeyValueObservedChange<Any>) -> Void // workaround for <rdar://problem/31640524> Erroneous (?) error when using bridging in the Foundation overlay // specifically, overriding observeValue(forKeyPath:of:change:context:) complains that it's not Obj-C-compatible @nonobjc static let swizzler: () = { let cls = NSClassFromString("_NSKVOCompatibility") as? _NSKVOCompatibilityShim.Type cls?._noteProcessHasUsedKVOSwiftOverlay() let bridgeClass: AnyClass = Helper.self let observeSel = #selector(NSObject.observeValue(forKeyPath:of:change:context:)) let swapSel = #selector(Helper._swizzle_me_observeValue(forKeyPath:of:change:context:)) let swapObserveMethod = class_getInstanceMethod(bridgeClass, swapSel)! class_addMethod(bridgeClass, observeSel, method_getImplementation(swapObserveMethod), method_getTypeEncoding(swapObserveMethod)) }() @nonobjc init(object: NSObject, keyPath: AnyKeyPath, options: NSKeyValueObservingOptions, callback: @escaping (NSObject, NSKeyValueObservedChange<Any>) -> Void) { _ = Helper.swizzler let path = _bridgeKeyPathToString(keyPath) self.object = object self.path = path self.callback = callback super.init() objc_setAssociatedObject(object, associationKey(), self, .OBJC_ASSOCIATION_RETAIN) __KVOKeyPathBridgeMachinery._withBridgeableKeyPath(from: path, to: keyPath) { object.addObserver(self, forKeyPath: path, options: options, context: nil) } } @nonobjc func invalidate() { guard let object = self.object else { return } object.removeObserver(self, forKeyPath: path, context: nil) objc_setAssociatedObject(object, associationKey(), nil, .OBJC_ASSOCIATION_ASSIGN) self.object = nil } @nonobjc private func associationKey() -> UnsafeRawPointer { return UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()) } @objc private func _swizzle_me_observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSString : Any]?, context: UnsafeMutableRawPointer?) { guard let object = object as? NSObject, object === self.object, let change = change else { return } let rawKind:UInt = change[NSKeyValueChangeKey.kindKey.rawValue as NSString] as! UInt let kind = NSKeyValueChange(rawValue: rawKind)! let notification = NSKeyValueObservedChange(kind: kind, newValue: change[NSKeyValueChangeKey.newKey.rawValue as NSString], oldValue: change[NSKeyValueChangeKey.oldKey.rawValue as NSString], indexes: change[NSKeyValueChangeKey.indexesKey.rawValue as NSString] as! IndexSet?, isPrior: change[NSKeyValueChangeKey.notificationIsPriorKey.rawValue as NSString] as? Bool ?? false) callback(object, notification) } } @nonobjc private let helper: Helper fileprivate init(object: NSObject, keyPath: AnyKeyPath, options: NSKeyValueObservingOptions, callback: @escaping (NSObject, NSKeyValueObservedChange<Any>) -> Void) { helper = Helper(object: object, keyPath: keyPath, options: options, callback: callback) } ///invalidate() will be called automatically when an NSKeyValueObservation is deinited @objc public func invalidate() { helper.invalidate() } deinit { invalidate() } } // Used for type-erase Optional type private protocol _OptionalForKVO { static func _castForKVO(_ value: Any) -> Any? } extension Optional: _OptionalForKVO { static func _castForKVO(_ value: Any) -> Any? { return value as? Wrapped } } extension _KeyValueCodingAndObserving { ///when the returned NSKeyValueObservation is deinited or invalidated, it will stop observing public func observe<Value>( _ keyPath: KeyPath<Self, Value>, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void) -> NSKeyValueObservation { return NSKeyValueObservation(object: self as! NSObject, keyPath: keyPath, options: options) { (obj, change) in let converter = { (changeValue: Any?) -> Value? in if let optionalType = Value.self as? _OptionalForKVO.Type { // Special logic for keyPath having a optional target value. When the keyPath referencing a nil value, the newValue/oldValue should be in the form .some(nil) instead of .none // Solve https://bugs.swift.org/browse/SR-6066 // NSNull is used by KVO to signal that the keyPath value is nil. // If Value == Optional<T>.self, We will get nil instead of .some(nil) when casting Optional(<null>) directly. // To fix this behavior, we will eliminate NSNull first, then cast the transformed value. if let unwrapped = changeValue { // We use _castForKVO to cast first. // If Value != Optional<NSNull>.self, the NSNull value will be eliminated. let nullEliminatedValue = optionalType._castForKVO(unwrapped) as Any let transformedOptional: Any? = nullEliminatedValue return transformedOptional as? Value } } return changeValue as? Value } let notification = NSKeyValueObservedChange(kind: change.kind, newValue: converter(change.newValue), oldValue: converter(change.oldValue), indexes: change.indexes, isPrior: change.isPrior) changeHandler(obj as! Self, notification) } } public func willChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>) { (self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath)) } public func willChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: __owned KeyPath<Self, Value>) { (self as! NSObject).willChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath)) } public func willChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void { (self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set) } public func didChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>) { (self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath)) } public func didChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: __owned KeyPath<Self, Value>) { (self as! NSObject).didChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath)) } public func didChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void { (self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set) } }
apache-2.0
24259458f4c206ae9f5341b7057ce193
52.507987
209
0.662527
5.371392
false
false
false
false
giaunv/auth-selfie-swift-rails-iphone
Selfie/HTTPHelper.swift
1
6335
// // HTTPHelper.swift // Selfie // // Created by Subhransu Behera on 18/11/14. // Copyright (c) 2014 subhb.org. All rights reserved. // import Foundation enum HTTPRequestAuthType { case HTTPBasicAuth case HTTPTokenAuth } enum HTTPRequestContentType { case HTTPJsonContent case HTTPMultipartContent } struct HTTPHelper { static let API_AUTH_NAME = "xcode366" static let API_AUTH_PASSWORD = "123" static let BASE_URL = "https://blooming-hollows-5882.herokuapp.com/api" func buildRequest(path: String!, method: String, authType: HTTPRequestAuthType, requestContentType: HTTPRequestContentType = HTTPRequestContentType.HTTPJsonContent, requestBoundary:NSString = "") -> NSMutableURLRequest { // 1. Create the request URL from path let requestURL = NSURL(string: "\(HTTPHelper.BASE_URL)/\(path)") var request = NSMutableURLRequest(URL: requestURL!) // Set HTTP request method and Content-Type request.HTTPMethod = method // 2. Set the correct Content-Type for the HTTP Request. This will be multipart/form-data for photo upload request and application/json for other requests in this app switch requestContentType { case .HTTPJsonContent: request.addValue("application/json", forHTTPHeaderField: "Content-Type") case .HTTPMultipartContent: let contentType = NSString(format: "multipart/form-data; boundary=%@", requestBoundary) request.addValue(contentType, forHTTPHeaderField: "Content-Type") } // 3. Set the correct Authorization header. switch authType { case .HTTPBasicAuth: // Set BASIC authentication header let basicAuthString = "\(HTTPHelper.API_AUTH_NAME):\(HTTPHelper.API_AUTH_PASSWORD)" let utf8str = basicAuthString.dataUsingEncoding(NSUTF8StringEncoding) let base64EncodedString = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0)) request.addValue("Basic \(base64EncodedString!)", forHTTPHeaderField: "Authorization") case .HTTPTokenAuth: // Retreieve Auth_Token from Keychain let userToken : NSString? = KeychainAccess.passwordForAccount("Auth_Token", service: "KeyChainService") // Set Authorization header request.addValue("Token token=\(userToken!)", forHTTPHeaderField: "Authorization") } return request } func sendRequest(request: NSURLRequest, completion:(NSData!, NSError!) -> Void) -> () { // Create a NSURLSession task let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in if error != nil { dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(data, error) }) return } dispatch_async(dispatch_get_main_queue(), { () -> Void in let httpResponse = response as NSHTTPURLResponse if httpResponse.statusCode == 200 { completion(data, nil) } else { var jsonerror:NSError? let errorDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:&jsonerror) as NSDictionary let responseError : NSError = NSError(domain: "HTTPHelperError", code: httpResponse.statusCode, userInfo: errorDict) completion(data, responseError) } }) } // start the task task.resume() } func uploadRequest(path: String, data: NSData, title: NSString) -> NSMutableURLRequest { let boundary : NSString = "---------------------------14737809831466499882746641449" var request = buildRequest(path, method: "POST", authType: HTTPRequestAuthType.HTTPTokenAuth, requestContentType:HTTPRequestContentType.HTTPMultipartContent, requestBoundary:boundary) as NSMutableURLRequest let bodyParams : NSMutableData = NSMutableData() // build and format HTTP body with data // prepare for multipart form uplaod let boundaryString = NSString(format: "--%@\r\n",boundary) let boundaryData = boundaryString.dataUsingEncoding(NSUTF8StringEncoding) as NSData! bodyParams.appendData(boundaryData) // set the parameter name let imageMeteData = "Content-Disposition: attachment; name=\"image\"; filename=\"photo\"\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) bodyParams.appendData(imageMeteData!) // set the content type let fileContentType = "Content-Type: application/octet-stream\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) bodyParams.appendData(fileContentType!) // add the actual image data bodyParams.appendData(data) let imageDataEnding = "\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) bodyParams.appendData(imageDataEnding!) let boundaryString2 = NSString(format: "--%@\r\n",boundary) let boundaryData2 = boundaryString.dataUsingEncoding(NSUTF8StringEncoding) as NSData! bodyParams.appendData(boundaryData2) // pass the caption of the image let formData = "Content-Disposition: form-data; name=\"title\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) bodyParams.appendData(formData!) let formData2 = title.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) bodyParams.appendData(formData2!) let closingFormData = "\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) bodyParams.appendData(closingFormData!) let closingData = NSString(format: "--%@--\r\n",boundary) let boundaryDataEnd = closingData.dataUsingEncoding(NSUTF8StringEncoding) as NSData! bodyParams.appendData(boundaryDataEnd) request.HTTPBody = bodyParams return request } func getErrorMessage(error: NSError) -> NSString { var errorMessage : NSString // return correct error message if error.domain == "HTTPHelperError" { let userInfo = error.userInfo as NSDictionary! errorMessage = userInfo.valueForKey("message") as NSString } else { errorMessage = error.description } return errorMessage } }
mit
32853bf6288e34011632f64db4f176cb
38.347826
172
0.698343
4.9223
false
false
false
false
swixbase/filesystem
Sources/Filesystem/FileSystemObjectType.swift
1
1221
/// Copyright 2017 Sergei Egorov /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. import Foundation public enum FileSystemObjectType: String { /// The object is a directory. case directory = "typeDirectory" /// The object is a regular file. case regular = "typeRegular" /// The object is a symbolic link. case symbolicLink = "typeSymbolicLink" /// The object is a socket. case socket = "typeSocket" /// The object is a characer special file. case characterSpecial = "typeCharacterSpecial" /// The object is a block special file. case blockSpecial = "typeBlockSpecial" /// The type of the object is unknown. case unknown = "typeUnknown" }
apache-2.0
d35748cb2604a2265c26f6eebaec3e83
29.525
76
0.703522
4.488971
false
false
false
false
ibm-cloud-security/appid-clientsdk-swift
Source/IBMCloudAppID/api/AppIDAuthorizationManager.swift
1
7797
/* * Copyright 2016, 2017 IBM Corp. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import BMSCore public class AppIDAuthorizationManager: BMSCore.AuthorizationManager { internal var oAuthManager:OAuthManager private static let logger = Logger.logger(name: Logger.bmsLoggerPrefix + "AppIDAuthorizationManager") /** Intializes the App ID Authorization Manager @param appid An AppID instance */ public init(appid:AppID) { self.oAuthManager = appid.oauthManager! } /** A response is an OAuth error response only if, 1. it's status is 401 or 403. 2. The value of the "WWW-Authenticate" header contains 'Bearer'. - Parameter httpResponse - Response to check the authorization conditions for. - returns: True if the response satisfies both conditions */ public func isAuthorizationRequired(for httpResponse: Response) -> Bool { AppIDAuthorizationManager.logger.debug(message: "isAuthorizationRequired") return AuthorizationHeaderHelper.isAuthorizationRequired(for: httpResponse) } /** Check if the params came from response that requires authorization - Parameter statusCode - Status code of the response - Parameter responseAuthorizationHeader - Response header - returns: True if status is 401 or 403 and The value of the header contains 'Bearer' */ public func isAuthorizationRequired(for statusCode: Int, httpResponseAuthorizationHeader responseAuthorizationHeader: String) -> Bool { return AuthorizationHeaderHelper.isAuthorizationRequired(statusCode: statusCode, header: responseAuthorizationHeader) } public func obtainAuthorization(completionHandler callback: BMSCompletionHandler?) { AppIDAuthorizationManager.logger.debug(message: "obtainAuthorization") class innerTokenDelegate: TokenResponseDelegate { var callback:(Response?, AuthorizationError?) -> Void init(_ callback: @escaping (Response?, AuthorizationError?) -> Void) { self.callback = callback } func onAuthorizationFailure(error: AuthorizationError) { self.callback(nil, error) } func onAuthorizationSuccess(accessToken: AccessToken?, identityToken: IdentityToken?, refreshToken: RefreshToken?, response: Response?) { self.callback(response, nil) } } let refreshToken = self.oAuthManager.tokenManager?.latestRefreshToken if refreshToken != nil { self.oAuthManager.tokenManager?.obtainTokensRefreshToken( refreshTokenString: refreshToken!.raw!, tokenResponseDelegate: innerTokenDelegate { (response, authorizationError) in if response != nil { callback?(response, nil) } else { self.launchAuthorization(callback) } }) } else { self.launchAuthorization(callback) } } public func launchAuthorization(_ callback: BMSCompletionHandler?) { class innerAuthorizationDelegate: AuthorizationDelegate { var callback:BMSCompletionHandler? init(callback:BMSCompletionHandler?) { self.callback = callback } func onAuthorizationFailure(error err:AuthorizationError) { callback?(nil,err) } func onAuthorizationCanceled () { callback?(nil, AuthorizationError.authorizationFailure("Authorization canceled")) } func onAuthorizationSuccess (accessToken:AccessToken?, identityToken:IdentityToken?, refreshToken: RefreshToken?, response:Response?) { callback?(response,nil) } } oAuthManager.authorizationManager?.launchAuthorizationUI(authorizationDelegate: innerAuthorizationDelegate(callback: callback)) } public func clearAuthorizationData() { AppIDAuthorizationManager.logger.debug(message: "clearAuthorizationData") self.oAuthManager.tokenManager?.notifyLogout(); self.oAuthManager.tokenManager?.clearStoredToken() } /** - returns: The locally stored authorization header or nil if the value does not exist. */ public var cachedAuthorizationHeader:String? { get { AppIDAuthorizationManager.logger.debug(message: "getCachedAuthorizationHeader") guard let accessToken = self.accessToken, let identityToken = self.identityToken else { return nil } return "Bearer " + accessToken.raw + " " + identityToken.raw } } /** Returns the UserIdentity object constructed from the Identity Token if there is one */ public var userIdentity:UserIdentity? { let idToken = self.identityToken let identity:[String:Any] = [ BaseUserIdentity.Key.authorizedBy : idToken?.authenticationMethods ?? "", BaseUserIdentity.Key.displayName : idToken?.name ?? "", BaseUserIdentity.Key.ID : idToken?.subject ?? "" ] return BaseUserIdentity(map: identity) } /** Returns the a DeviceIdentity object */ public var deviceIdentity:DeviceIdentity { return BaseDeviceIdentity() } /** Returns the an AppIdentity object */ public var appIdentity:AppIdentity { return BaseAppIdentity() } /** Returns the latest access token */ public var accessToken:AccessToken? { return self.oAuthManager.tokenManager?.latestAccessToken } /** Returns the latest identity token */ public var identityToken:IdentityToken? { return self.oAuthManager.tokenManager?.latestIdentityToken } /** Adds the cached authorization header to the given URL connection object. If the cached authorization header is equal to nil then this operation has no effect. - Parameter request - The request to add the header to. */ public func addCachedAuthorizationHeader(_ request: NSMutableURLRequest) { AppIDAuthorizationManager.logger.debug(message: "addCachedAuthorizationHeader") addAuthorizationHeader(request, header: cachedAuthorizationHeader) } private func addAuthorizationHeader(_ request: NSMutableURLRequest, header:String?) { AppIDAuthorizationManager.logger.debug(message: "addAuthorizationHeader") guard let unWrappedHeader = header else { return } request.setValue(unWrappedHeader, forHTTPHeaderField: AppIDConstants.AUTHORIZATION_HEADER) } /** Removes saved tokens */ public func logout() { self.oAuthManager.tokenManager?.notifyLogout(); self.clearAuthorizationData() } }
apache-2.0
e0adce66e7d9c06d708742f5663c9cf3
35.265116
149
0.638579
5.956455
false
false
false
false
dipen30/Qmote
KodiRemote/Pods/UPnAtom/Source/AV Profile/Services/ConnectionManager1Service.swift
1
6948
// // ConnectionManager1Service.swift // // Copyright (c) 2015 David Robles // // 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 open class ConnectionManager1Service: AbstractUPnPService { open func getProtocolInfo(_ success: @escaping (_ source: [String], _ sink: [String]) -> Void, failure: @escaping (_ error: NSError) -> Void) { let parameters = SOAPRequestSerializer.Parameters(soapAction: "GetProtocolInfo", serviceURN: urn, arguments: nil) soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in let responseObject = responseObject as? [String: String] success(responseObject?["Source"]?.components(separatedBy: ",") ?? [String](), responseObject?["Sink"]?.components(separatedBy: ",") ?? [String]()) }, failure: {(task, error) in } ) } open func prepareForConnection(remoteProtocolInfo: String, peerConnectionManager: String, peerConnectionID: String, direction: String, success: @escaping (_ connectionID: String?, _ avTransportID: String?, _ renderingControlServiceID: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { let arguments = [ "RemoteProtocolInfo" : remoteProtocolInfo, "PeerConnectionManager" : peerConnectionManager, "PeerConnectionID" : peerConnectionID, "Direction" : direction] let parameters = SOAPRequestSerializer.Parameters(soapAction: "PrepareForConnection", serviceURN: urn, arguments: arguments as! NSDictionary) // Check if the optional SOAP action "PrepareForConnection" is supported supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in if isSupported { self.soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in let responseObject = responseObject as? [String: String] success(responseObject?["ConnectionID"], responseObject?["AVTransportID"], responseObject?["RcsID"]) }, failure: {(task, error) in } ) } else { failure(createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)")) } } } open func connectionComplete(connectionID: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { let arguments = ["ConnectionID" : connectionID] let parameters = SOAPRequestSerializer.Parameters(soapAction: "ConnectionComplete", serviceURN: urn, arguments: arguments as! NSDictionary) // Check if the optional SOAP action "ConnectionComplete" is supported supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in if isSupported { self.soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in success() }, failure: {(task, error) in } ) } else { failure(createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)")) } } } open func getCurrentConnectionIDs(_ success: @escaping (_ connectionIDs: [String]) -> Void, failure: @escaping (_ error: NSError) -> Void) { let parameters = SOAPRequestSerializer.Parameters(soapAction: "GetCurrentConnectionIDs", serviceURN: urn, arguments: nil) soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in let responseObject = responseObject as? [String: String] success(responseObject?["ConnectionIDs"]?.components(separatedBy: ",") ?? [String]()) }, failure: {(task, error) in } ) } open func getCurrentConnectionInfo(connectionID: String, success: @escaping (_ renderingControlServiceID: String?, _ avTransportID: String?, _ protocolInfo: String?, _ peerConnectionManager: String?, _ peerConnectionID: String?, _ direction: String?, _ status: String?) -> Void, failure: @escaping (_ error: NSError) -> Void) { let arguments = ["ConnectionID" : connectionID] let parameters = SOAPRequestSerializer.Parameters(soapAction: "GetCurrentConnectionInfo", serviceURN: urn, arguments: arguments as! NSDictionary) soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in let responseObject = responseObject as? [String: String] success(responseObject?["RcsID"], responseObject?["AVTransportID"], responseObject?["ProtocolInfo"], responseObject?["PeerConnectionManager"], responseObject?["PeerConnectionID"], responseObject?["Direction"], responseObject?["Status"]) }, failure: {(task, error) in } ) } } /// for objective-c type checking extension AbstractUPnP { public func isConnectionManager1Service() -> Bool { return self is ConnectionManager1Service } } /// overrides ExtendedPrintable protocol implementation extension ConnectionManager1Service { override public var className: String { return "\(type(of: self))" } override open var description: String { var properties = PropertyPrinter() properties.add(super.className, property: super.description) return properties.description } }
apache-2.0
17cd9083855f569f58c810b20f9b6671
56.421488
331
0.673431
5.127675
false
false
false
false
lukejmann/FBLA2017
Pods/Instructions/Sources/Controllers/CoachMarksViewController.swift
1
12771
// CoachMarksViewController.swift // // Copyright (c) 2015, 2016 Frédéric Maquin <[email protected]>, // Daniel Basedow <[email protected]>, // Esteban Soto <[email protected]>, // Ogan Topkaya <> // // 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 // MARK: - Main Class /// Handles a set of coach marks, and display them successively. class CoachMarksViewController: UIViewController { // MARK: - Internal properties /// Control or control wrapper used to skip the flow. var skipView: CoachMarkSkipView? { willSet { if newValue == nil { self.skipView?.asView?.removeFromSuperview() self.skipView?.skipControl?.removeTarget(self, action: #selector(skipCoachMarksTour(_:)), for: .touchUpInside) } } didSet { guard let skipView = skipView else { return } guard skipView is UIView else { fatalError("skipView must conform to CoachMarkBodyView but also be a UIView.") } addSkipView() } } /// var currentCoachMarkView: CoachMarkView? /// var overlayView: OverlayView! /// var instructionsRootView: InstructionsRootView! /// var coachMarkDisplayManager: CoachMarkDisplayManager! /// var skipViewDisplayManager: SkipViewDisplayManager! /// weak var delegate: CoachMarksViewControllerDelegate? // MARK: - Private properties fileprivate var onGoingSizeChange = false fileprivate let mainViewsLayoutHelper = MainViewsLayoutHelper() // MARK: - Lifecycle convenience init(coachMarkDisplayManager: CoachMarkDisplayManager, skipViewDisplayManager: SkipViewDisplayManager) { self.init() self.coachMarkDisplayManager = coachMarkDisplayManager self.skipViewDisplayManager = skipViewDisplayManager } override func loadView() { view = DummyView(frame: UIScreen.main.bounds) view.translatesAutoresizingMaskIntoConstraints = false } // Called after the view was loaded. override func viewDidLoad() { super.viewDidLoad() } deinit { unregisterFromStatusBarFrameChanges() } // MARK: - Private Methods fileprivate func addOverlayView() { instructionsRootView.addSubview(overlayView) let constraints = mainViewsLayoutHelper.fullSizeConstraints(for: overlayView) instructionsRootView.addConstraints(constraints) overlayView.alpha = 0.0 } fileprivate func addRootView(to window: UIWindow) { window.addSubview(instructionsRootView) let constraints = mainViewsLayoutHelper.fullSizeConstraints(for: instructionsRootView) window.addConstraints(constraints) instructionsRootView.backgroundColor = UIColor.clear } /// Add a the "Skip view" to the main view container. fileprivate func addSkipView() { guard let skipView = skipView else { return } skipView.asView?.alpha = 0.0 skipView.skipControl?.addTarget(self, action: #selector(skipCoachMarksTour(_:)), for: .touchUpInside) instructionsRootView.addSubview(skipView.asView!) } } // MARK: - Coach Mark Display extension CoachMarksViewController { // MARK: - Internal Methods func prepareToShowCoachMarks(_ completion: @escaping () -> Void) { disableInteraction() overlayView.prepareForFade() if let skipView = skipView { self.skipViewDisplayManager.show(skipView: skipView, duration: overlayView.fadeAnimationDuration) } UIView.animate(withDuration: overlayView.fadeAnimationDuration, animations: { () -> Void in self.overlayView.alpha = 1.0 }, completion: { (_: Bool) -> Void in self.enableInteraction() completion() }) } func hide(coachMark: CoachMark, animated: Bool = true, completion: (() -> Void)? = nil) { guard let currentCoachMarkView = currentCoachMarkView else { completion?() return } disableInteraction() let duration: TimeInterval if animated { duration = coachMark.animationDuration } else { duration = 0 } self.coachMarkDisplayManager.hide(coachMarkView: currentCoachMarkView, overlayView: overlayView, animationDuration: duration) { self.enableInteraction() self.removeTargetFromCurrentCoachView() completion?() } } func show(coachMark: inout CoachMark, at index: Int, animated: Bool = true, completion: (() -> Void)? = nil) { disableInteraction() coachMark.computeMetadata(inFrame: instructionsRootView.frame) let passthrough = coachMark.allowTouchInsideCutoutPath let coachMarkView = coachMarkDisplayManager.createCoachMarkView(from: coachMark, at: index) currentCoachMarkView = coachMarkView addTargetToCurrentCoachView() coachMarkDisplayManager.showNew(coachMarkView: coachMarkView, from: coachMark, on: overlayView!, animated: animated) { self.instructionsRootView.passthrough = passthrough self.enableInteraction() completion?() } } // MARK: - Private Methods private func disableInteraction() { instructionsRootView.passthrough = false instructionsRootView.isUserInteractionEnabled = true overlayView.isUserInteractionEnabled = false currentCoachMarkView?.isUserInteractionEnabled = false skipView?.asView?.isUserInteractionEnabled = false } private func enableInteraction() { instructionsRootView.isUserInteractionEnabled = true overlayView.isUserInteractionEnabled = true currentCoachMarkView?.isUserInteractionEnabled = true skipView?.asView?.isUserInteractionEnabled = true } } // MARK: - Change Events extension CoachMarksViewController { // MARK: - Overrides override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if currentCoachMarkView == nil { return } if onGoingSizeChange { return } onGoingSizeChange = true overlayView.update(cutoutPath: nil) delegate?.willTransition() super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil, completion: { (_: UIViewControllerTransitionCoordinatorContext) -> Void in self.onGoingSizeChange = false self.delegate?.didTransition() }) } // MARK: - Internal Methods /// Will remove currently displayed coach mark. func prepareForSizeTransition() { guard let skipView = skipView else { return } skipViewDisplayManager?.hide(skipView: skipView) } /// Will re-add the current coach mark func restoreAfterSizeTransitionDidComplete() { guard let skipView = skipView else { return } skipViewDisplayManager?.show(skipView: skipView) } // MARK: - Private methods fileprivate func registerForStatusBarFrameChanges() { let center = NotificationCenter.default center.addObserver(self, selector: #selector(prepareForStatusBarChange), name: .UIApplicationWillChangeStatusBarFrame, object: nil) center.addObserver(self, selector: #selector(restoreAfterStatusBarChangeDidComplete), name: .UIApplicationDidChangeStatusBarFrame, object: nil) } fileprivate func unregisterFromStatusBarFrameChanges() { NotificationCenter.default.removeObserver(self) } /// Same as `prepareForSizeTransition`, but for status bar changes. @objc fileprivate func prepareForStatusBarChange() { if !onGoingSizeChange { prepareForSizeTransition() } } /// Same as `restoreAfterSizeTransitionDidComplete`, but for status bar changes. @objc fileprivate func restoreAfterStatusBarChangeDidComplete() { if !onGoingSizeChange { prepareForSizeTransition() restoreAfterSizeTransitionDidComplete() } } } // MARK: - Extension: Controller Containment extension CoachMarksViewController { /// Will attach the controller as a child of the given view controller. This will /// allow the coach mark controller to respond to size changes, though /// `instructionsRootView` will be a subview of `UIWindow`. /// /// - Parameter parentViewController: the controller of which become a child func attachTo(_ parentViewController: UIViewController) { guard let window = parentViewController.view?.window else { print("attachToViewController: Instructions could not be properly" + "attached to the window, did you call `startOn` inside" + "`viewDidLoad` instead of `ViewDidAppear`?") return } registerForStatusBarFrameChanges() parentViewController.addChildViewController(self) parentViewController.view.addSubview(self.view) addRootView(to: window) addOverlayView() // If we're in the background we'll manually lay out the view. // // `instructionsRootView` is not laid out automatically in the // background, likely because it's added to the window. #if !INSTRUCTIONS_APP_EXTENSIONS if UIApplication.shared.applicationState == .background { window.layoutIfNeeded() } #else window.layoutIfNeeded() #endif self.didMove(toParentViewController: parentViewController) } /// Detach the controller from its parent view controller. func detachFromParentViewController() { self.instructionsRootView.removeFromSuperview() self.willMove(toParentViewController: nil) self.view.removeFromSuperview() self.removeFromParentViewController() unregisterFromStatusBarFrameChanges() } } // MARK: - Private Extension: User Events private extension CoachMarksViewController { /// Add touch up target to the current coach mark view. func addTargetToCurrentCoachView() { currentCoachMarkView?.nextControl?.addTarget(self, action: #selector(didTapCoachMark(_:)), for: .touchUpInside) } /// Remove touch up target from the current coach mark view. func removeTargetFromCurrentCoachView() { currentCoachMarkView?.nextControl?.removeTarget(self, action: #selector(didTapCoachMark(_:)), for: .touchUpInside) } /// Will be called when the user perform an action requiring the display of the next coach mark. /// /// - Parameter sender: the object sending the message @objc func didTapCoachMark(_ sender: AnyObject?) { delegate?.didTap(coachMarkView: currentCoachMarkView) } /// Will be called when the user choose to skip the coach mark tour. /// /// - Parameter sender: the object sending the message @objc func skipCoachMarksTour(_ sender: AnyObject?) { delegate?.didTap(skipView: skipView) } }
mit
13402ed499ad107b3c18f0ee81ed5d63
35.378917
100
0.652361
5.788305
false
false
false
false
ncalexan/firefox-ios
Client/Frontend/Settings/AppSettingsTableViewController.swift
1
8893
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import Account /// App Settings Screen (triggered by tapping the 'Gear' in the Tab Tray Controller) class AppSettingsTableViewController: SettingsTableViewController { fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier" override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Settings", comment: "Settings") navigationItem.leftBarButtonItem = UIBarButtonItem( title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"), style: UIBarButtonItemStyle.done, target: navigationController, action: #selector((navigationController as! SettingsNavigationController).SELdone)) navigationItem.leftBarButtonItem?.accessibilityIdentifier = "AppSettingsTableViewController.navigationItem.leftBarButtonItem" tableView.accessibilityIdentifier = "AppSettingsTableViewController.tableView" // Refresh the user's FxA profile upon viewing settings. This will update their avatar, // display name, etc. if AppConstants.MOZ_SHOW_FXA_AVATAR { profile.getAccount()?.updateProfile() } } override func generateSettings() -> [SettingSection] { var settings = [SettingSection]() let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title") let accountDebugSettings = [ // Debug settings: RequirePasswordDebugSetting(settings: self), RequireUpgradeDebugSetting(settings: self), ForgetSyncAuthStateDebugSetting(settings: self), StageSyncServiceDebugSetting(settings: self), ] let prefs = profile.prefs var generalSettings: [Setting] = [ SearchSetting(settings: self), NewTabPageSetting(settings: self), HomePageSetting(settings: self), OpenWithSetting(settings: self), BoolSetting(prefs: prefs, prefKey: "blockPopups", defaultValue: true, titleText: NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")), BoolSetting(prefs: prefs, prefKey: "saveLogins", defaultValue: true, titleText: NSLocalizedString("Save Logins", comment: "Setting to enable the built-in password manager")), ] let accountChinaSyncSetting: [Setting] if !profile.isChinaEdition { accountChinaSyncSetting = [] } else { accountChinaSyncSetting = [ // Show China sync service setting: ChinaSyncServiceSetting(settings: self) ] } // There is nothing to show in the Customize section if we don't include the compact tab layout // setting on iPad. When more options are added that work on both device types, this logic can // be changed. if UIDevice.current.userInterfaceIdiom == .phone { generalSettings += [ BoolSetting(prefs: prefs, prefKey: "CompactTabLayout", defaultValue: true, titleText: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview")) ] } generalSettings += [ BoolSetting(prefs: prefs, prefKey: "showClipboardBar", defaultValue: false, titleText: Strings.SettingsOfferClipboardBarTitle, statusText: Strings.SettingsOfferClipboardBarStatus) ] var accountSectionTitle: NSAttributedString? if AppConstants.MOZ_SHOW_FXA_AVATAR { accountSectionTitle = NSAttributedString(string: Strings.FxAFirefoxAccount) } settings += [ SettingSection(title: accountSectionTitle, children: [ // Without a Firefox Account: ConnectSetting(settings: self), AdvanceAccountSetting(settings: self), // With a Firefox Account: AccountStatusSetting(settings: self), SyncNowSetting(settings: self) ] + accountChinaSyncSetting + accountDebugSettings)] if !profile.hasAccount() { settings += [SettingSection(title: NSAttributedString(string: Strings.FxASyncUsageDetails), children: [])] } settings += [ SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings)] var privacySettings = [Setting]() privacySettings.append(LoginsSetting(settings: self, delegate: settingsDelegate)) privacySettings.append(TouchIDPasscodeSetting(settings: self)) privacySettings.append(ClearPrivateDataSetting(settings: self)) privacySettings += [ BoolSetting(prefs: prefs, prefKey: "settings.closePrivateTabs", defaultValue: false, titleText: NSLocalizedString("Close Private Tabs", tableName: "PrivateBrowsing", comment: "Setting for closing private tabs"), statusText: NSLocalizedString("When Leaving Private Browsing", tableName: "PrivateBrowsing", comment: "Will be displayed in Settings under 'Close Private Tabs'")) ] if #available(iOS 11, *) { privacySettings.append(ContentBlockerSetting(settings:self)) } privacySettings += [ PrivacyPolicySetting() ] settings += [ SettingSection(title: NSAttributedString(string: privacyTitle), children: privacySettings), SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [ ShowIntroductionSetting(settings: self), SendFeedbackSetting(), SendAnonymousUsageDataSetting(prefs: prefs, delegate: settingsDelegate), OpenSupportPageSetting(delegate: settingsDelegate), ]), SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [ VersionSetting(settings: self), LicenseAndAcknowledgementsSetting(), YourRightsSetting(), ExportBrowserDataSetting(settings: self), DeleteExportedDataSetting(settings: self), EnableBookmarkMergingSetting(settings: self), ForceCrashSetting(settings: self) ])] if profile.hasAccount() { settings += [SettingSection(title: nil, children: [DisconnectSetting(settings: self)])] } return settings } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if !profile.hasAccount() { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView let sectionSetting = settings[section] headerView.titleLabel.text = sectionSetting.title?.string switch section { // Hide the bottom border for the Sign In to Firefox value prop case 1: headerView.titleAlignment = .top headerView.titleLabel.numberOfLines = 0 headerView.showBottomBorder = false headerView.titleLabel.snp.updateConstraints { make in make.right.equalTo(headerView).offset(-50) } // Hide the top border for the General section header when the user is not signed in. case 2: headerView.showTopBorder = false default: return super.tableView(tableView, viewForHeaderInSection: section) } return headerView } return super.tableView(tableView, viewForHeaderInSection: section) } } extension AppSettingsTableViewController { func navigateToLoginsList() { let viewController = LoginListViewController(profile: profile) viewController.settingsDelegate = settingsDelegate navigationController?.pushViewController(viewController, animated: true) } } extension AppSettingsTableViewController: PasscodeEntryDelegate { @objc func passcodeValidationDidSucceed() { navigationController?.dismiss(animated: true) { self.navigateToLoginsList() } } }
mpl-2.0
627d15329093e83384cad52cf777adbb
45.07772
178
0.642415
6.258269
false
false
false
false
primatelabs/geekbench-swift
GeekbenchSwift/main.swift
1
1469
// Copyright (c) 2014 Primate Labs Inc. // Use of this source code is governed by the 2-clause BSD license that // can be found in the LICENSE file. import Foundation let workloadFactories = [ {() -> Workload in return MandelbrotWorkload(width: 800, height: 800) }, // {() -> Workload in return SGEMMWorkload(matrixSize: 896, blockSize: 512 / sizeof(Float32)) }, {() -> Workload in return SFFTWorkload(size: 8 * 1024 * 1024, chunkSize: 4096)}, {() -> Workload in return FibonacciWorkload(n: 36)}, ] func printResult(result : WorkloadResult) { print(result.workloadName) for (rate, runtime) in Zip2Sequence(result.rates, result.runtimes) { let rateString = result.workloadUnits.stringFromRate(rate) print(" \(rateString) (\(runtime) seconds)") } let minRate = result.rates.reduce(Double.infinity) { min($0, $1) } let maxRate = result.rates.reduce(0) { max($0, $1) } let avgRate = result.rates.reduce(0) { $0 + $1 } / Double(result.rates.count) let minString = result.workloadUnits.stringFromRate(minRate) let maxString = result.workloadUnits.stringFromRate(maxRate) let avgString = result.workloadUnits.stringFromRate(avgRate) print("") print(" Min rate: \(minString)") print(" Max rate: \(maxString)") print(" Avg rate: \(avgString)") print("") } func main() { for workloadFactory in workloadFactories { let workload = workloadFactory() let result = workload.run() printResult(result) } } main()
bsd-2-clause
ec1a2ade21c2d59db60826d1a88a401a
30.934783
97
0.690946
3.556901
false
false
false
false
brentsimmons/Evergreen
Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift
1
10263
// // TimelineViewController+ContextualMenus.swift // NetNewsWire // // Created by Brent Simmons on 2/9/18. // Copyright © 2018 Ranchero Software. All rights reserved. // import AppKit import RSCore import Articles import Account extension TimelineViewController { func contextualMenuForClickedRows() -> NSMenu? { let row = tableView.clickedRow guard row != -1, let article = articles.articleAtRow(row) else { return nil } if selectedArticles.contains(article) { // If the clickedRow is part of the selected rows, then do a contextual menu for all the selected rows. return menu(for: selectedArticles) } return menu(for: [article]) } } // MARK: Contextual Menu Actions extension TimelineViewController { @objc func markArticlesReadFromContextualMenu(_ sender: Any?) { guard let articles = articles(from: sender) else { return } markArticles(articles, read: true) } @objc func markArticlesUnreadFromContextualMenu(_ sender: Any?) { guard let articles = articles(from: sender) else { return } markArticles(articles, read: false) } @objc func markAboveArticlesReadFromContextualMenu(_ sender: Any?) { guard let articles = articles(from: sender) else { return } markAboveArticlesRead(articles) } @objc func markBelowArticlesReadFromContextualMenu(_ sender: Any?) { guard let articles = articles(from: sender) else { return } markBelowArticlesRead(articles) } @objc func markArticlesStarredFromContextualMenu(_ sender: Any?) { guard let articles = articles(from: sender) else { return } markArticles(articles, starred: true) } @objc func markArticlesUnstarredFromContextualMenu(_ sender: Any?) { guard let articles = articles(from: sender) else { return } markArticles(articles, starred: false) } @objc func selectFeedInSidebarFromContextualMenu(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let webFeed = menuItem.representedObject as? WebFeed else { return } delegate?.timelineRequestedWebFeedSelection(self, webFeed: webFeed) } @objc func markAllInFeedAsRead(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let feedArticles = menuItem.representedObject as? ArticleArray else { return } guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: feedArticles, markingRead: true, undoManager: undoManager) else { return } runCommand(markReadCommand) } @objc func openInBrowserFromContextualMenu(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let urlString = menuItem.representedObject as? String else { return } Browser.open(urlString, inBackground: false) } @objc func copyURLFromContextualMenu(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let urlString = menuItem.representedObject as? String else { return } URLPasteboardWriter.write(urlString: urlString, to: .general) } @objc func performShareServiceFromContextualMenu(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let sharingCommandInfo = menuItem.representedObject as? SharingCommandInfo else { return } sharingCommandInfo.perform() } } private extension TimelineViewController { func markArticles(_ articles: [Article], read: Bool) { markArticles(articles, statusKey: .read, flag: read) } func markArticles(_ articles: [Article], starred: Bool) { markArticles(articles, statusKey: .starred, flag: starred) } func markArticles(_ articles: [Article], statusKey: ArticleStatus.Key, flag: Bool) { guard let undoManager = undoManager, let markStatusCommand = MarkStatusCommand(initialArticles: articles, statusKey: statusKey, flag: flag, undoManager: undoManager) else { return } runCommand(markStatusCommand) } func unreadArticles(from articles: [Article]) -> [Article]? { let filteredArticles = articles.filter { !$0.status.read } return filteredArticles.isEmpty ? nil : filteredArticles } func readArticles(from articles: [Article]) -> [Article]? { let filteredArticles = articles.filter { $0.status.read } return filteredArticles.isEmpty ? nil : filteredArticles } func articles(from sender: Any?) -> [Article]? { return (sender as? NSMenuItem)?.representedObject as? [Article] } func menu(for articles: [Article]) -> NSMenu? { let menu = NSMenu(title: "") if articles.anyArticleIsUnread() { menu.addItem(markReadMenuItem(articles)) } if articles.anyArticleIsReadAndCanMarkUnread() { menu.addItem(markUnreadMenuItem(articles)) } if articles.anyArticleIsUnstarred() { menu.addItem(markStarredMenuItem(articles)) } if articles.anyArticleIsStarred() { menu.addItem(markUnstarredMenuItem(articles)) } if let first = articles.first, self.articles.articlesAbove(article: first).canMarkAllAsRead() { menu.addItem(markAboveReadMenuItem(articles)) } if let last = articles.last, self.articles.articlesBelow(article: last).canMarkAllAsRead() { menu.addItem(markBelowReadMenuItem(articles)) } menu.addSeparatorIfNeeded() if articles.count == 1, let feed = articles.first!.webFeed { if !(representedObjects?.contains(where: { $0 as? WebFeed == feed }) ?? false) { menu.addItem(selectFeedInSidebarMenuItem(feed)) } if let markAllMenuItem = markAllAsReadMenuItem(feed) { menu.addItem(markAllMenuItem) } } if articles.count == 1, let link = articles.first!.preferredLink { menu.addSeparatorIfNeeded() menu.addItem(openInBrowserMenuItem(link)) menu.addSeparatorIfNeeded() menu.addItem(copyArticleURLMenuItem(link)) if let externalLink = articles.first?.externalLink, externalLink != link { menu.addItem(copyExternalURLMenuItem(externalLink)) } } if let sharingMenu = shareMenu(for: articles) { menu.addSeparatorIfNeeded() let menuItem = NSMenuItem(title: sharingMenu.title, action: nil, keyEquivalent: "") menuItem.submenu = sharingMenu menu.addItem(menuItem) } return menu } func shareMenu(for articles: [Article]) -> NSMenu? { if articles.isEmpty { return nil } let sortedArticles = articles.sortedByDate(.orderedAscending) let items = sortedArticles.map { ArticlePasteboardWriter(article: $0) } let standardServices = NSSharingService.sharingServices(forItems: items) let customServices = SharingServicePickerDelegate.customSharingServices(for: items) let services = standardServices + customServices if services.isEmpty { return nil } let menu = NSMenu(title: NSLocalizedString("Share", comment: "Share menu name")) services.forEach { (service) in service.delegate = sharingServiceDelegate let menuItem = NSMenuItem(title: service.menuItemTitle, action: #selector(performShareServiceFromContextualMenu(_:)), keyEquivalent: "") menuItem.image = service.image let sharingCommandInfo = SharingCommandInfo(service: service, items: items) menuItem.representedObject = sharingCommandInfo menu.addItem(menuItem) } return menu } func markReadMenuItem(_ articles: [Article]) -> NSMenuItem { return menuItem(NSLocalizedString("Mark as Read", comment: "Command"), #selector(markArticlesReadFromContextualMenu(_:)), articles) } func markUnreadMenuItem(_ articles: [Article]) -> NSMenuItem { return menuItem(NSLocalizedString("Mark as Unread", comment: "Command"), #selector(markArticlesUnreadFromContextualMenu(_:)), articles) } func markStarredMenuItem(_ articles: [Article]) -> NSMenuItem { return menuItem(NSLocalizedString("Mark as Starred", comment: "Command"), #selector(markArticlesStarredFromContextualMenu(_:)), articles) } func markUnstarredMenuItem(_ articles: [Article]) -> NSMenuItem { return menuItem(NSLocalizedString("Mark as Unstarred", comment: "Command"), #selector(markArticlesUnstarredFromContextualMenu(_:)), articles) } func markAboveReadMenuItem(_ articles: [Article]) -> NSMenuItem { return menuItem(NSLocalizedString("Mark Above as Read", comment: "Command"), #selector(markAboveArticlesReadFromContextualMenu(_:)), articles) } func markBelowReadMenuItem(_ articles: [Article]) -> NSMenuItem { return menuItem(NSLocalizedString("Mark Below as Read", comment: "Command"), #selector(markBelowArticlesReadFromContextualMenu(_:)), articles) } func selectFeedInSidebarMenuItem(_ feed: WebFeed) -> NSMenuItem { let localizedMenuText = NSLocalizedString("Select “%@” in Sidebar", comment: "Command") let formattedMenuText = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) return menuItem(formattedMenuText as String, #selector(selectFeedInSidebarFromContextualMenu(_:)), feed) } func markAllAsReadMenuItem(_ feed: WebFeed) -> NSMenuItem? { guard let articlesSet = try? feed.fetchArticles() else { return nil } let articles = Array(articlesSet) guard articles.canMarkAllAsRead() else { return nil } let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") let menuText = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String return menuItem(menuText, #selector(markAllInFeedAsRead(_:)), articles) } func openInBrowserMenuItem(_ urlString: String) -> NSMenuItem { return menuItem(NSLocalizedString("Open in Browser", comment: "Command"), #selector(openInBrowserFromContextualMenu(_:)), urlString) } func copyArticleURLMenuItem(_ urlString: String) -> NSMenuItem { return menuItem(NSLocalizedString("Copy Article URL", comment: "Command"), #selector(copyURLFromContextualMenu(_:)), urlString) } func copyExternalURLMenuItem(_ urlString: String) -> NSMenuItem { return menuItem(NSLocalizedString("Copy External URL", comment: "Command"), #selector(copyURLFromContextualMenu(_:)), urlString) } func menuItem(_ title: String, _ action: Selector, _ representedObject: Any) -> NSMenuItem { let item = NSMenuItem(title: title, action: action, keyEquivalent: "") item.representedObject = representedObject item.target = self return item } } private final class SharingCommandInfo { let service: NSSharingService let items: [Any] init(service: NSSharingService, items: [Any]) { self.service = service self.items = items } func perform() { service.perform(withItems: items) } }
mit
1b38e55c94614a6f0ddb4cf83fa6ece2
32.292208
174
0.744783
4.114767
false
false
false
false
harlanhaskins/Snapcache
Snapcache/Snapcache.swift
1
3703
// // Snapcache.swift // // // Created by Harlan Haskins on 11/17/14. // // import UIKit let SnapcacheUserInfoFailingURLKey = "com.snapcache.FailingURLKey" public protocol Cacheable { var url: NSURL { get } var key: String { get } var type: String { get } func snapcache(manager: Snapcache, didLoadImage image: UIImage) func snapcache(manager: Snapcache, didFailWithError error: NSError) } public class Snapcache { public class var sharedCache: Snapcache { return Constants.sharedInstance } private struct Constants { static let sharedInstance = Snapcache() static let requestQueue = dispatch_queue_create("com.snapcache.RequestsQueue", DISPATCH_QUEUE_SERIAL) static let cacheQueue = dispatch_queue_create("com.snapcache.CacheQueue", DISPATCH_QUEUE_SERIAL) } private var cache = [String: NSCache]() private var requests = [NSURL: [Cacheable]]() public func loadImageForObject(object: Cacheable) { if let image = self.cachedImageForKey(object.key, type: object.type) { object.snapcache(self, didLoadImage:image) } else { self.addRequest(object: object) } } private func cachedImageForKey(key: String, type: String) -> UIImage? { return self.cache[type]?.objectForKey(key) as? UIImage } private func cacheImage(image: UIImage, key: String, type: String) { let collection = self.cache[type] ?? NSCache() collection.setObject(image, forKey: key) self.cache[type] = collection } private func setImage(image: UIImage, atURL url: NSURL, forKey key: String, withType type: String) { dispatch_async(Constants.cacheQueue) { self.cacheImage(image, key: key, type: type) self.runCompletionsForURL(url, image: image, error: nil) } } private func addRequest(#object: Cacheable) { dispatch_async(Constants.requestQueue) { var requests = self.requests[object.url] ?? [Cacheable]() requests.append(object) if requests.count == 1 { dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { self.loadAssetForURL(object.url, key: object.key, type: object.type) } } self.requests[object.url] = requests } } private func loadAssetForURL(url: NSURL, key: String, type: String) { let request = NSURLRequest(URL: url) NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if let image = UIImage(data: data) { self.setImage(image, atURL: url, forKey: key, withType: type) } else { let realError = error ?? NSError( domain: "Failed to load resource", code: 0xbadb33f, userInfo: [SnapcacheUserInfoFailingURLKey: url] ) self.runCompletionsForURL(url, image: nil, error: realError) } }.resume() } private func runCompletionsForURL(url: NSURL, image: UIImage?, error: NSError?) { dispatch_async(dispatch_get_main_queue()) { if let requests = self.requests[url] { for object in requests { if let image = image { object.snapcache(self, didLoadImage: image) } else if let error = error { object.snapcache(self, didFailWithError: error) } } self.requests[url] = nil } } } }
mit
4c83862cfd65c46426ef7a481f651a11
33.933962
109
0.588442
4.594293
false
false
false
false
ps2/rileylink_ios
MinimedKit/PumpEvents/ClearAlarmPumpEvent.swift
1
926
// // ClearAlarmPumpEvent.swift // RileyLink // // Created by Pete Schwamb on 3/8/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct ClearAlarmPumpEvent: TimestampedPumpEvent { public let length: Int public let rawData: Data public let timestamp: DateComponents public let alarmType: PumpAlarmType public init?(availableData: Data, pumpModel: PumpModel) { length = 7 guard length <= availableData.count else { return nil } rawData = availableData.subdata(in: 0..<length) alarmType = PumpAlarmType(rawType: availableData[1]) timestamp = DateComponents(pumpEventData: availableData, offset: 2) } public var dictionaryRepresentation: [String: Any] { return [ "_type": "ClearAlarm", "alarm": "\(self.alarmType)" ] } }
mit
bff9b9604e67ba518a14c1d72e458cf0
24
75
0.623784
4.60199
false
false
false
false
laant/mqtt_chat_swift
App/UIImageView+downloadByImageUrl.swift
1
1416
// // UIImageView+downloadByImageUrl.swift // // // http://stackoverflow.com/questions/24231680/loading-image-from-url // answered Leo Dabus // import UIKit extension UIImageView { func downloadByImageUrl(urlStr:String) { guard let url = NSURL(string: urlStr) else {return} let extInfo = Utility.isExistImageFile(urlStr) if extInfo.is_exist { let image = UIImage(contentsOfFile: extInfo.full_path)! self.image = image } else { NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in guard let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200, let mimeType = response?.MIMEType where mimeType.hasPrefix("image"), let data = data where error == nil, let image = UIImage(data: data) else { return } data.writeToFile(extInfo.full_path, atomically: true) dispatch_async(dispatch_get_main_queue()) { () -> Void in self.image = image UIView.animateWithDuration(0.25, animations: { () -> Void in self.alpha = 0 self.alpha = 1 }) } }).resume() } } }
mit
3ef1d69692245e9081849e6706ea740c
35.307692
117
0.543785
4.882759
false
false
false
false
SrirangaDigital/shankara-android
iOS/Advaita Sharada/Advaita Sharada/BookmarkTableDataSource.swift
1
2066
// // BookmarkTableDataSource.swift // Advaita Sharada // // Created by Amiruddin Nagri on 06/08/15. // Copyright (c) 2015 Sriranga Digital Software Technologies Pvt. Ltd. All rights reserved. // import UIKit import CoreData class BookmarkTableDataSource: NSObject, LinkBasedDataSource { var managedObjectContext: NSManagedObjectContext? var userDataManagedObjectContext: NSManagedObjectContext? let book: Link let count: Int init(managedObjectContext: NSManagedObjectContext, userDataManagedObjectContext: NSManagedObjectContext, book: Link) { self.book = book self.managedObjectContext = managedObjectContext self.userDataManagedObjectContext = userDataManagedObjectContext self.count = Bookmark.count(userDataManagedObjectContext, bookId: self.book.entity_id.integerValue) } func linkForIndexPath(indexPath: NSIndexPath) -> Link? { return Link.linkOnPage(managedObjectContext!, book: book, page: self.bookmarkForIndexPath(indexPath)!.page_id.integerValue) } func bookmarkForIndexPath(indexPath: NSIndexPath) -> Bookmark? { return Bookmark.bookmarkAt(userDataManagedObjectContext!, bookId: self.book.entity_id.integerValue, index: indexPath.row) } @objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("bookmark_cell") as? UITableViewCell ?? UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "bookmark_cell") cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator let bookmark = bookmarkForIndexPath(indexPath) cell.textLabel!.text = bookmark?.bookmark_text cell.detailTextLabel!.text = bookmark?.chapter return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } @objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return count } }
gpl-2.0
5edc2760e177024ec8f881521121fd87
41.163265
190
0.740077
5.380208
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Main/ViewModel/BaseViewModel.swift
1
3495
// // BaseViewModel.swift // DYZB // // Created by xiudou on 16/10/27. // Copyright © 2016年 xiudo. All rights reserved. // import UIKit /// 加载主播 class BaseViewModel { lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() lazy var phoneStatusModel : PhoneStatusModel = PhoneStatusModel() func loadAnchDates(_ isGroup : Bool, urlString : String, parameters : [String : Any]? = nil,finishCallBack:@escaping ()->()){ NetworkTools.requestData(.get, URLString: urlString, parameters: parameters) { (result) -> () in guard let resultDict = result as? [String : Any] else {return} guard let dictArray = resultDict["data"] as? [[String : Any]] else {return} if isGroup == true{ for dic in dictArray{ let roomList = dic["room_list"] as! [[String : Any]] // 处理房间里没有数据的情况 if roomList.count == 0{ continue } debugLog(dic) self.anchorGroups.append(AnchorGroup(dict: dic)) } }else{ // 2.1.创建组 let group = AnchorGroup() // 2.2.遍历dataArray的所有的字典 for dict in dictArray { group.anchors.append(AnchorModel(dict: dict)) } // 2.3.将group,添加到anchorGroups self.anchorGroups.append(group) } finishCallBack() } } } /// 获取时间 extension BaseViewModel { // http://capi.douyucdn.cn/api/v1/timestamp?client_sys=ios func updateDate(_ finishCallBack:@escaping ()->()){ NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/timestamp?client_sys=ios") { (result) in guard let resultDict = result as? [String : Any] else { return } guard let error = resultDict["error"] as? Int else{ return } if error != 0 { debugLog(error) return } guard let date = resultDict["data"] else { return } userDefaults.set(date, forKey: dateKey) userDefaults.synchronize() finishCallBack() } } } /// iPhone状态 extension BaseViewModel { func iPhoneStatus(_ finishCallBack:@escaping ()->(),_ messageCallBack:@escaping (_ message : String)->()){ NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getStatus?token=\(TOKEN)&client_sys=ios") { (result) in guard let resultDict = result as? [String : Any] else { return } guard let error = resultDict["error"] as? Int else{ return } if error != 0 { // debugLog(error) guard let data = resultDict["data"] as? String else { return } messageCallBack("data = \(data),error = \(error)") return } guard let dateDict = resultDict["data"] as? [String : Any] else { return } self.phoneStatusModel = PhoneStatusModel(dict: dateDict) finishCallBack() } } }
mit
98258254fa6cb5d04c16eb28edb13185
31.245283
137
0.497659
5.078752
false
false
false
false
rmichelberger/shop
Shop/ExchangeTableViewController.swift
1
5543
// // ExchangeTableViewController.swift // Shop // // Created by Roland Michelberger on 16.04.17. // Copyright © 2017 rolandmichelberger. All rights reserved. // import UIKit class ExchangeTableViewController: UITableViewController { var sourcePrice : Price? private var prices = [Price]() private let currencyFormatter = NumberFormatter() let dateFormatter = DateFormatter() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .medium dateFormatter.locale = Locale.current refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(ExchangeTableViewController.refresh), for: UIControlEvents.valueChanged) tableView.addSubview(refreshControl!) // not required when using UITableViewController // animate refresh control refreshControl?.beginRefreshing() refresh() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refresh() { loadExhangeRates() } func loadExhangeRates() { if let currency = sourcePrice?.currency { ExchangeRatesService.exchangeRates(fromSource: currency) { (exchangeRates, error) in if let error = error { print(error) } else if let exchangeRates = exchangeRates { self.prices.removeAll() for exchangeRate in exchangeRates.quotes { if let amount = self.sourcePrice?.amount.multiplying(by: NSDecimalNumber(string: "\(exchangeRate.rate)")) { self.prices.append(Price(amount: amount, currency: exchangeRate.to)) } } // order alphabetical by currency self.prices = self.prices.sorted(by: { $0.currency.rawValue < $1.currency.rawValue }) } DispatchQueue.main.async { self.tableView.reloadData() self.refreshControl?.endRefreshing() if let timeInterval = exchangeRates?.timestamp { let date = Date(timeIntervalSince1970: TimeInterval(timeInterval)) let dateString = self.dateFormatter.string(from: date) self.refreshControl?.attributedTitle = NSAttributedString(string: dateString) } } } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return prices.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... let price = prices[indexPath.row] cell.textLabel?.text = currencyFormatter.string(from: price) return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
6632433cc6c875a83ca123d4edcdc877
36.70068
137
0.620715
5.684103
false
false
false
false
kickstarter/ios-ksapi
KsApi/models/Update.swift
1
1751
import Foundation import Argo import Curry import Runes public struct Update { public let body: String? public let commentsCount: Int? public let hasLiked: Bool? public let id: Int public let isPublic: Bool public let likesCount: Int? public let projectId: Int public let publishedAt: TimeInterval? public let sequence: Int public let title: String public let urls: UrlsEnvelope public let user: User? public let visible: Bool? public struct UrlsEnvelope { public let web: WebEnvelope public struct WebEnvelope { public let update: String } } } extension Update: Equatable { } public func == (lhs: Update, rhs: Update) -> Bool { return lhs.id == rhs.id } extension Update: Decodable { public static func decode(_ json: JSON) -> Decoded<Update> { let create = curry(Update.init) let tmp1 = create <^> json <|? "body" <*> json <|? "comments_count" <*> json <|? "has_liked" let tmp2 = tmp1 <*> json <| "id" <*> json <| "public" <*> json <|? "likes_count" let tmp3 = tmp2 <*> json <| "project_id" <*> json <|? "published_at" <*> json <| "sequence" <*> (json <| "title" <|> .success("")) return tmp3 <*> json <| "urls" <*> json <|? "user" <*> json <|? "visible" } } extension Update.UrlsEnvelope: Decodable { static public func decode(_ json: JSON) -> Decoded<Update.UrlsEnvelope> { return curry(Update.UrlsEnvelope.init) <^> json <| "web" } } extension Update.UrlsEnvelope.WebEnvelope: Decodable { static public func decode(_ json: JSON) -> Decoded<Update.UrlsEnvelope.WebEnvelope> { return curry(Update.UrlsEnvelope.WebEnvelope.init) <^> json <| "update" } }
apache-2.0
d57a535a2f3d966f13b13d2c684a213f
23.319444
87
0.622501
3.891111
false
false
false
false
wireapp/wire-ios-sync-engine
Source/Synchronization/Strategies/LabelUpstreamRequestStrategy.swift
1
4758
// // Wire // Copyright (C) 2019 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 public class LabelUpstreamRequestStrategy: AbstractRequestStrategy, ZMContextChangeTracker, ZMContextChangeTrackerSource, ZMSingleRequestTranscoder { fileprivate let jsonEncoder = JSONEncoder() fileprivate var upstreamSync: ZMSingleRequestSync! override public init(withManagedObjectContext managedObjectContext: NSManagedObjectContext, applicationStatus: ApplicationStatus) { super.init(withManagedObjectContext: managedObjectContext, applicationStatus: applicationStatus) self.configuration = .allowsRequestsWhileOnline self.upstreamSync = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: managedObjectContext) } override public func nextRequestIfAllowed(for apiVersion: APIVersion) -> ZMTransportRequest? { return upstreamSync.nextRequest(for: apiVersion) } // MARK: - ZMContextChangeTracker, ZMContextChangeTrackerSource public var contextChangeTrackers: [ZMContextChangeTracker] { return [self] } public func fetchRequestForTrackedObjects() -> NSFetchRequest<NSFetchRequestResult>? { guard let predicateForObjectsThatNeedToBeUpdatedUpstream = Label.predicateForObjectsThatNeedToBeUpdatedUpstream() else { fatal("predicateForObjectsThatNeedToBeUpdatedUpstream not defined for Label entity") } return Label.sortedFetchRequest(with: predicateForObjectsThatNeedToBeUpdatedUpstream) } public func addTrackedObjects(_ objects: Set<NSManagedObject>) { guard !objects.isEmpty else { return } upstreamSync.readyForNextRequestIfNotBusy() } public func objectsDidChange(_ object: Set<NSManagedObject>) { let labels = object.compactMap({ $0 as? Label }) guard !labels.isEmpty, labels.any({ Label.predicateForObjectsThatNeedToBeUpdatedUpstream()!.evaluate(with: $0) }) else { return } upstreamSync.readyForNextRequestIfNotBusy() } // MARK: - ZMSingleRequestTranscoder public func request(for sync: ZMSingleRequestSync, apiVersion: APIVersion) -> ZMTransportRequest? { let fetchRequest = NSFetchRequest<Label>(entityName: Label.entityName()) let labels = managedObjectContext.fetchOrAssert(request: fetchRequest) let labelsToUpload = labels.filter({ !$0.markedForDeletion }) let updatedKeys = labels.map({ return ($0, $0.modifiedKeys) }) let labelPayload = LabelPayload(labels: labelsToUpload.compactMap({ LabelUpdate($0) })) let transportPayload: Any do { let data = try jsonEncoder.encode(labelPayload) transportPayload = try JSONSerialization.jsonObject(with: data, options: []) } catch let error { fatal("Couldn't encode label update: \(error)") } let request = ZMTransportRequest(path: "/properties/labels", method: .methodPUT, payload: transportPayload as? ZMTransportData, apiVersion: apiVersion.rawValue) request.add(ZMCompletionHandler(on: managedObjectContext, block: { [weak self] (response) in self?.didReceive(response, updatedKeys: updatedKeys) })) return request } private func didReceive(_ response: ZMTransportResponse, updatedKeys: [(Label, Set<AnyHashable>?)]) { guard response.result == .permanentError || response.result == .success else { return } for (label, updatedKeys) in updatedKeys { guard let updatedKeys = updatedKeys else { continue } if updatedKeys.contains(#keyPath(Label.markedForDeletion)) { managedObjectContext.delete(label) } else { label.resetLocallyModifiedKeys(updatedKeys) } } } public func didReceive(_ response: ZMTransportResponse, forSingleRequest sync: ZMSingleRequestSync) { if let labelsWithModifications = try? managedObjectContext.count(for: fetchRequestForTrackedObjects()!), labelsWithModifications > 0 { upstreamSync.readyForNextRequestIfNotBusy() } } }
gpl-3.0
23107b8da45fbfd7ba22406671513fd6
41.482143
168
0.716478
5.316201
false
false
false
false
jianghongbing/APIReferenceDemo
Swift/Syntax/Array.playground/Contents.swift
1
6214
//: Playground - noun: a place where people can play import UIKit //Array:元素的集合,有序的,可以重复的 //1.Array的构建 //字面量构建 let intArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] //构建空数组,下面这两行代码的都是构建空数组,构建空数组必须指定数组元素的类型 //var emptyArray : [String] = [] var emptyArray = [String]() //构建一个重复元素的数组 let repeatElementArray = Array(repeatElement("hello", count: 5)) //2.Array常用的属性 let isEmpty = emptyArray.isEmpty //判断某个元素是否为空 let count = intArray.count //数组中元素的个数 let capacity = intArray.capacity //数组的容量.大于或等于数组中元素的个数 //3.访问Array中的元素 let first = intArray.first //数组中的第一个元素 let last = intArray.last //数组中的最后一个元素 let indexElement = intArray[4] //通过下标来访问数组中的元素 let subRangeArray = intArray[2 ..< 5] //获取某个range范围内的元素 //4.添加元素,let修饰的数组常量不能添加或移除元素 var cities = [String]() //添加元素 cities.append("wuhan") cities.append(contentsOf: ["beijing", "shanghai"]) //添加某一个集合到该数组的后面,该集合中的元素必须和数组中的元素类型相同,或者是其子类 //插入元素 cities.insert("shenzhen", at: 0) cities.insert(contentsOf: ["guangzhou", "chengdu"], at: 2) //替换元素 cities.replaceSubrange(0 ..< 2, with: ["chongqing", "wuhan"]) //使用指定的大小来储存数组 cities.reserveCapacity(cities.count) //5.查找元素 let isContains = cities.contains("wuhan") //数组是否包含某个元素 //找出符合条件的第一个元素 let findFirst = cities.first { $0.contains("u") } findFirst var index = cities.index(of: "chengdu") //元素的索引 //找出符合元素的索引 index = cities.index(where: { $0.hasPrefix("wu") }) index //元素中最大值和最小值 var min = cities.min() var max = cities.max() min = cities.min { $0.count < $1.count } min max = cities.max { $0.count < $1.count } max //6.子数组 //从前往后找子数组 var prefix = cities.prefix(2) //数组的元素的索引小于n的元素(不包含index为2的元素)组成的集合 prefix = cities.prefix(through: 2) //数组的元素的索引小于或等于n的元素(包含index为2的元素)组成的集合 prefix = cities.prefix(upTo: 3) //数组的元素的索引小于n的元素的集合 prefix = cities.prefix { $0 >= "c" } //如果找到不符合条件的元素,就停止查找,忽略后面的元素,返回第一个不符合条件的前面的符合条件的元素的集合 print(prefix) //从后往前找子数组 var suffix = cities.suffix(2) //后2个元素 suffix = cities.suffix(from: 2) //后n-2个元素 //7.drop,返回移除元素后的元素数组, var dropElementArray = cities.dropFirst() //返回移除第一个元素后的数组 dropElementArray = cities.dropLast() //返回移除后最后一个元素后的数组 dropElementArray = cities.dropLast(2) //返回移除后2两个元素后的数组 dropElementArray = cities.dropFirst(2) //返回移除前2个元素后的数组 //8.数组的转变 //map函数,返回一个转变后的数组 let mapArray = cities.map { $0.count } print(mapArray) let reduceString = cities.reduce("") { $0 + $1 } print(reduceString) //9.枚举器 //数组的遍历 for city in cities { print(city) } cities.forEach { print($0) } for (index, city) in cities.enumerated() { print(index, city) } var iterator = cities.makeIterator() while let next = iterator.next() { print(next) } //10.数组的排序 cities.sort() cities.sort { $0.count > $1.count } //按照某种条件排序 cities.reverse() //翻转元素 cities.swapAt(0, 2) //交换某两个元素的位置 //11.join && splite //将数组元素合并成一个字符串 let cityString = cities.joined(separator: ",") //将字符串以某个分隔符,返回分割后的元素组成的数组 let cityArray = cities.split(separator: ",") let nestedArray = [[1, 6, 4], [2, 5, 7]] //如果数组中元素也有数组,返回内元素组成的数组 let joinedArray = nestedArray.joined() for number in joinedArray { print(number) } //11.数组的比较 let a = [1, 2, 3, 4, 5] let b = [1, 2, 4, 3, 5] a == b //元素相同,顺序一致 a != b a.elementsEqual(b) //元素相同,顺序一致 a.starts(with: [1, 2]) //是否已某个集合为起点 //符合某种条件的是否以某个集合为起点 //a.starts(with: [1, 2]) { // $0 == $1 //} a.lexicographicallyPrecedes(b) //a中的元素是否在b中的元素之前(以在字典中的顺序做比较) //12 index let startIndex = cities.startIndex //数组的开始索引,总是为0 let endIndex = cities.endIndex //数组的结束索引,值为cities.count - 1 let indexAfter = cities.index(after: startIndex) //某个索引的后一个索引 let indexBefore = cities.index(before: endIndex) //某个索引的前一个索引 var inoutIndex = 3 cities.formIndex(before: &inoutIndex) //formIndex inoutIndex cities.formIndex(after: &inoutIndex) inoutIndex cities.index(1, offsetBy: 2) //某一个index,再增加一个数值后的index cities.index(1, offsetBy: 3, limitedBy: 5) //限定一个最大值的index,在某个index,在增加一个数值后的index,不能超过限定的index cities.distance(from: startIndex, to: endIndex) //两个index之间的距离 //indices:获取数组的合法索引目录,也就是其中的值不会超过数组的边界 for index in cities.indices { print(index) } //13.remove //cities.removeFirst() //移除第一个元素 //cities.removeLast() //移除最后一个元素 //cities.remove(at: 0) //移除某一个位置的元素 //cities.removeFirst(2) //移除前2个元素 //cities.removeLast(2) //移除后2个元素 let indexRange = startIndex ..< cities.index(startIndex, offsetBy: 2) cities.removeSubrange(indexRange) //移除某一范围内的元素 cities.popLast() //最后一个元素出栈,从当前的数组中移除,并返回该元素 cities.capacity cities.removeAll(keepingCapacity: true) //移除所有的元素,是否保存数组的容量 cities.capacity cities.removeAll(keepingCapacity: false) cities.capacity
mit
5183d335be9e99930004dfb5d60d100c
26.349693
95
0.727456
2.762082
false
false
false
false
whiteath/ReadFoundationSource
Foundation/Measurement.swift
5
14908
//===----------------------------------------------------------------------===// // // 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 /// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`. /// /// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators. public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable, CustomStringConvertible { public typealias ReferenceType = NSMeasurement /// The unit component of the `Measurement`. public let unit: UnitType /// The value component of the `Measurement`. public var value: Double /// Create a `Measurement` given a specified value and unit. public init(value: Double, unit: UnitType) { self.value = value self.unit = unit } public var hashValue: Int { return Int(bitPattern: _CFHashDouble(value)) } public var description: String { return "\(value) \(unit.symbol)" } public var debugDescription: String { return "\(value) \(unit.symbol)" } } /// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension. extension Measurement where UnitType : Dimension { /// Returns a new measurement created by converting to the specified unit. /// /// - parameter otherUnit: A unit of the same `Dimension`. /// - returns: A converted measurement. public func converted(to otherUnit: UnitType) -> Measurement<UnitType> { if unit.isEqual(otherUnit) { return Measurement(value: value, unit: otherUnit) } else { let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value) if otherUnit.isEqual(type(of: unit).baseUnit()) { return Measurement(value: valueInTermsOfBase, unit: otherUnit) } else { let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase) return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit) } } } /// Converts the measurement to the specified unit. /// /// - parameter otherUnit: A unit of the same `Dimension`. public mutating func convert(to otherUnit: UnitType) { self = converted(to: otherUnit) } } /// Add two measurements of the same Unit. /// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`. /// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`. public func +<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value + rhs.value, unit: lhs.unit) } else { fatalError("Attempt to add measurements with non-equal units") } } /// Add two measurements of the same Dimension. /// /// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit. /// - returns: The result of adding the two measurements. public func +<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value + rhs.value, unit: lhs.unit) } else { let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value) let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value) return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit()) } } /// Subtract two measurements of the same Unit. /// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`. /// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`. public func -<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value - rhs.value, unit: lhs.unit) } else { fatalError("Attempt to subtract measurements with non-equal units") } } /// Subtract two measurements of the same Dimension. /// /// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit. /// - returns: The result of adding the two measurements. public func -<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit == rhs.unit { return Measurement(value: lhs.value - rhs.value, unit: lhs.unit) } else { let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value) let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value) return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit()) } } /// Multiply a measurement by a scalar value. /// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`. public func *<UnitType>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> { return Measurement(value: lhs.value * rhs, unit: lhs.unit) } /// Multiply a scalar value by a measurement. /// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`. public func *<UnitType>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> { return Measurement(value: lhs * rhs.value, unit: rhs.unit) } /// Divide a measurement by a scalar value. /// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`. public func /<UnitType>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> { return Measurement(value: lhs.value / rhs, unit: lhs.unit) } /// Divide a scalar value by a measurement. /// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`. public func /<UnitType>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> { return Measurement(value: lhs / rhs.value, unit: rhs.unit) } /// Compare two measurements of the same `Unit`. /// - returns: `true` if `lhs.value == rhs.value && lhs.unit == rhs.unit`. public func ==<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value == rhs.value && lhs.unit == rhs.unit } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if the measurements are equal. public func ==<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value == rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value == rhsInLhs.value } } /// Compare two measurements of the same `Unit`. /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`. /// - returns: `lhs.value < rhs.value` public func <<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value < rhs.value } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value < rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if `lhs` is less than `rhs`. public func <<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value < rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value < rhsInLhs.value } } /// Compare two measurements of the same `Unit`. /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`. /// - returns: `lhs.value > rhs.value` public func ><UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value > rhs.value } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value > rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if `lhs` is greater than `rhs`. public func ><UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value > rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value > rhsInLhs.value } } /// Compare two measurements of the same `Unit`. /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`. /// - returns: `lhs.value <= rhs.value` public func <=<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value <= rhs.value } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value < rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if `lhs` is less than or equal to `rhs`. public func <=<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value <= rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value <= rhsInLhs.value } } /// Compare two measurements of the same `Unit`. /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`. /// - returns: `lhs.value >= rhs.value` public func >=<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value >= rhs.value } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value >= rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if `lhs` is greater or equal to `rhs`. public func >=<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value >= rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value >= rhsInLhs.value } } // Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types. extension Measurement : _ObjectTypeBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSMeasurement { return NSMeasurement(doubleValue: value, unit: unit) } public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) { result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType) } public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool { if let u = source.unit as? UnitType { result = Measurement(value: source.doubleValue, unit: u) return true } else { return false } } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement { let u = source!.unit as! UnitType return Measurement(value: source!.doubleValue, unit: u) } } extension Measurement : Codable { private enum CodingKeys : Int, CodingKey { case value case unit } private enum UnitCodingKeys : Int, CodingKey { case symbol case converter } private enum LinearConverterCodingKeys : Int, CodingKey { case coefficient case constant } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let value = try container.decode(Double.self, forKey: .value) let unitContainer = try container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit) let symbol = try unitContainer.decode(String.self, forKey: .symbol) let unit: UnitType if UnitType.self is Dimension.Type { let converterContainer = try unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter) let coefficient = try converterContainer.decode(Double.self, forKey: .coefficient) let constant = try converterContainer.decode(Double.self, forKey: .constant) let unitMetaType = (UnitType.self as! Dimension.Type) unit = (unitMetaType.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant)) as! UnitType) } else { unit = UnitType(symbol: symbol) } self.init(value: value, unit: unit) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.value, forKey: .value) var unitContainer = container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit) try unitContainer.encode(self.unit.symbol, forKey: .symbol) if UnitType.self is Dimension.Type { guard type(of: (self.unit as! Dimension).converter) is UnitConverterLinear.Type else { preconditionFailure("Cannot encode a Measurement whose UnitType has a non-linear unit converter.") } let converter = (self.unit as! Dimension).converter as! UnitConverterLinear var converterContainer = unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter) try converterContainer.encode(converter.coefficient, forKey: .coefficient) try converterContainer.encode(converter.constant, forKey: .constant) } } }
apache-2.0
938ba493d371ae2664a0ac2d9409183d
43.634731
276
0.667695
4.329945
false
false
false
false
muukii0803/PhotosPicker
PhotosPicker/Sources/PhotosPickerAssetCell.swift
2
4682
// PhotosPickerAssetCell.swift // // Copyright (c) 2015 muukii // // 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 Foundation public class PhotosPickerAssetCell: UICollectionViewCell { public weak var thumbnailImageView: UIImageView? public override init(frame: CGRect) { super.init(frame: frame) self.setup() self.setupSelectedOverlayView() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func prepareForReuse() { super.prepareForReuse() self.thumbnailImageView?.image = nil } public func setup() { let thumbnailImageView = UIImageView() thumbnailImageView.contentMode = .ScaleAspectFill thumbnailImageView.clipsToBounds = true thumbnailImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.contentView.addSubview(thumbnailImageView) self.thumbnailImageView = thumbnailImageView let views = [ "thumbnailImageView": thumbnailImageView, ] self.contentView.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "V:|-(0)-[thumbnailImageView]-(0)-|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views ) ) self.contentView.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "H:|-(0)-[thumbnailImageView]-(0)-|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views ) ) } public override var selected: Bool { get { return super.selected } set { super.selected = newValue self._selectedOvarlayView?.alpha = newValue ? 1: 0 } } public func didSelect(selected: Bool) { let animateView = self.contentView.snapshotViewAfterScreenUpdates(true) self.addSubview(animateView) self.contentView.hidden = true UIView.animateKeyframesWithDuration(0.45, delay: 0, options: UIViewKeyframeAnimationOptions.BeginFromCurrentState, animations: { () -> Void in UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.15, animations: { () -> Void in animateView.transform = CGAffineTransformMakeScale(0.95, 0.95) }) UIView.addKeyframeWithRelativeStartTime(0.15, relativeDuration: 0.15, animations: { () -> Void in animateView.transform = CGAffineTransformMakeScale(1.03, 1.03) }) UIView.addKeyframeWithRelativeStartTime(0.30, relativeDuration: 0.15, animations: { () -> Void in animateView.transform = CGAffineTransformIdentity }) }) { (finish) -> Void in animateView.removeFromSuperview() self.contentView.hidden = false } } public func selectedOverlayView() -> UIView { let view = UIView() view.backgroundColor = UIColor(white: 0, alpha: 0.5) return view } private func setupSelectedOverlayView() { let view = self.selectedOverlayView() view.frame = self.bounds view.alpha = 0 self.contentView.addSubview(view) self._selectedOvarlayView = view } private var _selectedOvarlayView: UIView? }
mit
c94c3da80a9f38d1061d466c61b4f87c
33.940299
150
0.632208
5.57381
false
false
false
false
cbracken/flutter
examples/platform_channel_swift/ios/Runner/AppDelegate.swift
6
3453
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import UIKit import Flutter enum ChannelName { static let battery = "samples.flutter.io/battery" static let charging = "samples.flutter.io/charging" } enum BatteryState { static let charging = "charging" static let discharging = "discharging" } enum MyFlutterErrorCode { static let unavailable = "UNAVAILABLE" } @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate, FlutterStreamHandler { private var eventSink: FlutterEventSink? override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { GeneratedPluginRegistrant.register(with: self) guard let controller = window?.rootViewController as? FlutterViewController else { fatalError("rootViewController is not type FlutterViewController") } let batteryChannel = FlutterMethodChannel(name: ChannelName.battery, binaryMessenger: controller.binaryMessenger) batteryChannel.setMethodCallHandler({ [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in guard call.method == "getBatteryLevel" else { result(FlutterMethodNotImplemented) return } self?.receiveBatteryLevel(result: result) }) let chargingChannel = FlutterEventChannel(name: ChannelName.charging, binaryMessenger: controller.binaryMessenger) chargingChannel.setStreamHandler(self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } private func receiveBatteryLevel(result: FlutterResult) { let device = UIDevice.current device.isBatteryMonitoringEnabled = true guard device.batteryState != .unknown else { result(FlutterError(code: MyFlutterErrorCode.unavailable, message: "Battery info unavailable", details: nil)) return } result(Int(device.batteryLevel * 100)) } public func onListen(withArguments arguments: Any?, eventSink: @escaping FlutterEventSink) -> FlutterError? { self.eventSink = eventSink UIDevice.current.isBatteryMonitoringEnabled = true sendBatteryStateEvent() NotificationCenter.default.addObserver( self, selector: #selector(AppDelegate.onBatteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil) return nil } @objc private func onBatteryStateDidChange(notification: NSNotification) { sendBatteryStateEvent() } private func sendBatteryStateEvent() { guard let eventSink = eventSink else { return } switch UIDevice.current.batteryState { case .full: eventSink(BatteryState.charging) case .charging: eventSink(BatteryState.charging) case .unplugged: eventSink(BatteryState.discharging) default: eventSink(FlutterError(code: MyFlutterErrorCode.unavailable, message: "Charging status unavailable", details: nil)) } } public func onCancel(withArguments arguments: Any?) -> FlutterError? { NotificationCenter.default.removeObserver(self) eventSink = nil return nil } }
bsd-3-clause
9ec6a5e151e59a32a96501e366378845
32.524272
98
0.696496
5.161435
false
false
false
false
inacioferrarini/York
Classes/Context/FullStackAppContext.swift
1
1836
// The MIT License (MIT) // // Copyright (c) 2016 Inácio Ferrarini // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit open class FullStackAppContext: NSObject { open let viewControllers: [String : UIViewController] open let coreDataStack: CoreDataStack open let syncRules: DataSyncRules open let router: NavigationRouter open let logger: Logger public init(viewControllers: [String : UIViewController], coreDataStack: CoreDataStack, syncRules: DataSyncRules, router: NavigationRouter, logger: Logger) { self.viewControllers = viewControllers self.coreDataStack = coreDataStack self.syncRules = syncRules self.router = router self.logger = logger super.init() } }
mit
a876e942c6f12a6afe2d2c7537654628
41.674419
161
0.723706
4.693095
false
false
false
false
markohlebar/Fontana
Spreadit/AppDelegate.swift
1
3555
// // AppDelegate.swift // Spreadit // // Created by Marko Hlebar on 28/10/2015. // Copyright © 2015 Marko Hlebar. All rights reserved. // import UIKit import HockeySDK import iRate @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, iRateDelegate { var window: UIWindow? override class func initialize(){ let rate = iRate.sharedInstance() rate.eventsUntilPrompt = 10; rate.daysUntilPrompt = 0; rate.remindPeriod = 0; } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let url = launchOptions?[UIApplicationLaunchOptionsURLKey] as? NSURL FNTAppTracker.sharedInstance().startWithPreviewURL(url) let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil) NSURLCache.setSharedURLCache(urlCache) NSSetUncaughtExceptionHandler { (exception : NSException) -> Void in print(exception.callStackSymbols) } UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.whiteColor()] UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().barTintColor = UIColor.fnt_teal() UITabBar.appearance().tintColor = UIColor.fnt_teal() BITHockeyManager.sharedHockeyManager().configureWithIdentifier("9bc7ee209ec3404dba1ec07b94cca99e"); BITHockeyManager.sharedHockeyManager().startManager(); BITHockeyManager.sharedHockeyManager().authenticator.authenticateInstallation(); DonationStore.defaultStore.loadProducts() return true } func openURLIfNeeded(options: [NSObject: AnyObject]) { if let url = options[UIApplicationLaunchOptionsURLKey] { openUrl(url as! NSURL) } } func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { return openUrl(url) } func openUrl(url: NSURL) -> Bool { guard url.scheme == "fontanakey" else { return false } if (url.absoluteString == "fontanakey://donate") { rootViewController().selectedIndex = 1 } else if (url.absoluteString == "fontanakey://usage") { let viewController = UIViewController.loadFromStoryboard("VideoViewController") as! VideoViewController viewController.selectedIndex = 1 rootViewController().selectedIndex = 1 rootViewController().pushViewController(viewController) } else if (url.absoluteString == "fontanakey://installation") { let viewController = UIViewController.loadFromStoryboard("VideoViewController") as! VideoViewController viewController.selectedIndex = 0 rootViewController().selectedIndex = 1 rootViewController().pushViewController(viewController) } return true } func pushOnCurrentNavigationController(viewController: UIViewController) { if let navigationController = rootViewController().selectedViewController as? UINavigationController { navigationController.pushViewController(viewController, animated: false) } } func rootViewController() -> RootViewController { return window!.rootViewController! as! RootViewController } }
agpl-3.0
a975a6b42350da229370731d39d3fdd5
36.020833
127
0.665729
5.778862
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Discover/CustomView/StarCardView.swift
3
3562
// // StarCardView.swift // iOSStar // // Created by J-bb on 17/7/6. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import Kingfisher class StarCardView: UICollectionViewCell { lazy var showImageView:UIImageView = { let imageView = UIImageView() imageView.isUserInteractionEnabled = true imageView.image = UIImage(named: "blank") imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView }() lazy var infoView: UIView = { let view = UIView() view.backgroundColor = UIColor(hexString: "7C09AC") return view }() lazy var statusLabel: UILabel = { let label = UILabel() label.text = "正式出售" label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: 14) label.textAlignment = .center return label }() lazy var priceLabel: UILabel = { let label = UILabel() label.text = "¥7.06/秒" label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: 24) label.textAlignment = .center return label }() var backImage:UIImage? override init(frame: CGRect) { super.init(frame: frame) addSubViews() } func addSubViews() { showImageView.layer.cornerRadius = 4 showImageView.layer.masksToBounds = true showImageView.layer.shadowColor = UIColor.gray.cgColor showImageView.layer.shadowOffset = CGSize(width: 10, height: 10) contentView.addSubview(showImageView) // showImageView.addSubview(infoView) // infoView.addSubview(statusLabel) // infoView.addSubview(priceLabel) showImageView.snp.makeConstraints { (make) in make.top.equalTo(53) make.left.equalTo(15) make.right.equalTo(-15) make.bottom.equalTo(-60) } // infoView.snp.makeConstraints { (make) in // make.bottom.equalTo(0) // make.left.equalTo(0) // make.right.equalTo(0) // make.height.equalTo(75) // } // // statusLabel.snp.makeConstraints { (make) in // make.top.equalTo(14) // make.centerX.equalTo(infoView) // make.height.equalTo(14) // } // priceLabel.snp.makeConstraints { (make) in // make.top.equalTo(statusLabel.snp.bottom).offset(14) // make.centerX.equalTo(statusLabel) // make.height.equalTo(18) // } // backImage = showImageView.image } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubViews() } func setStarModel(starModel:StarSortListModel) { guard URL(string:ShareDataModel.share().qiniuHeader + starModel.home_pic_tail) != nil else { return } showImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + starModel.home_pic_tail)!, placeholder: UIImage(named: "blank"), options: nil, progressBlock: nil) { (image, error, cacheType, url) in if image != nil { self.backImage = image } } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
gpl-3.0
aaab19bc4b550569097dac9ae07958fe
27.837398
222
0.582464
4.45603
false
false
false
false
BalestraPatrick/HomeKitty
Sources/App/Setup/Route.swift
1
680
// // Copyright © 2018 HomeKitty. All rights reserved. // import Routing import Vapor /// Register your application's routes here. public func routes(_ router: Router) throws { // Configuring controllers _ = AboutController(router: router) _ = ManufacturerController(router: router) _ = AccessoryController(router: router) _ = SearchController(router: router) _ = ReportController(router: router) _ = DonationController(router: router) _ = CategoryController(router: router) _ = HomeController(router: router) _ = ContributeController(router: router) _ = HomeKitAppController(router: router) _ = RSSController(router: router) }
mit
28123e65dfc655d445e4582d9a4b7ea9
29.863636
52
0.701031
4.24375
false
false
false
false
ALiOSDev/ALTableView
ALTableViewSwift/Pods/SwipeCellKit/Source/SwipeController.swift
1
22346
// // SwipeController.swift // SwipeCellKit // // Created by Mohammad Kurabi on 5/19/18. // import Foundation protocol SwipeControllerDelegate: class { func swipeController(_ controller: SwipeController, canBeginEditingSwipeableFor orientation: SwipeActionsOrientation) -> Bool func swipeController(_ controller: SwipeController, editActionsForSwipeableFor orientation: SwipeActionsOrientation) -> [SwipeAction]? func swipeController(_ controller: SwipeController, editActionsOptionsForSwipeableFor orientation: SwipeActionsOrientation) -> SwipeOptions func swipeController(_ controller: SwipeController, willBeginEditingSwipeableFor orientation: SwipeActionsOrientation) func swipeController(_ controller: SwipeController, didEndEditingSwipeableFor orientation: SwipeActionsOrientation) func swipeController(_ controller: SwipeController, didDeleteSwipeableAt indexPath: IndexPath) func swipeController(_ controller: SwipeController, visibleRectFor scrollView: UIScrollView) -> CGRect? } class SwipeController: NSObject { weak var swipeable: (UIView & Swipeable)? weak var actionsContainerView: UIView? weak var delegate: SwipeControllerDelegate? weak var scrollView: UIScrollView? var animator: SwipeAnimator? let elasticScrollRatio: CGFloat = 0.4 var originalCenter: CGFloat = 0 var scrollRatio: CGFloat = 1.0 var originalLayoutMargins: UIEdgeInsets = .zero lazy var panGestureRecognizer: UIPanGestureRecognizer = { let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:))) gesture.delegate = self return gesture }() lazy var tapGestureRecognizer: UITapGestureRecognizer = { let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(gesture:))) gesture.delegate = self return gesture }() init(swipeable: UIView & Swipeable, actionsContainerView: UIView) { self.swipeable = swipeable self.actionsContainerView = actionsContainerView super.init() configure() } @objc func handlePan(gesture: UIPanGestureRecognizer) { guard let target = actionsContainerView, var swipeable = self.swipeable else { return } let velocity = gesture.velocity(in: target) if delegate?.swipeController(self, canBeginEditingSwipeableFor: velocity.x > 0 ? .left : .right) == false { return } switch gesture.state { case .began: if let swipeable = scrollView?.swipeables.first(where: { $0.state == .dragging }) as? UIView, swipeable != self.swipeable { return } stopAnimatorIfNeeded() originalCenter = target.center.x if swipeable.state == .center || swipeable.state == .animatingToCenter { let orientation: SwipeActionsOrientation = velocity.x > 0 ? .left : .right showActionsView(for: orientation) } case .changed: guard let actionsView = swipeable.actionsView, let actionsContainerView = self.actionsContainerView else { return } guard swipeable.state.isActive else { return } if swipeable.state == .animatingToCenter { let swipedCell = scrollView?.swipeables.first(where: { $0.state == .dragging || $0.state == .left || $0.state == .right }) as? UIView if let swipedCell = swipedCell, swipedCell != self.swipeable { return } } let translation = gesture.translation(in: target).x scrollRatio = 1.0 // Check if dragging past the center of the opposite direction of action view, if so // then we need to apply elasticity if (translation + originalCenter - swipeable.bounds.midX) * actionsView.orientation.scale > 0 { target.center.x = gesture.elasticTranslation(in: target, withLimit: .zero, fromOriginalCenter: CGPoint(x: originalCenter, y: 0)).x swipeable.actionsView?.visibleWidth = abs((swipeable as Swipeable).frame.minX) scrollRatio = elasticScrollRatio return } if let expansionStyle = actionsView.options.expansionStyle, let scrollView = scrollView { let referenceFrame = actionsContainerView != swipeable ? actionsContainerView.frame : nil; let expanded = expansionStyle.shouldExpand(view: swipeable, gesture: gesture, in: scrollView, within: referenceFrame) let targetOffset = expansionStyle.targetOffset(for: swipeable) let currentOffset = abs(translation + originalCenter - swipeable.bounds.midX) if expanded && !actionsView.expanded && targetOffset > currentOffset { let centerForTranslationToEdge = swipeable.bounds.midX - targetOffset * actionsView.orientation.scale let delta = centerForTranslationToEdge - originalCenter animate(toOffset: centerForTranslationToEdge) gesture.setTranslation(CGPoint(x: delta, y: 0), in: swipeable.superview!) } else { target.center.x = gesture.elasticTranslation(in: target, withLimit: CGSize(width: targetOffset, height: 0), fromOriginalCenter: CGPoint(x: originalCenter, y: 0), applyingRatio: expansionStyle.targetOverscrollElasticity).x swipeable.actionsView?.visibleWidth = abs(actionsContainerView.frame.minX) } actionsView.setExpanded(expanded: expanded, feedback: true) } else { target.center.x = gesture.elasticTranslation(in: target, withLimit: CGSize(width: actionsView.preferredWidth, height: 0), fromOriginalCenter: CGPoint(x: originalCenter, y: 0), applyingRatio: elasticScrollRatio).x swipeable.actionsView?.visibleWidth = abs(actionsContainerView.frame.minX) if (target.center.x - originalCenter) / translation != 1.0 { scrollRatio = elasticScrollRatio } } case .ended, .cancelled, .failed: guard let actionsView = swipeable.actionsView, let actionsContainerView = self.actionsContainerView else { return } if swipeable.state.isActive == false && swipeable.bounds.midX == target.center.x { return } swipeable.state = targetState(forVelocity: velocity) if actionsView.expanded == true, let expandedAction = actionsView.expandableAction { perform(action: expandedAction) } else { let targetOffset = targetCenter(active: swipeable.state.isActive) let distance = targetOffset - actionsContainerView.center.x let normalizedVelocity = velocity.x * scrollRatio / distance animate(toOffset: targetOffset, withInitialVelocity: normalizedVelocity) { _ in if self.swipeable?.state == .center { self.reset() } } if !swipeable.state.isActive { delegate?.swipeController(self, didEndEditingSwipeableFor: actionsView.orientation) } } default: break } } @discardableResult func showActionsView(for orientation: SwipeActionsOrientation) -> Bool { guard let actions = delegate?.swipeController(self, editActionsForSwipeableFor: orientation), actions.count > 0 else { return false } guard let swipeable = self.swipeable else { return false } originalLayoutMargins = swipeable.layoutMargins configureActionsView(with: actions, for: orientation) delegate?.swipeController(self, willBeginEditingSwipeableFor: orientation) return true } func configureActionsView(with actions: [SwipeAction], for orientation: SwipeActionsOrientation) { guard var swipeable = self.swipeable, let actionsContainerView = self.actionsContainerView, let scrollView = self.scrollView else { return } let options = delegate?.swipeController(self, editActionsOptionsForSwipeableFor: orientation) ?? SwipeOptions() swipeable.actionsView?.removeFromSuperview() swipeable.actionsView = nil var contentEdgeInsets = UIEdgeInsets.zero if let visibleTableViewRect = delegate?.swipeController(self, visibleRectFor: scrollView) { let frame = (swipeable as Swipeable).frame let visibleSwipeableRect = frame.intersection(visibleTableViewRect) if visibleSwipeableRect.isNull == false { let top = visibleSwipeableRect.minY > frame.minY ? max(0, visibleSwipeableRect.minY - frame.minY) : 0 let bottom = max(0, frame.size.height - visibleSwipeableRect.size.height - top) contentEdgeInsets = UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0) } } let actionsView = SwipeActionsView(contentEdgeInsets: contentEdgeInsets, maxSize: swipeable.bounds.size, safeAreaInsetView: scrollView, options: options, orientation: orientation, actions: actions) actionsView.delegate = self actionsContainerView.addSubview(actionsView) actionsView.heightAnchor.constraint(equalTo: swipeable.heightAnchor).isActive = true actionsView.widthAnchor.constraint(equalTo: swipeable.widthAnchor, multiplier: 2).isActive = true actionsView.topAnchor.constraint(equalTo: swipeable.topAnchor).isActive = true if orientation == .left { actionsView.rightAnchor.constraint(equalTo: actionsContainerView.leftAnchor).isActive = true } else { actionsView.leftAnchor.constraint(equalTo: actionsContainerView.rightAnchor).isActive = true } actionsView.setNeedsUpdateConstraints() swipeable.actionsView = actionsView swipeable.state = .dragging } func animate(duration: Double = 0.7, toOffset offset: CGFloat, withInitialVelocity velocity: CGFloat = 0, completion: ((Bool) -> Void)? = nil) { stopAnimatorIfNeeded() swipeable?.layoutIfNeeded() let animator: SwipeAnimator = { if velocity != 0 { if #available(iOS 10, *) { let velocity = CGVector(dx: velocity, dy: velocity) let parameters = UISpringTimingParameters(mass: 1.0, stiffness: 100, damping: 18, initialVelocity: velocity) return UIViewPropertyAnimator(duration: 0.0, timingParameters: parameters) } else { return UIViewSpringAnimator(duration: duration, damping: 1.0, initialVelocity: velocity) } } else { if #available(iOS 10, *) { return UIViewPropertyAnimator(duration: duration, dampingRatio: 1.0) } else { return UIViewSpringAnimator(duration: duration, damping: 1.0) } } }() animator.addAnimations({ guard let swipeable = self.swipeable, let actionsContainerView = self.actionsContainerView else { return } actionsContainerView.center = CGPoint(x: offset, y: actionsContainerView.center.y) swipeable.actionsView?.visibleWidth = abs(actionsContainerView.frame.minX) swipeable.layoutIfNeeded() }) if let completion = completion { animator.addCompletion(completion: completion) } self.animator = animator animator.startAnimation() } func traitCollectionDidChange(from previousTraitCollrection: UITraitCollection?, to traitCollection: UITraitCollection) { guard let swipeable = self.swipeable, let actionsContainerView = self.actionsContainerView, previousTraitCollrection != nil else { return } if swipeable.state == .left || swipeable.state == .right { let targetOffset = targetCenter(active: swipeable.state.isActive) actionsContainerView.center = CGPoint(x: targetOffset, y: actionsContainerView.center.y) swipeable.actionsView?.visibleWidth = abs(actionsContainerView.frame.minX) swipeable.layoutIfNeeded() } } func stopAnimatorIfNeeded() { if animator?.isRunning == true { animator?.stopAnimation(true) } } @objc func handleTap(gesture: UITapGestureRecognizer) { hideSwipe(animated: true) } @objc func handleTablePan(gesture: UIPanGestureRecognizer) { if gesture.state == .began { hideSwipe(animated: true) } } func targetState(forVelocity velocity: CGPoint) -> SwipeState { guard let actionsView = swipeable?.actionsView else { return .center } switch actionsView.orientation { case .left: return (velocity.x < 0 && !actionsView.expanded) ? .center : .left case .right: return (velocity.x > 0 && !actionsView.expanded) ? .center : .right } } func targetCenter(active: Bool) -> CGFloat { guard let swipeable = self.swipeable else { return 0 } guard let actionsView = swipeable.actionsView, active == true else { return swipeable.bounds.midX } return swipeable.bounds.midX - actionsView.preferredWidth * actionsView.orientation.scale } func configure() { swipeable?.addGestureRecognizer(tapGestureRecognizer) swipeable?.addGestureRecognizer(panGestureRecognizer) } func reset() { swipeable?.state = .center swipeable?.actionsView?.removeFromSuperview() swipeable?.actionsView = nil } } extension SwipeController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == tapGestureRecognizer { if UIAccessibility.isVoiceOverRunning { scrollView?.hideSwipeables() } let swipedCell = scrollView?.swipeables.first(where: { $0.state.isActive || $0.panGestureRecognizer.state == .began || $0.panGestureRecognizer.state == .changed || $0.panGestureRecognizer.state == .ended }) return swipedCell == nil ? false : true } if gestureRecognizer == panGestureRecognizer, let view = gestureRecognizer.view, let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer { let translation = gestureRecognizer.translation(in: view) return abs(translation.y) <= abs(translation.x) } return true } } extension SwipeController: SwipeActionsViewDelegate { func swipeActionsView(_ swipeActionsView: SwipeActionsView, didSelect action: SwipeAction) { perform(action: action) } func perform(action: SwipeAction) { guard let actionsView = swipeable?.actionsView else { return } if action == actionsView.expandableAction, let expansionStyle = actionsView.options.expansionStyle { // Trigger the expansion (may already be expanded from drag) actionsView.setExpanded(expanded: true) switch expansionStyle.completionAnimation { case .bounce: perform(action: action, hide: true) case .fill(let fillOption): performFillAction(action: action, fillOption: fillOption) } } else { perform(action: action, hide: action.hidesWhenSelected) } } func perform(action: SwipeAction, hide: Bool) { guard let indexPath = swipeable?.indexPath else { return } if hide { hideSwipe(animated: true) } action.handler?(action, indexPath) } func performFillAction(action: SwipeAction, fillOption: SwipeExpansionStyle.FillOptions) { guard let swipeable = self.swipeable, let actionsContainerView = self.actionsContainerView else { return } guard let actionsView = swipeable.actionsView, let indexPath = swipeable.indexPath else { return } let newCenter = swipeable.bounds.midX - (swipeable.bounds.width + actionsView.minimumButtonWidth) * actionsView.orientation.scale action.completionHandler = { [weak self] style in guard let `self` = self else { return } action.completionHandler = nil self.delegate?.swipeController(self, didEndEditingSwipeableFor: actionsView.orientation) switch style { case .delete: actionsContainerView.mask = actionsView.createDeletionMask() self.delegate?.swipeController(self, didDeleteSwipeableAt: indexPath) UIView.animate(withDuration: 0.3, animations: { guard let actionsContainerView = self.actionsContainerView else { return } actionsContainerView.center.x = newCenter actionsContainerView.mask?.frame.size.height = 0 swipeable.actionsView?.visibleWidth = abs(actionsContainerView.frame.minX) if fillOption.timing == .after { actionsView.alpha = 0 } }) { [weak self] _ in self?.actionsContainerView?.mask = nil self?.reset() } case .reset: self.hideSwipe(animated: true) } } let invokeAction = { action.handler?(action, indexPath) if let style = fillOption.autoFulFillmentStyle { action.fulfill(with: style) } } animate(duration: 0.3, toOffset: newCenter) { _ in if fillOption.timing == .after { invokeAction() } } if fillOption.timing == .with { invokeAction() } } func hideSwipe(animated: Bool, completion: ((Bool) -> Void)? = nil) { guard var swipeable = self.swipeable, let actionsContainerView = self.actionsContainerView else { return } guard swipeable.state == .left || swipeable.state == .right else { return } guard let actionView = swipeable.actionsView else { return } swipeable.state = .animatingToCenter let targetCenter = self.targetCenter(active: false) if animated { animate(toOffset: targetCenter) { complete in self.reset() completion?(complete) } } else { actionsContainerView.center = CGPoint(x: targetCenter, y: actionsContainerView.center.y) swipeable.actionsView?.visibleWidth = abs(actionsContainerView.frame.minX) reset() } delegate?.swipeController(self, didEndEditingSwipeableFor: actionView.orientation) } func showSwipe(orientation: SwipeActionsOrientation, animated: Bool = true, completion: ((Bool) -> Void)? = nil) { setSwipeOffset(.greatestFiniteMagnitude * orientation.scale * -1, animated: animated, completion: completion) } func setSwipeOffset(_ offset: CGFloat, animated: Bool = true, completion: ((Bool) -> Void)? = nil) { guard var swipeable = self.swipeable, let actionsContainerView = self.actionsContainerView else { return } guard offset != 0 else { hideSwipe(animated: animated, completion: completion) return } let orientation: SwipeActionsOrientation = offset > 0 ? .left : .right let targetState = SwipeState(orientation: orientation) if swipeable.state != targetState { guard showActionsView(for: orientation) else { return } scrollView?.hideSwipeables() swipeable.state = targetState } let maxOffset = min(swipeable.bounds.width, abs(offset)) * orientation.scale * -1 let targetCenter = abs(offset) == CGFloat.greatestFiniteMagnitude ? self.targetCenter(active: true) : swipeable.bounds.midX + maxOffset if animated { animate(toOffset: targetCenter) { complete in completion?(complete) } } else { actionsContainerView.center.x = targetCenter swipeable.actionsView?.visibleWidth = abs(actionsContainerView.frame.minX) } } }
mit
b10d3596d46a1ee0ed5b6dac1f41d40b
41.973077
149
0.590352
6.002149
false
false
false
false
johnno1962/Dynamo
TickTackToe/TickTackToe.swift
1
3861
// // TickTackToe.swift // Yaws // // Created by John Holdsworth on 13/06/2015. // Copyright (c) 2015 John Holdsworth. All rights reserved. // import Foundation #if !os(iOS) import Dynamo #endif private class TickTackGameEngine: NSObject { var board = [["white", "white", "white"], ["white", "white", "white"], ["white", "white", "white"]] func winner() -> String? { var won: String? let middle = board[1][1] if board[1][0] == middle && middle == board[1][2] || board[0][1] == middle && middle == board[2][1] || board[0][0] == middle && middle == board[2][2] || board[0][2] == middle && middle == board[2][0] { if middle != "white" { won = middle } } if board[0][0] == board[0][1] && board[0][1] == board[0][2] || board[0][0] == board[1][0] && board[1][0] == board[2][0] { if board[0][0] != "white" { won = board[0][0] } } if board[0][2] == board[1][2] && board[1][2] == board[2][2] || board[2][0] == board[2][1] && board[2][1] == board[2][2] { if board[2][2] != "white" { won = board[2][2] } } return won } } @objc (TickTackToeSwiftlet) open class TickTackToeSwiftlet: SessionApplication { fileprivate var engine = TickTackGameEngine() @objc override open func processRequest( out: DynamoHTTPConnection, pathInfo: String, parameters: [String:String], cookies: [String:String] ) { var cookies = cookies // reset board and keep scores if let whoWon = parameters["reset"] { engine = TickTackGameEngine() if whoWon != "draw" { let newCount = cookies[whoWon] ?? "0" let newValue = "\(Int(newCount)!+1)" out.setCookie( name: whoWon, value: newValue, expires: 60 ) cookies[whoWon] = newValue } } let scores = cookies.keys .filter( { $0 == "red" || $0 == "green" } ) .map( { "\($0) wins: \(cookies[$0]!)" } ).joined( separator: ", " ) out.print( html( nil ) + head( title( "Tick Tack Toe Example" ) + style( "body, table { font: 10pt Arial; } " + "table { border: 4px outset; } " + "td { border: 4px inset; }" ) ) + body( nil ) + h3( "Tick Tack Toe "+scores ) ) // make move let player = parameters["player"] ?? "green" if let x = parameters["x"]?.toInt(), let y = parameters["y"]?.toInt() { engine.board[y][x] = player } // print board let nextPlayer = player == "green" ? "red" : "green" var played = 0 out.print( center( nil ) + table( nil ) ) for y in 0..<3 { out.print( tr( nil ) ) for x in 0..<3 { var attrs = ["bgcolor":engine.board[y][x], "width":"100", "height":"100"] if engine.board[y][x] != "white" { played += 1 } else { attrs["onclick"] = "document.location.replace( '\(pathInfo)?player=\(nextPlayer)&x=\(x)&y=\(y)' );" } out.print( td( attrs, "&nbsp;" ) ) } out.print( _tr() ) } out.print( _table() ) // check for winner let won = engine.winner() if won != nil { out.print( script( "alert( '\(player) wins' ); document.location.href = '/ticktacktoe?reset=\(won!)';" ) ) } else if played == 9 { out.print( script( "alert( 'It\\'s a draw!' ); document.location.href = '/ticktacktoe?reset=draw';" ) ) } out.print( backButton() ) } }
mit
a4b209d59754938c1f4f531f9633875f
31.445378
147
0.465682
3.652791
false
false
false
false
ranacquat/fish
Carthage/Checkouts/Fusuma/Sources/FSCameraView.swift
1
15367
// // FSCameraView.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/14. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit import AVFoundation enum UIUserInterfaceIdiom : Int { case Unspecified case Phone case Pad } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.main.bounds.size.width static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0 static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0 static let IS_IPAD_PRO = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0 } @objc protocol FSCameraViewDelegate: class { func cameraShotFinished(_ image: UIImage) } final class FSCameraView: UIView, UIGestureRecognizerDelegate { @IBOutlet var typePicker: UIPickerView! @IBOutlet weak var previewViewContainer: UIView! @IBOutlet weak var shotButton: UIButton! @IBOutlet weak var flashButton: UIButton! @IBOutlet weak var flipButton: UIButton! @IBOutlet weak var croppedAspectRatioConstraint: NSLayoutConstraint! @IBOutlet weak var fullAspectRatioConstraint: NSLayoutConstraint! weak var delegate: FSCameraViewDelegate? = nil var session: AVCaptureSession? var device: AVCaptureDevice? var videoInput: AVCaptureDeviceInput? var imageOutput: AVCaptureStillImageOutput? var focusView: UIView? var flashOffImage: UIImage? var flashOnImage: UIImage? static func instance() -> FSCameraView { return UINib(nibName: "FSCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSCameraView } func initialize() { if session != nil { return } self.backgroundColor = fusumaBackgroundColor let bundle = Bundle(for: self.classForCoder) flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil) flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil) let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil) let shotImage = fusumaShotImage != nil ? fusumaShotImage : UIImage(named: "ic_radio_button_checked", in: bundle, compatibleWith: nil) if(fusumaTintIcons) { flashButton.tintColor = fusumaBaseTintColor flipButton.tintColor = fusumaBaseTintColor shotButton.tintColor = fusumaBaseTintColor flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) shotButton.setImage(shotImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) } else { flashButton.setImage(flashOffImage, for: UIControlState()) flipButton.setImage(flipImage, for: UIControlState()) shotButton.setImage(shotImage, for: UIControlState()) } self.isHidden = false // AVCapture session = AVCaptureSession() for device in AVCaptureDevice.devices() { if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.back { self.device = device if !device.hasFlash { flashButton.isHidden = true } } } do { if let session = session { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput) imageOutput = AVCaptureStillImageOutput() session.addOutput(imageOutput) let videoLayer = AVCaptureVideoPreviewLayer(session: session) videoLayer?.frame = self.previewViewContainer.bounds videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill self.previewViewContainer.layer.addSublayer(videoLayer!) session.sessionPreset = AVCaptureSessionPresetPhoto session.startRunning() } // Focus View self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90)) let tapRecognizer = UITapGestureRecognizer(target: self, action:#selector(FSCameraView.focus(_:))) tapRecognizer.delegate = self self.previewViewContainer.addGestureRecognizer(tapRecognizer) } catch { } // THIS TEST IS NEEDED TO BE COMPATIBLE FOR IPAD if (DeviceType.IS_IPAD || DeviceType.IS_IPAD_PRO) { print("IS_IPAD : NO FLASH CONFIGURATION") }else{ flashConfiguration() } self.startCamera() NotificationCenter.default.addObserver(self, selector: #selector(FSCameraView.willEnterForegroundNotification(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) } func willEnterForegroundNotification(_ notification: Notification) { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if status == AVAuthorizationStatus.authorized { session?.startRunning() } else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted { session?.stopRunning() } } deinit { NotificationCenter.default.removeObserver(self) } func startCamera() { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if status == AVAuthorizationStatus.authorized { session?.startRunning() } else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted { session?.stopRunning() } } func stopCamera() { session?.stopRunning() } @IBAction func shotButtonPressed(_ sender: UIButton) { guard let imageOutput = imageOutput else { return } DispatchQueue.global(qos: .default).async(execute: { () -> Void in let videoConnection = imageOutput.connection(withMediaType: AVMediaTypeVideo) let orientation: UIDeviceOrientation = UIDevice.current.orientation switch (orientation) { case .portrait: videoConnection?.videoOrientation = .portrait case .portraitUpsideDown: videoConnection?.videoOrientation = .portraitUpsideDown case .landscapeRight: videoConnection?.videoOrientation = .landscapeLeft case .landscapeLeft: videoConnection?.videoOrientation = .landscapeRight default: videoConnection?.videoOrientation = .portrait } imageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (buffer, error) -> Void in self.session?.stopRunning() let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) if let image = UIImage(data: data!), let delegate = self.delegate { // Image size var iw: CGFloat var ih: CGFloat switch (orientation) { case .landscapeLeft, .landscapeRight: // Swap width and height if orientation is landscape iw = image.size.height ih = image.size.width default: iw = image.size.width ih = image.size.height } // Frame size let sw = self.previewViewContainer.frame.width // The center coordinate along Y axis let rcy = ih * 0.5 let imageRef = image.cgImage?.cropping(to: CGRect(x: rcy-iw*0.5, y: 0 , width: iw, height: iw)) DispatchQueue.main.async(execute: { () -> Void in if fusumaCropImage { let resizedImage = UIImage(cgImage: imageRef!, scale: sw/iw, orientation: image.imageOrientation) delegate.cameraShotFinished(resizedImage) } else { delegate.cameraShotFinished(image) } self.session = nil self.device = nil self.imageOutput = nil }) } }) }) } @IBAction func flipButtonPressed(_ sender: UIButton) { if !cameraIsAvailable() { return } session?.stopRunning() do { session?.beginConfiguration() if let session = session { for input in session.inputs { session.removeInput(input as! AVCaptureInput) } let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) { if let device = device as? AVCaptureDevice , device.position == position { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput) } } } session?.commitConfiguration() } catch { } session?.startRunning() } @IBAction func flashButtonPressed(_ sender: UIButton) { if !cameraIsAvailable() { return } do { if let device = device { guard device.hasFlash else { return } try device.lockForConfiguration() let mode = device.flashMode if mode == AVCaptureFlashMode.off { device.flashMode = AVCaptureFlashMode.on flashButton.setImage(flashOnImage, for: UIControlState()) } else if mode == AVCaptureFlashMode.on { device.flashMode = AVCaptureFlashMode.off flashButton.setImage(flashOffImage, for: UIControlState()) } device.unlockForConfiguration() } } catch _ { flashButton.setImage(flashOffImage, for: UIControlState()) return } } } extension FSCameraView { @objc func focus(_ recognizer: UITapGestureRecognizer) { let point = recognizer.location(in: self) let viewsize = self.bounds.size let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width) let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { try device?.lockForConfiguration() } catch _ { return } if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true { device?.focusMode = AVCaptureFocusMode.autoFocus device?.focusPointOfInterest = newPoint } if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true { device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure device?.exposurePointOfInterest = newPoint } device?.unlockForConfiguration() self.focusView?.alpha = 0.0 self.focusView?.center = point self.focusView?.backgroundColor = UIColor.clear self.focusView?.layer.borderColor = fusumaBaseTintColor.cgColor self.focusView?.layer.borderWidth = 1.0 self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.addSubview(self.focusView!) UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState animations: { self.focusView!.alpha = 1.0 self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7) }, completion: {(finished) in self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.focusView!.removeFromSuperview() }) } func flashConfiguration() { do { if let device = device { guard device.hasFlash else { return } try device.lockForConfiguration() device.flashMode = AVCaptureFlashMode.off flashButton.setImage(flashOffImage, for: UIControlState()) device.unlockForConfiguration() } } catch _ { return } } func cameraIsAvailable() -> Bool { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if status == AVAuthorizationStatus.authorized { return true } return false } }
mit
e8ec6a7882720aa5c6903c1821379698
33.371365
196
0.555584
6.217726
false
false
false
false
bengottlieb/HelpKit
HelpKit/Framework Code/Walkthrough.Transition.swift
1
4656
// // Walkthrough+Transition.swift // HelpKit // // Created by Ben Gottlieb on 2/19/17. // Copyright © 2017 Stand Alone, Inc. All rights reserved. // import UIKit extension Walkthrough { public enum Direction { case `in`, out, none } public enum EndPoint { case begin, end } public struct Transition { public enum Kind: String { case fade, moveLeft, moveRight, moveUp, moveDown, pop, drop } public let kind: Kind public let duration: TimeInterval? public let delay: TimeInterval public init?(rawValue: String?) { guard let components = rawValue?.components(separatedBy: ","), let kind = Kind(rawValue: components.first ?? "") else { self.kind = .drop return nil } self.kind = kind if components.count > 1, let dur = TimeInterval(components[1]) { self.duration = dur } else { self.duration = nil } if components.count > 2, let delay = TimeInterval(components[2]) { self.delay = delay } else { self.delay = 0 } } public init(kind: Kind, duration: TimeInterval? = nil, delay: TimeInterval = 0) { self.kind = kind self.duration = duration self.delay = delay } var inverse: Transition { switch self.kind { case .moveLeft: return Transition(kind: .moveRight, duration: self.duration, delay: self.delay) case .moveRight: return Transition(kind: .moveLeft, duration: self.duration, delay: self.delay) case .moveUp: return Transition(kind: .moveDown, duration: self.duration, delay: self.delay) case .moveDown: return Transition(kind: .moveUp, duration: self.duration, delay: self.delay) default: return self } } func transform(state: UIView.AnimatableState?, direction: Direction, endPoint: EndPoint, in parent: Scene) -> UIView.AnimatableState? { guard var result = state else { return nil } let disappearing = direction != .in if endPoint == .begin { //how should we set things up before the animation begins? switch self.kind { case .fade: result.alpha = disappearing ? 1.0 : 0.0 case .moveLeft: if !disappearing { result.frame.origin.x = result.frame.origin.x + parent.view.bounds.width } case .moveRight: if !disappearing { result.frame.origin.x = result.frame.origin.x - parent.view.bounds.width } case .moveUp: if !disappearing { result.frame.origin.y = result.frame.origin.y + parent.view.bounds.height } case .moveDown: if !disappearing { result.frame.origin.y = result.frame.origin.y - parent.view.bounds.height } case .pop: if !disappearing { result.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) result.alpha = 0.0 } else { result.transform = .identity result.alpha = 1.0 } case .drop: if !disappearing { result.transform = CGAffineTransform(scaleX: 10.0, y: 10.0) result.alpha = 0.0 } else { result.transform = .identity result.alpha = 1.0 } } } else { switch self.kind { case .fade: result.alpha = disappearing ? 0.0 : 1.0 case .moveLeft: if disappearing { result.frame.origin.x = result.frame.origin.x + parent.view.bounds.width } case .moveRight: if disappearing { result.frame.origin.x = result.frame.origin.x - parent.view.bounds.width } case .moveUp: if disappearing { result.frame.origin.y = result.frame.origin.y + parent.view.bounds.height } case .moveDown: if disappearing { result.frame.origin.y = result.frame.origin.y - parent.view.bounds.height } case .pop: if disappearing { result.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) result.alpha = 0.0 } else { result.transform = .identity result.alpha = 1.0 } case .drop: if disappearing { result.transform = CGAffineTransform(scaleX: 10.0, y: 10.0) result.alpha = 0.0 } else { result.transform = .identity result.alpha = 1.0 } } } return result } } } extension Walkthrough.Transition { public static let fade = Walkthrough.Transition(kind: .fade, duration: 0.2) public static let moveLeft = Walkthrough.Transition(kind: .moveLeft, duration: 0.2) public static let moveRight = Walkthrough.Transition(kind: .moveRight, duration: 0.2) public static let moveUp = Walkthrough.Transition(kind: .moveUp, duration: 0.2) public static let moveDown = Walkthrough.Transition(kind: .moveDown, duration: 0.2) public static let pop = Walkthrough.Transition(kind: .pop, duration: 0.2) public static let drop = Walkthrough.Transition(kind: .drop, duration: 0.2) }
mit
2f920aa76faa770401b5feb55c672134
30.452703
137
0.656069
3.505271
false
false
false
false
davetobin/pxctest
PXCTestKit/Command/RunTests/RunTestsWorker.swift
1
6036
// // RunTestsWorker.swift // pxctest // // Created by Johannes Plunien on 29/12/2016. // Copyright © 2016 Johannes Plunien. All rights reserved. // import FBSimulatorControl import Foundation final class RunTestsWorker { let name: String let applications: [FBApplicationDescriptor] let simulator: FBSimulator let targetName: String let testLaunchConfiguration: FBTestLaunchConfiguration var configuration: FBSimulatorConfiguration { return simulator.configuration! } private(set) var errors: [RunTestsError] = [] init(name: String, applications: [FBApplicationDescriptor], simulator: FBSimulator, targetName: String, testLaunchConfiguration: FBTestLaunchConfiguration) { self.name = name self.applications = applications self.simulator = simulator self.targetName = targetName self.testLaunchConfiguration = testLaunchConfiguration } func abortTestRun() throws { for application in applications { try simulator.killApplication(withBundleID: application.bundleID) } } func cleanUpLogFiles(fileManager: RunTestsFileManager) throws { let logFilesPath = fileManager.urlFor(worker: self).path for logFilePath in FBFileFinder.contentsOfDirectory(withBasePath: logFilesPath) { let temporaryFilePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString).path guard let reader = FileReader(path: logFilePath), let writer = FileWriter(path: temporaryFilePath) else { continue } for line in reader { writer.write(string: line.replacingOccurrences(of: "XCTestOutputBarrier", with: "")) } try FileManager.default.removeItem(atPath: logFilePath) try FileManager.default.moveItem(atPath: temporaryFilePath, toPath: logFilePath) } } func extractDiagnostics(fileManager: RunTestsFileManager) throws { for error in errors { for crash in error.crashes { let destinationPath = fileManager.urlFor(worker: self).path try crash.writeOut(toDirectory: destinationPath) } } } func startTests(context: RunTestsContext, reporters: RunTestsReporters) throws { let workingDirectoryURL = context.fileManager.urlFor(worker: self) let testEnvironment = Environment.injectPrefixedVariables( from: context.environment, into: testLaunchConfiguration.testEnvironment, workingDirectoryURL: workingDirectoryURL ) let bundleName = self.testLaunchConfiguration.applicationLaunchConfiguration!.bundleName! let outputPath = workingDirectoryURL.appendingPathComponent("\(bundleName).log").path let applicationLaunchConfiguration = self.testLaunchConfiguration .applicationLaunchConfiguration! .withOutput(try FBProcessOutputConfiguration(stdOut: outputPath, stdErr: outputPath)) var testLaunchConfigurartion = self.testLaunchConfiguration .withTestEnvironment(testEnvironment) .withApplicationLaunchConfiguration(applicationLaunchConfiguration) let testsToRun: Set<String> = [ context.testsToRun[name], testLaunchConfiguration.testsToRun ].flatMap { $0 }.reduce(Set<String>()) { $0.0.union($0.1) } if testsToRun.count > 0 { testLaunchConfigurartion = testLaunchConfigurartion.withTestsToRun(testsToRun) } let reporter = try reporters.addReporter(for: simulator, name: name, testTargetName: targetName) try simulator.startTest(with: testLaunchConfigurartion, reporter: reporter) } func waitForTestResult(timeout: TimeInterval) { let testManagerResults = simulator.resourceSink.testManagers.flatMap { $0.waitUntilTestingHasFinished(withTimeout: timeout) } if testManagerResults.reduce(true, { $0 && $1.didEndSuccessfully }) { return } errors.append( RunTestsError( simulator: simulator, target: name, errors: testManagerResults.flatMap { $0.error }, crashes: testManagerResults.flatMap { $0.crashDiagnostic } ) ) } } extension Sequence where Iterator.Element == RunTestsWorker { func abortTestRun() throws { for worker in self { try worker.abortTestRun() } } func boot(context: BootContext) throws { for worker in self { guard worker.simulator.state != .booted else { continue } try worker.simulator.boot(context: context) } } func installApplications() throws { for worker in self { try worker.simulator.install(applications: worker.applications) } } func loadDefaults(context: DefaultsContext) throws { for worker in self { try worker.simulator.loadDefaults(context: context) } } func overrideWatchDogTimer() throws { for worker in self { let applications = worker.applications.map { $0.bundleID } try worker.simulator.overrideWatchDogTimer(forApplications: applications, withTimeout: 60.0) } } func startTests(context: RunTestsContext, reporters: RunTestsReporters) throws { for worker in self { try worker.startTests(context: context, reporters: reporters) } } func waitForTestResult(context: TestResultContext) throws -> [RunTestsError] { for worker in self { worker.waitForTestResult(timeout: context.timeout) } for worker in self { try worker.extractDiagnostics(fileManager: context.fileManager) } for worker in self { try worker.cleanUpLogFiles(fileManager: context.fileManager) } return flatMap { $0.errors } } }
mit
389573697f0d6703f630b84a27fb00d3
34.292398
161
0.660481
5.446751
false
true
false
false
OpenSourceContributions/SwiftOCR
framework/SwiftOCR/GPUImage2-master/examples/Mac/FilterShowcase/FilterShowcase/FilterShowcaseWindowController.swift
3
3771
import Cocoa import GPUImage import AVFoundation let blendImageName = "Lambeau.jpg" class FilterShowcaseWindowController: NSWindowController { @IBOutlet var filterView: RenderView! @IBOutlet weak var filterSlider: NSSlider! dynamic var currentSliderValue:Float = 0.5 { willSet(newSliderValue) { switch (currentFilterOperation!.sliderConfiguration) { case .enabled: currentFilterOperation!.updateBasedOnSliderValue(newSliderValue) case .disabled: break } } } var currentFilterOperation: FilterOperationInterface? var videoCamera:Camera! lazy var blendImage:PictureInput = { return PictureInput(imageName:blendImageName) }() var currentlySelectedRow = 1 override func windowDidLoad() { super.windowDidLoad() do { videoCamera = try Camera(sessionPreset:AVCaptureSessionPreset1280x720) videoCamera.runBenchmark = true videoCamera.startCapture() } catch { fatalError("Couldn't initialize camera with error: \(error)") } self.changeSelectedRow(0) } func changeSelectedRow(_ row:Int) { guard (currentlySelectedRow != row) else { return } currentlySelectedRow = row // Clean up everything from the previous filter selection first // videoCamera.stopCapture() videoCamera.removeAllTargets() currentFilterOperation?.filter.removeAllTargets() currentFilterOperation?.secondInput?.removeAllTargets() currentFilterOperation = filterOperations[row] switch currentFilterOperation!.filterOperationType { case .singleInput: videoCamera.addTarget((currentFilterOperation!.filter)) currentFilterOperation!.filter.addTarget(filterView!) case .blend: blendImage.removeAllTargets() videoCamera.addTarget((currentFilterOperation!.filter)) self.blendImage.addTarget((currentFilterOperation!.filter)) currentFilterOperation!.filter.addTarget(filterView!) self.blendImage.processImage() case let .custom(filterSetupFunction:setupFunction): currentFilterOperation!.configureCustomFilter(setupFunction(videoCamera!, currentFilterOperation!.filter, filterView!)) } switch currentFilterOperation!.sliderConfiguration { case .disabled: filterSlider.isEnabled = false // case let .Enabled(minimumValue, initialValue, maximumValue, filterSliderCallback): case let .enabled(minimumValue, maximumValue, initialValue): filterSlider.minValue = Double(minimumValue) filterSlider.maxValue = Double(maximumValue) filterSlider.isEnabled = true currentSliderValue = initialValue } videoCamera.startCapture() } // MARK: - // MARK: Table view delegate and datasource methods func numberOfRowsInTableView(_ aTableView:NSTableView!) -> Int { return filterOperations.count } func tableView(_ aTableView:NSTableView!, objectValueForTableColumn aTableColumn:NSTableColumn!, row rowIndex:Int) -> AnyObject! { let filterInList:FilterOperationInterface = filterOperations[rowIndex] return filterInList.listName as NSString } func tableViewSelectionDidChange(_ aNotification: Notification!) { if let currentTableView = aNotification.object as? NSTableView { let rowIndex = currentTableView.selectedRow self.changeSelectedRow(rowIndex) } } }
apache-2.0
06e3bcd7772a879165fb663c13c7a8b4
37.090909
135
0.65659
6.043269
false
false
false
false
romaonthego/TableViewDataManager
Source/Classes/Components/TableViewFormCell.swift
1
3785
// // TableViewFormCell.swift // TableViewDataManager // // Copyright (c) 2016 Roman Efimov (https://github.com/romaonthego) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public class TableViewFormCell: TableViewCell { @IBOutlet var labelCenterYConstraint: NSLayoutConstraint? @IBOutlet var labelRightMarginConstraint: NSLayoutConstraint? @IBOutlet var labelWidthConstraint: NSLayoutConstraint? @IBOutlet public private(set) var titleLabel: UILabel? public override func cellWillAppear() { updateActionBarNavigationControl() self.selectionStyle = .None guard let titleLabel = self.titleLabel else { return } titleLabel.text = self.item.text if let labelRightMarginConstraint = self.labelRightMarginConstraint { if let text = self.item.text where text.characters.count > 0 { labelRightMarginConstraint.constant = 13 } else { labelRightMarginConstraint.constant = 0 } } } public override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if let responder = self.responder() where selected { responder.becomeFirstResponder() } } public override func updateConstraints() { super.updateConstraints() guard let titleLabel = self.titleLabel else { return } self.updateTitleLabelConstraints(titleLabel) } private func updateTitleLabelConstraints(titleLabel: UILabel) { if let labelWidthConstraint = self.labelWidthConstraint { if self.item.text != nil && self.item is TableViewFormItem { var minWidth: Float = 0 for item in self.section.items { if let text = item.text where item is TableViewFormItem { let width = Float(NSString(string: text).boundingRectWithSize(CGSize(width: self.frame.size.width, height: CGFloat(DBL_MAX)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: titleLabel.font], context: nil).size.width) minWidth = max(width, minWidth) } } labelWidthConstraint.constant = CGFloat(minWidth) } else { labelWidthConstraint.constant = 0 } } // Fix label center Y // if let labelCenterYConstraint = self.labelCenterYConstraint { labelCenterYConstraint.constant = 0.5 } } }
mit
1cde2657225a34e7a3ed87a23b7cbf7a
38.842105
149
0.648349
5.353607
false
false
false
false
BENMESSAOUD/RSS
News/Manager/RSSKeyDescription.swift
1
642
// // RSSKeyDescription.swift // News // // Created by Mahmoud Ben Messaoud on 17/03/2017. // Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved. // import Foundation enum ChannelKeys : String { case name = "channel" case title = "title" case description = "description" case link = "link" case date = "pubDate" case image = "image" case imageUrl = "url" case items = "items" } enum ItemKeys : String { case name = "item" case title = "title" case description = "description" case link = "link" case date = "pubDate" case image = "enclosure" case imageUrl = "url" }
mit
e793759f390ecce6acdd9615ac25c8bb
20.366667
63
0.628705
3.642045
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/CouponMapViewController.swift
1
9010
// // CouponMapViewController.swift // Wuakup // // Created by Guillermo Gutiérrez on 08/01/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import UIKit import MapKit @IBDesignable open class CouponMapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var loadingIndicatorView: ScissorsLoadingView! let numberOfCouponsToCenter = 5 open var coupons: [Coupon] = [Coupon]() open var selectedCoupon: Coupon? open var userLocation: CLLocation? open var allowDetailsNavigation = false var selectedAnnotation: CouponAnnotation? { get { return selectedCoupon.map{ self.annotations[$0.id] } ?? .none } } // Used to customize and filter the offer query open var filterOptions: FilterOptions? open var loadCouponsOnRegionChange = false fileprivate var shouldLoad = false fileprivate var lastRequestCenter: CLLocationCoordinate2D? fileprivate var annotations = [Int: CouponAnnotation]() fileprivate var loading: Bool = false { didSet { self.loadingIndicatorView.isHidden = false UIView.animate(withDuration: 0.3, animations: { self.loadingIndicatorView?.alpha = self.loading ? 1 : 0 return }) } } let selectionSpan = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05) let offersService = OffersService.sharedInstance required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: View lifecycle override open func viewDidLoad() { super.viewDidLoad() refreshUI() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) mapView?.showsUserLocation = true loadingIndicatorView.isHidden = true loadingIndicatorView?.alpha = 0 if let navigationController = navigationController { loadingIndicatorView.fillColor = navigationController.navigationBar.tintColor } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !shouldLoad { if let coupon = selectedCoupon { selectCoupon(coupon, animated: true) } else { centerInSelection(animated) } } // Ignore first animations delay(2) { self.shouldLoad = true return } } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) mapView?.showsUserLocation = false } // MARK: Private Methods func refreshUI() { mapView?.removeAnnotations(mapView.annotations) annotations.removeAll(keepingCapacity: false) for coupon in coupons { guard coupon.store?.location() != nil else { continue } let annotation = CouponAnnotation(coupon: coupon) mapView?.addAnnotation(annotation) annotations[coupon.id] = annotation } } func reloadCoupons() { guard let mapView = mapView else { return } let center = mapView.region.center let span = mapView.region.span let corner = CLLocation(latitude: center.latitude + span.latitudeDelta / 2, longitude: center.longitude + span.longitudeDelta / 2) let radius = corner.distance(from: center.toLocation()) self.lastRequestCenter = center self.loading = true NSLog("Requesting coupons for center %f, %f with radius %f meters", center.latitude, center.longitude, radius) offersService.findStoreOffers(nearLocation: center, radius: radius, sensor: false, filterOptions: filterOptions, completion: { (coupons, error) -> Void in self.loading = false if let error = error { NSLog("Error loading coupons: \(error)") } else { // Add only offers from new stores let storeIds = self.coupons.map{ $0.store?.id ?? -1 } let newCoupons = (coupons ?? [Coupon]()).filter{ !storeIds.contains($0.store?.id ?? 0) } let annotations = newCoupons.map{ CouponAnnotation(coupon: $0) } self.coupons += newCoupons mapView.addAnnotations(annotations) } }) } func selectCoupon(_ coupon: Coupon, animated: Bool = false) { selectedCoupon = coupon guard let annotation = self.annotations[coupon.id] else { return } self.centerInAnnotations([annotation], animated: animated) delay(1) { self.mapView?.selectAnnotation(annotation, animated: animated) return } } func centerInSelection(_ animated: Bool) { var annotations = [CouponAnnotation]() if let selectedAnnotation = self.selectedAnnotation { annotations = [selectedAnnotation] } else if (self.annotations.count > 0) { let limit = min(self.annotations.count, numberOfCouponsToCenter) annotations = Array(self.annotations.values.prefix(limit)) } centerInAnnotations(annotations, animated: animated) } func centerInCoordinate(_ coordinate: CLLocationCoordinate2D, animated: Bool) { let region = MKCoordinateRegion(center: coordinate, span: selectionSpan) self.mapView?.setRegion(region, animated: animated) } func centerInAnnotations(_ annotations: [CouponAnnotation], animated: Bool) { if annotations.count > 0 { mapView?.showAnnotations(annotations, animated: animated) } } // MARK: Actions func showDetails(forOffer offer: Coupon) { let detailsStoryboardId = "couponDetails" let detailsVC = self.storyboard?.instantiateViewController(withIdentifier: detailsStoryboardId) as! CouponDetailsViewController detailsVC.userLocation = self.userLocation detailsVC.coupons = coupons detailsVC.selectedIndex = coupons.firstIndex(of: offer) ?? 0 self.navigationController?.pushViewController(detailsVC, animated: true) } // MARK: MKMapViewDelegate methods open func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { return (annotation as? CouponAnnotation).map { couponAnnotation in let identifier = "couponAnnotation" let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) ?? CouponAnnotationView(annotation: couponAnnotation, reuseIdentifier: identifier) annotationView.layoutSubviews() annotationView.annotation = couponAnnotation annotationView.canShowCallout = true if couponAnnotation.coupon.company.logo?.sourceUrl != nil { if !(annotationView.leftCalloutAccessoryView is UIImageView) { let imageView = UIImageView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 52, height: 52))) imageView.contentMode = .scaleAspectFit annotationView.leftCalloutAccessoryView = imageView } } else { annotationView.leftCalloutAccessoryView = nil } if allowDetailsNavigation { let button = UIButton(type: .detailDisclosure) annotationView.rightCalloutAccessoryView = button } annotationView.setNeedsLayout() return annotationView } } open func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let annotation = view.annotation as? CouponAnnotation { showDetails(forOffer: annotation.coupon) } } open func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { guard let annotation = view.annotation as? CouponAnnotation, let imageView = view.leftCalloutAccessoryView as? UIImageView, let logoUrl = annotation.coupon.company.logo?.sourceUrl else { return } imageView.sd_setImage(with: logoUrl) } open func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { // NSLog("Region changed with new center: %f, %f", mapView.region.center.latitude, mapView.region.center.longitude) if loadCouponsOnRegionChange && shouldLoad { let center = mapView.region.center delay(0.5) { // If center hasn't changed in X seconds, reload results if center.isEqualTo(mapView.region.center) { self.reloadCoupons() } } } } }
mit
bfa9d6a01f6cc67f9063dcdd7c1b4470
37.5
181
0.627484
5.427108
false
false
false
false
voidException/ActiveLabel.swift
ActiveLabelDemo/ViewController.swift
10
1858
// // ViewController.swift // ActiveLabelDemo // // Created by Johannes Schickling on 9/4/15. // Copyright © 2015 Optonaut. All rights reserved. // import UIKit import ActiveLabel class ViewController: UIViewController { let label = ActiveLabel() override func viewDidLoad() { super.viewDidLoad() label.text = "This is a post with #multiple #hashtags and a @userhandle. Links are also supported like this one: http://optonaut.co." label.numberOfLines = 0 label.lineSpacing = 4 label.textColor = UIColor(red: 102.0/255, green: 117.0/255, blue: 127.0/255, alpha: 1) label.hashtagColor = UIColor(red: 85.0/255, green: 172.0/255, blue: 238.0/255, alpha: 1) label.mentionColor = UIColor(red: 238.0/255, green: 85.0/255, blue: 96.0/255, alpha: 1) label.URLColor = UIColor(red: 85.0/255, green: 238.0/255, blue: 151.0/255, alpha: 1) label.handleMentionTap { self.alert("Mention", message: $0) } label.handleHashtagTap { self.alert("Hashtag", message: $0) } label.handleURLTap { self.alert("URL", message: $0.description) } label.frame = CGRect(x: 20, y: 40, width: view.frame.width - 40, height: 300) view.addSubview(label) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func alert(title: String, message: String) { let vc = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) vc.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: nil)) presentViewController(vc, animated: true, completion: nil) } }
mit
cf3448adad5c59d39a8a88e31319d3a2
35.411765
141
0.640819
3.901261
false
false
false
false
sgerguri/mal
swift/reader.swift
23
7081
//****************************************************************************** // MAL - reader //****************************************************************************** import Foundation let kSymbolWithMeta = MalSymbol(symbol: "with-meta") let kSymbolDeref = MalSymbol(symbol: "deref") let token_pattern = "[[:space:],]*" + // Skip whitespace: a sequence of zero or more commas or [:space:]'s "(" + "~@" + // Literal "~@" "|" + "[\\[\\]{}()`'~^@]" + // Punctuation: Any one of []{}()`'~^@ "|" + "\"(?:\\\\.|[^\\\\\"])*\"" + // Quoted string: characters other than \ or ", or any escaped characters "|" + ";.*" + // Comment: semicolon followed by anything "|" + "[^[:space:]\\[\\]{}()`'\",;]*" + // Symbol, keyword, number, nil, true, false: any sequence of chars but [:space:] or []{}()`'",; ")" let atom_pattern = "(^;.*$)" + // Comment "|" + "(^-?[0-9]+$)" + // Integer "|" + "(^-?[0-9][0-9.]*$)" + // Float "|" + "(^nil$)" + // nil "|" + "(^true$)" + // true "|" + "(^false$)" + // false "|" + "(^\".*\"$)" + // String "|" + "(:.*)" + // Keyword "|" + "(^[^\"]*$)" // Symbol var token_regex: NSRegularExpression = NSRegularExpression(pattern:token_pattern, options:.allZeros, error:nil)! var atom_regex: NSRegularExpression = NSRegularExpression(pattern:atom_pattern, options:.allZeros, error:nil)! class Reader { init(_ tokens: [String]) { self.tokens = tokens self.index = 0 } func next() -> String? { let token = peek() increment() return token } func peek() -> String? { if index < tokens.count { return tokens[index] } return nil } private func increment() { ++index } private let tokens: [String] private var index: Int } func tokenizer(s: String) -> [String] { var tokens = [String]() let range = NSMakeRange(0, count(s.utf16)) let matches = token_regex.matchesInString(s, options:.allZeros, range:range) for match in matches as! [NSTextCheckingResult] { if match.range.length > 0 { let token = (s as NSString).substringWithRange(match.rangeAtIndex(1)) tokens.append(token) } } return tokens } private func have_match_at(match: NSTextCheckingResult, index:Int) -> Bool { return Int64(match.rangeAtIndex(index).location) < LLONG_MAX } func read_atom(token: String) -> MalVal { let range = NSMakeRange(0, count(token.utf16)) let matches = atom_regex.matchesInString(token, options:.allZeros, range:range) for match in matches as! [NSTextCheckingResult] { if have_match_at(match, 1) { // Comment return MalComment(comment: token) } else if have_match_at(match, 2) { // Integer if let value = NSNumberFormatter().numberFromString(token)?.longLongValue { return MalInteger(value: value) } return MalError(message: "invalid integer: \(token)") } else if have_match_at(match, 3) { // Float if let value = NSNumberFormatter().numberFromString(token)?.doubleValue { return MalFloat(value: value) } return MalError(message: "invalid float: \(token)") } else if have_match_at(match, 4) { // nil return MalNil() } else if have_match_at(match, 5) { // true return MalTrue() } else if have_match_at(match, 6) { // false return MalFalse() } else if have_match_at(match, 7) { // String return MalString(escaped: token) } else if have_match_at(match, 8) { // Keyword return MalKeyword(keyword: dropFirst(token)) } else if have_match_at(match, 9) { // Symbol return MalSymbol(symbol: token) } } return MalError(message: "Unknown token=\(token)") } func read_elements(r: Reader, open: String, close: String) -> ([MalVal]?, MalVal?) { var list = [MalVal]() while let token = r.peek() { if token == close { r.increment() // Consume the closing paren return (list, nil) } else { let item = read_form(r) if is_error(item) { return (nil, item) } if item.type != .TypeComment { list.append(item) } } } return (nil, MalError(message: "ran out of tokens -- possibly unbalanced ()'s")) } func read_list(r: Reader) -> MalVal { let (list, err) = read_elements(r, "(", ")") return err != nil ? err! : MalList(array: list!) } func read_vector(r: Reader) -> MalVal { let (list, err) = read_elements(r, "[", "]") return err != nil ? err! : MalVector(array: list!) } func read_hashmap(r: Reader) -> MalVal { let (list, err) = read_elements(r, "{", "}") return err != nil ? err! : MalHashMap(array: list!) } func common_quote(r: Reader, symbol: String) -> MalVal { let next = read_form(r) if is_error(next) { return next } return MalList(objects: MalSymbol(symbol: symbol), next) } func read_form(r: Reader) -> MalVal { if let token = r.next() { switch token { case "(": return read_list(r) case ")": return MalError(message: "unexpected \")\"") case "[": return read_vector(r) case "]": return MalError(message: "unexpected \"]\"") case "{": return read_hashmap(r) case "}": return MalError(message: "unexpected \"}\"") case "`": return common_quote(r, "quasiquote") case "'": return common_quote(r, "quote") case "~": return common_quote(r, "unquote") case "~@": return common_quote(r, "splice-unquote") case "^": let meta = read_form(r) if is_error(meta) { return meta } let form = read_form(r) if is_error(form) { return form } return MalList(objects: kSymbolWithMeta, form, meta) case "@": let form = read_form(r) if is_error(form) { return form } return MalList(objects: kSymbolDeref, form) default: return read_atom(token) } } return MalError(message: "ran out of tokens -- possibly unbalanced ()'s") } func read_str(s: String) -> MalVal { let tokens = tokenizer(s) let reader = Reader(tokens) let obj = read_form(reader) return obj }
mpl-2.0
e1c304760ac1d817569b1e6edc1fc5d0
32.880383
140
0.487784
4.219905
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/PresentationLayer/Wallet/Receive/View/ReceiveViewController.swift
1
1559
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit class ReceiveViewController: UIViewController { @IBOutlet var addressLabel: UILabel! @IBOutlet var qrImageView: UIImageView! @IBOutlet var copyAddressButton: UIButton! @IBOutlet var addressTitleLabel: UILabel! var output: ReceiveViewOutput! // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() output.viewIsReady() localize() } // MARK: Privates private func localize() { navigationItem.title = Localized.receiveTitle() addressTitleLabel.text = Localized.receiveAddressTitle() copyAddressButton.setTitle(Localized.receiveCopyButton(), for: .normal) } // MARK: Actions @IBAction func copyAddressPressed() { guard let address = addressLabel.text else { return } output.copyAddressPressed(address: address) } @IBAction func sharePressed(_ sender: UIBarButtonItem) { let text = addressLabel.text! let image = qrImageView.image! let activity = UIActivityViewController(activityItems: [image, text], applicationActivities: nil) activity.excludedActivityTypes = [.print, .assignToContact] present(activity, animated: true, completion: nil) } } // MARK: - ReceiveViewInput extension ReceiveViewController: ReceiveViewInput { func didReceiveWallet(_ wallet: Wallet) { addressLabel.text = wallet.address } func didReceiveQRImage(_ image: UIImage) { qrImageView.image = image } func setupInitialState() { } }
gpl-3.0
8bdad65244e09a6e65669f059045452a
22.253731
101
0.716945
4.692771
false
false
false
false
VladiMihaylenko/omim
iphone/Maps/Classes/CarPlay/CarPlayRouter.swift
1
11690
import CarPlay import Contacts @available(iOS 12.0, *) protocol CarPlayRouterListener: class { func didCreateRoute(routeInfo: RouteInfo, trip: CPTrip) func didUpdateRouteInfo(_ routeInfo: RouteInfo, forTrip trip: CPTrip) func didFailureBuildRoute(forTrip trip: CPTrip, code: RouterResultCode, countries: [String]) func routeDidFinish(_ trip: CPTrip) } @available(iOS 12.0, *) @objc(MWMCarPlayRouter) final class CarPlayRouter: NSObject { private let listenerContainer: ListenerContainer<CarPlayRouterListener> private var routeSession: CPNavigationSession? private var initialSpeedCamSettings: SpeedCameraManagerMode var currentTrip: CPTrip? { return routeSession?.trip } var previewTrip: CPTrip? var speedCameraMode: SpeedCameraManagerMode { return RoutingManager.routingManager.speedCameraMode } override init() { listenerContainer = ListenerContainer<CarPlayRouterListener>() initialSpeedCamSettings = RoutingManager.routingManager.speedCameraMode super.init() } func addListener(_ listener: CarPlayRouterListener) { listenerContainer.addListener(listener) } func removeListener(_ listener: CarPlayRouterListener) { listenerContainer.removeListener(listener) } func subscribeToEvents() { RoutingManager.routingManager.add(self) } func unsubscribeFromEvents() { RoutingManager.routingManager.remove(self) } func completeRouteAndRemovePoints() { let manager = RoutingManager.routingManager manager.stopRoutingAndRemoveRoutePoints(true) manager.deleteSavedRoutePoints() manager.apply(routeType: .vehicle) previewTrip = nil } func rebuildRoute() { guard let trip = previewTrip else { return } do { try RoutingManager.routingManager.buildRoute() } catch let error as NSError { listenerContainer.forEach({ let code = RouterResultCode(rawValue: UInt(error.code)) ?? .internalError $0.didFailureBuildRoute(forTrip: trip, code: code, countries: []) }) } } func buildRoute(trip: CPTrip) { completeRouteAndRemovePoints() previewTrip = trip guard let info = trip.userInfo as? [String: MWMRoutePoint] else { listenerContainer.forEach({ $0.didFailureBuildRoute(forTrip: trip, code: .routeNotFound, countries: []) }) return } guard let startPoint = info[CPConstants.Trip.start], let endPoint = info[CPConstants.Trip.end] else { listenerContainer.forEach({ var code: RouterResultCode! if info[CPConstants.Trip.end] == nil { code = .endPointNotFound } else { code = .startPointNotFound } $0.didFailureBuildRoute(forTrip: trip, code: code, countries: []) }) return } let manager = RoutingManager.routingManager manager.add(routePoint: startPoint) manager.add(routePoint: endPoint) do { try manager.buildRoute() } catch let error as NSError { listenerContainer.forEach({ let code = RouterResultCode(rawValue: UInt(error.code)) ?? .internalError $0.didFailureBuildRoute(forTrip: trip, code: code, countries: []) }) } } func updateStartPointAndRebuild(trip: CPTrip) { let manager = RoutingManager.routingManager previewTrip = trip guard let info = trip.userInfo as? [String: MWMRoutePoint] else { listenerContainer.forEach({ $0.didFailureBuildRoute(forTrip: trip, code: .routeNotFound, countries: []) }) return } guard let startPoint = info[CPConstants.Trip.start] else { listenerContainer.forEach({ $0.didFailureBuildRoute(forTrip: trip, code: .startPointNotFound, countries: []) }) return } manager.add(routePoint: startPoint) manager.apply(routeType: .vehicle) do { try manager.buildRoute() } catch let error as NSError { listenerContainer.forEach({ let code = RouterResultCode(rawValue: UInt(error.code)) ?? .internalError $0.didFailureBuildRoute(forTrip: trip, code: code, countries: []) }) } } func startRoute() { let manager = RoutingManager.routingManager manager.startRoute() } func setupCarPlaySpeedCameraMode() { if case .auto = initialSpeedCamSettings { RoutingManager.routingManager.speedCameraMode = .always } } func setupInitialSpeedCameraMode() { RoutingManager.routingManager.speedCameraMode = initialSpeedCamSettings } func updateSpeedCameraMode(_ mode: SpeedCameraManagerMode) { initialSpeedCamSettings = mode RoutingManager.routingManager.speedCameraMode = mode } func restoreTripPreviewOnCarplay(beforeRootTemplateDidAppear: Bool) { guard MWMRouter.isRestoreProcessCompleted() else { DispatchQueue.main.async { [weak self] in self?.restoreTripPreviewOnCarplay(beforeRootTemplateDidAppear: false) } return } let manager = RoutingManager.routingManager MWMRouter.hideNavigationMapControls() guard manager.isRoutingActive, let startPoint = manager.startPoint, let endPoint = manager.endPoint else { completeRouteAndRemovePoints() return } let trip = createTrip(startPoint: startPoint, endPoint: endPoint, routeInfo: manager.routeInfo) previewTrip = trip if manager.type != .vehicle { CarPlayService.shared.showRecoverRouteAlert(trip: trip, isTypeCorrect: false) return } if !startPoint.isMyPosition { CarPlayService.shared.showRecoverRouteAlert(trip: trip, isTypeCorrect: true) return } if beforeRootTemplateDidAppear { CarPlayService.shared.preparedToPreviewTrips = [trip] } else { CarPlayService.shared.preparePreview(trips: [trip]) } } func restoredNavigationSession() -> (CPTrip, RouteInfo)? { let manager = RoutingManager.routingManager if manager.isOnRoute, manager.type == .vehicle, let startPoint = manager.startPoint, let endPoint = manager.endPoint, let routeInfo = manager.routeInfo { MWMRouter.hideNavigationMapControls() let trip = createTrip(startPoint: startPoint, endPoint: endPoint, routeInfo: routeInfo) previewTrip = trip return (trip, routeInfo) } return nil } } // MARK: - Navigation session management @available(iOS 12.0, *) extension CarPlayRouter { func startNavigationSession(forTrip trip: CPTrip, template: CPMapTemplate) { routeSession = template.startNavigationSession(for: trip) routeSession?.pauseTrip(for: .loading, description: nil) updateUpcomingManeuvers() } func cancelTrip() { routeSession?.cancelTrip() routeSession = nil completeRouteAndRemovePoints() } func finishTrip() { routeSession?.finishTrip() routeSession = nil completeRouteAndRemovePoints() } func updateUpcomingManeuvers() { let maneuvers = createUpcomingManeuvers() routeSession?.upcomingManeuvers = maneuvers } private func createUpcomingManeuvers() -> [CPManeuver] { guard let routeInfo = RoutingManager.routingManager.routeInfo else { return [] } var maneuvers = [CPManeuver]() let primaryManeuver = CPManeuver() primaryManeuver.userInfo = CPConstants.Maneuvers.primary primaryManeuver.instructionVariants = [routeInfo.streetName] if let imageName = routeInfo.turnImageName, let symbol = UIImage(named: imageName) { primaryManeuver.symbolSet = CPImageSet(lightContentImage: symbol, darkContentImage: symbol) } if let distance = Double(routeInfo.distanceToTurn) { let measurement = Measurement(value: distance, unit: routeInfo.turnUnits) let estimates = CPTravelEstimates(distanceRemaining: measurement, timeRemaining: 0.0) primaryManeuver.initialTravelEstimates = estimates } maneuvers.append(primaryManeuver) if let imageName = routeInfo.nextTurnImageName, let symbol = UIImage(named: imageName) { let secondaryManeuver = CPManeuver() secondaryManeuver.userInfo = CPConstants.Maneuvers.secondary secondaryManeuver.instructionVariants = [L("then_turn")] secondaryManeuver.symbolSet = CPImageSet(lightContentImage: symbol, darkContentImage: symbol) maneuvers.append(secondaryManeuver) } return maneuvers } func createTrip(startPoint: MWMRoutePoint, endPoint: MWMRoutePoint, routeInfo: RouteInfo? = nil) -> CPTrip { let startPlacemark = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: startPoint.latitude, longitude: startPoint.longitude)) let endPlacemark = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: endPoint.latitude, longitude: endPoint.longitude), addressDictionary: [CNPostalAddressStreetKey: endPoint.subtitle]) let startItem = MKMapItem(placemark: startPlacemark) let endItem = MKMapItem(placemark: endPlacemark) endItem.name = endPoint.title let routeChoice = CPRouteChoice(summaryVariants: [" "], additionalInformationVariants: [], selectionSummaryVariants: []) routeChoice.userInfo = routeInfo let trip = CPTrip(origin: startItem, destination: endItem, routeChoices: [routeChoice]) trip.userInfo = [CPConstants.Trip.start: startPoint, CPConstants.Trip.end: endPoint] return trip } } // MARK: - RoutingManagerListener implementation @available(iOS 12.0, *) extension CarPlayRouter: RoutingManagerListener { func updateCameraInfo(isCameraOnRoute: Bool, speedLimit limit: String?) { CarPlayService.shared.updateCameraUI(isCameraOnRoute: isCameraOnRoute, speedLimit: limit) } func processRouteBuilderEvent(with code: RouterResultCode, countries: [String]) { guard let trip = previewTrip else { return } switch code { case .noError, .hasWarnings: let manager = RoutingManager.routingManager if manager.isRouteFinished { listenerContainer.forEach({ $0.routeDidFinish(trip) }) return } if let info = manager.routeInfo { previewTrip?.routeChoices.first?.userInfo = info if routeSession == nil { listenerContainer.forEach({ $0.didCreateRoute(routeInfo: info, trip: trip) }) } else { listenerContainer.forEach({ $0.didUpdateRouteInfo(info, forTrip: trip) }) } } default: listenerContainer.forEach({ $0.didFailureBuildRoute(forTrip: trip, code: code, countries: countries) }) } } func didLocationUpdate(_ notifications: [String]) { guard let trip = previewTrip else { return } let manager = RoutingManager.routingManager if manager.isRouteFinished { listenerContainer.forEach({ $0.routeDidFinish(trip) }) return } guard let routeInfo = manager.routeInfo, manager.isRoutingActive else { return } listenerContainer.forEach({ $0.didUpdateRouteInfo(routeInfo, forTrip: trip) }) let tts = MWMTextToSpeech.tts()! if manager.isOnRoute && tts.active { tts.playTurnNotifications(notifications) tts.playWarningSound() } } }
apache-2.0
7a4bbc5d71b3f9d39687177819698822
32.688761
124
0.669461
4.95549
false
false
false
false
DeKoServidoni/MiniTLC
MiniTLC-iOS/MiniTLC/MiniTLC/SidePanelViewController.swift
1
5201
// // SidePanelViewController.swift // MiniTLC // // Created by DeKo Servidoni on 3/1/16. // Copyright © 2016 DeKo Servidoni. All rights reserved. // import Foundation import UIKit protocol SidePanelViewControllerDelegate { func openViewController(controller: UIViewController!) } class SidePanelViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: Class attributes var menuSection0: [String] = ["Início"] var menuSection1: [String] = ["Tirar foto!"] var menuSection2: [String] = ["Fale conosco!", "Sobre"] var iconSection0: [String] = ["icon_home"] var iconSection1: [String] = ["icon_camera"] var iconSection2: [String] = ["icon_talk_with_us", "icon_about"] var delegate: SidePanelViewControllerDelegate? var loadedStoryboard: UIStoryboard? // MARK: Class constants let NUMBER_OF_SECTIONS = 3 // MARK: Lifecycle functions override func viewDidLoad() { super.viewDidLoad() loadedStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) } // MARK: Table view delegate functions func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var quantity = menuSection0.count if section == 1 { quantity = menuSection1.count } else if section == 2 { quantity = menuSection2.count } return quantity } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return (section == 0) ? 0 : 2 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return NUMBER_OF_SECTIONS } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("MenuItemIdentifier") as? SlideMenuCell if cell == nil { let array = NSBundle.mainBundle().loadNibNamed("SlideMenuCell", owner: self, options: nil) cell = array[0] as? SlideMenuCell } var itemText = "" var itemImage = "" if indexPath.section == 0 { itemImage = iconSection0[indexPath.row] itemText = menuSection0[indexPath.row] } else if indexPath.section == 1 { itemImage = iconSection1[indexPath.row] itemText = menuSection1[indexPath.row] } else { itemImage = iconSection2[indexPath.row] itemText = menuSection2[indexPath.row] } cell!.icon.image = UIImage(named: itemImage) cell!.label.text = itemText return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var controller: UIViewController? switch indexPath.section { case 0: controller = selectItemFromSection0(indexPath.row) break case 1: controller = selectItemFromSection1(indexPath.row) break case 2: selectItemFromSection2(indexPath.row) break default: // do nothing break } if controller != nil { delegate?.openViewController(controller) } } // MARK: Private functions // Select the desired view from the first section private func selectItemFromSection0(index: Int) -> UIViewController? { var controller: UIViewController? switch index { case 0: /** HOME **/ controller = loadedStoryboard!.instantiateViewControllerWithIdentifier("HomeViewController") as? HomeViewController break default: // do nothing break } return controller } // Select the desired view from second section private func selectItemFromSection1(index: Int) -> UIViewController? { var controller: UIViewController? switch index { case 0: /** PICTURE CHOOSER **/ controller = loadedStoryboard!.instantiateViewControllerWithIdentifier("PictureChooserViewController") as? PictureChooserViewController break default: // do nothing break } return controller } // Select the desired view from the last section private func selectItemFromSection2(index: Int) { switch index { case 0: /** TALK WITH US **/ let url = NSURL(string: "mailto:[email protected]") UIApplication.sharedApplication().openURL(url!) break default: // do nothing break } } }
apache-2.0
ab6a2b302fa5a2f2e4c5f02e0876fe65
27.729282
151
0.563378
5.694414
false
false
false
false
Mamadoukaba/Chillapp
Chillapp/WebviewViewController.swift
1
3066
// // WebviewViewController.swift // Chillapp // // Created by Mamadou Kaba on 8/3/15. // Copyright (c) 2015 Mamadou Kaba. All rights reserved. // import UIKit import THContactPicker import AddressBook import AddressBookUI import MessageUI import SwiftyJSON class WebviewViewController: UIViewController { @IBOutlet weak var urlPage: UIWebView! var URLPath = "http://google.com" override func viewDidLoad() { super.viewDidLoad() loadAdressURL() navigationController?.setNavigationBarHidden(false, animated: true) UINavigationBar.appearance().barTintColor = UIColor.whiteColor() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default } override func viewWillAppear(animated: Bool) { //UIApplication.sharedApplication().statusBarStyle = .LightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func function(string: String) -> String { return string + "ok" } func loadAdressURL() { let requestURL = NSURL (string: URLPath) let request = NSURLRequest(URL: requestURL!) urlPage.loadRequest(request) } @IBAction func contactButton(sender: UIButton) { var picker: ABPeoplePickerNavigationController = ABPeoplePickerNavigationController() picker.peoplePickerDelegate = self self.presentViewController(picker, animated: true, completion: nil) } } extension WebviewViewController: ABPeoplePickerNavigationControllerDelegate, MFMessageComposeViewControllerDelegate { func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecord!) { dismissViewControllerAnimated(true) { () -> Void in if !MFMessageComposeViewController.canSendText() { return } var messageVC = MFMessageComposeViewController() let unmanagedPhones = ABRecordCopyValue(person, kABPersonPhoneProperty) let phones: ABMultiValueRef = Unmanaged.fromOpaque(unmanagedPhones.toOpaque()).takeUnretainedValue() as NSObject as ABMultiValueRef let unmanagedPhone = ABMultiValueCopyValueAtIndex(phones, 0) let phone: String = Unmanaged.fromOpaque(unmanagedPhone.toOpaque()).takeUnretainedValue() as NSObject as! String messageVC.body = selectedVenue messageVC.recipients = [phone] messageVC.messageComposeDelegate = self; self.presentViewController(messageVC, animated: false, completion: nil) } } func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { dismissViewControllerAnimated(true, completion: nil) } }
mit
10cb6e009c4b002e0633563d64f4c779
32.336957
134
0.681344
5.896154
false
false
false
false
devpunk/velvet_room
Source/Model/Vita/MVitaPtpPackProtocolDefaultValues.swift
1
422
import Foundation struct MVitaPtpPackProtocolDefaultValues { static let kThumbFormat:UInt32 = 0 static let kThumbCompressedSize:UInt32 = 0 static let kThumbWith:UInt32 = 0 static let kThumbHeight:UInt32 = 0 static let kImageWith:UInt32 = 0 static let kImageHeight:UInt32 = 0 static let kImageBitDepth:UInt32 = 0 static let kSequenceNumber:UInt32 = 0 static let kTerminate:UInt16 = 0 }
mit
f2947bbbd387febac3be58306afbf340
29.142857
46
0.744076
3.907407
false
false
false
false
SimplicityMobile/Simplicity
Simplicity/OAuth2Error.swift
2
3508
// // OAuth2Error.swift // Simplicity // // Created by Edward Jiang on 5/17/16. // Copyright © 2016 Stormpath. All rights reserved. // import Foundation /** An OAuth 2 Error response. Subclass of LoginError. Error codes subject to change, so initialize a OAuth2ErrorCode enum with the raw value of the error code to check. */ public class OAuth2Error: LoginError { /// A mapping of OAuth 2 Error strings to OAuth2ErrorCode enum. public static let mapping: [String: OAuth2ErrorCode] = [ "invalid_request": .invalidRequest, "unauthorized_client": .unauthorizedClient, "access_denied": .accessDenied, "unsupported_response_type": .unsupportedResponseType, "invalid_scope": .invalidScope, "server_error": .serverError, "temporarily_unavailable": .temporarilyUnavailable ] /** Constructs a OAuth 2 error object from an OAuth response. - parameters: - callbackParameters: A dictionary of OAuth 2 Error response parameters. - returns: OAuth2Error object. */ public class func error(_ callbackParameters: [String: String]) -> LoginError? { let errorCode = mapping[callbackParameters["error"] ?? ""] if let errorCode = errorCode { let errorDescription = callbackParameters["error_description"]?.removingPercentEncoding?.replacingOccurrences(of: "+", with: " ") ?? errorCode.description return OAuth2Error(code: errorCode.rawValue, description: errorDescription) } else { return nil } } } /// OAuth 2 Error codes public enum OAuth2ErrorCode: Int, CustomStringConvertible { /** The request is missing a required parameter. This is usually programmer error, and should be filed as a GitHub issue. */ case invalidRequest = 100, /// The client ID is not authorized to make this request. unauthorizedClient, /// The user or OAuth server denied this request. accessDenied, /// The grant type requested is not supported. This is programmer error. unsupportedResponseType, /// A scope requested is invalid. invalidScope, /// The authorization server is currently experiencing an error. serverError, /// The authorization server is currently unavailable. temporarilyUnavailable /// User readable default error message public var description: String { switch self { case .invalidRequest: return "The OAuth request is missing a required parameter" case .unauthorizedClient: return "The client ID is not authorized to make this request" case .accessDenied: return "You denied the login request" case .unsupportedResponseType: return "The grant type requested is not supported" case .invalidScope: return "A scope requested is invalid" case .serverError: return "The login server experienced an internal error" case .temporarilyUnavailable: return "The login server is temporarily unavailable. Please try again later. " } } }
apache-2.0
d1df5a4bf73e7efd565e64ae314bb295
37.538462
166
0.600798
5.656452
false
false
false
false
ratreya/Lipika_IME
Input Source/ClientManager.swift
1
6405
/* * LipikaIME is a user-configurable phonetic Input Method Engine for Mac OS X. * Copyright (C) 2018 Ranganath Atreya * * 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. */ import InputMethodKit import LipikaEngine_OSX class ClientManager: CustomStringConvertible { private let notFoundRange = NSMakeRange(NSNotFound, NSNotFound) private let config = LipikaConfig() private let client: IMKTextInput private let candidatesWindow: IMKCandidates // This is the position of the cursor within the marked text public var markedCursorLocation: Int? = nil private (set) var candidates = [String]() // Cache, otherwise clients quitting can sometimes SEGFAULT us private var _description: String var description: String { return _description } private var attributes: [NSAttributedString.Key: Any]! { var rect = NSMakeRect(0, 0, 0, 0) return client.attributes(forCharacterIndex: 0, lineHeightRectangle: &rect) as? [NSAttributedString.Key : Any] } init(client: IMKTextInput) { Logger.log.debug("Initializing client: \(client.bundleIdentifier()!) with Id: \(client.uniqueClientIdentifierString()!)") self.client = client if !client.supportsUnicode() { Logger.log.warning("Client: \(client.bundleIdentifier()!) does not support Unicode!") } if !client.supportsProperty(TSMDocumentPropertyTag(kTSMDocumentSupportDocumentAccessPropertyTag)) { Logger.log.warning("Client: \(client.bundleIdentifier()!) does not support Document Access!") } candidatesWindow = IMKCandidates(server: (NSApp.delegate as! AppDelegate).server, panelType: kIMKSingleRowSteppingCandidatePanel) candidatesWindow.setAttributes([IMKCandidatesSendServerKeyEventFirst: NSNumber(booleanLiteral: true)]) _description = "\(client.bundleIdentifier()!) with Id: \(client.uniqueClientIdentifierString()!)" } func setGlobalCursorLocation(_ location: Int) { client.setMarkedText("|", selectionRange: NSMakeRange(0, 0), replacementRange: NSMakeRange(location, 0)) client.setMarkedText("", selectionRange: NSMakeRange(0, 0), replacementRange: NSMakeRange(location, 0)) } func updateMarkedCursorLocation(_ delta: Int) -> Bool { Logger.log.debug("Cursor moved: \(delta) with selectedRange: \(client.selectedRange()), markedRange: \(client.markedRange()) and cursorPosition: \(markedCursorLocation?.description ?? "nil")") if client.markedRange().length == NSNotFound { return false } let nextPosition = (markedCursorLocation ?? client.markedRange().length) + delta if (0...client.markedRange().length).contains(nextPosition) { Logger.log.debug("Still within markedRange") markedCursorLocation = nextPosition return true } Logger.log.debug("Outside of markedRange") markedCursorLocation = nil return false } func showActive(clientText: NSAttributedString, candidateText: String, replacementRange: NSRange? = nil) { Logger.log.debug("Showing clientText: \(clientText) and candidateText: \(candidateText)") client.setMarkedText(clientText, selectionRange: NSMakeRange(markedCursorLocation ?? clientText.length, 0), replacementRange: replacementRange ?? notFoundRange) candidates = [candidateText] if clientText.string.isEmpty { candidatesWindow.hide() } else { candidatesWindow.update() if config.showCandidates { candidatesWindow.show() } } } func finalize(_ output: String) { Logger.log.debug("Finalizing with: \(output)") client.insertText(output, replacementRange: notFoundRange) candidatesWindow.hide() markedCursorLocation = nil } func clear() { Logger.log.debug("Clearing MarkedText and Candidate window") client.setMarkedText("", selectionRange: NSMakeRange(0, 0), replacementRange: notFoundRange) candidatesWindow.hide() markedCursorLocation = nil } func findWord(at current: Int) -> NSRange? { let maxLength = client.length() var exponent = 2 var wordStart = -1, wordEnd = -1 Logger.log.debug("Finding word at: \(current) with max: \(maxLength)") repeat { let low = wordStart == -1 ? max(current - 2 << exponent, 0): wordStart let high = wordEnd == -1 ? min(current + 2 << exponent, maxLength): wordEnd Logger.log.debug("Looking for word between \(low) and \(high)") var real = NSRange() guard let text = client.string(from: NSMakeRange(low, high - low), actualRange: &real) else { return nil } Logger.log.debug("Looking for word in text: \(text)") if wordStart == -1, let startOffset = text.unicodeScalars[text.unicodeScalars.startIndex..<text.unicodeScalars.index(text.unicodeScalars.startIndex, offsetBy: current - real.location)].reversed().index(where: { CharacterSet.whitespacesAndNewlines.contains($0) })?.base.encodedOffset { wordStart = real.location + startOffset Logger.log.debug("Found wordStart: \(wordStart)") } if wordEnd == -1, let endOffset = text.unicodeScalars[text.unicodeScalars.index(text.unicodeScalars.startIndex, offsetBy: current - real.location)..<text.unicodeScalars.endIndex].index(where: { CharacterSet.whitespacesAndNewlines.contains($0) })?.encodedOffset { wordEnd = real.location + endOffset Logger.log.debug("Found wordEnd: \(wordEnd)") } exponent += 1 if wordStart == -1, low == 0 { wordStart = low Logger.log.debug("Starting word at beginning of document") } if wordEnd == -1, high == maxLength { wordEnd = high Logger.log.debug("Ending word at end of document") } } while(wordStart == -1 || wordEnd == -1) Logger.log.debug("Found word between \(wordStart) and \(wordEnd)") return NSMakeRange(wordStart, wordEnd - wordStart) } }
gpl-3.0
c040da6a538a69f3ffed63def01cef19
49.039063
296
0.656831
4.934515
false
false
false
false
vi4m/Zewo
Modules/Reflection/Tests/ReflectionTests/InternalTests.swift
2
3077
import XCTest @testable import Reflection public class InternalTests : XCTestCase { func testShallowMetadata() { func testShallowMetadata<T>(type: T.Type, expectedKind: Metadata.Kind) { let shallowMetadata = Metadata(type: type) XCTAssert(shallowMetadata.kind == expectedKind, "\(shallowMetadata.kind) does not match expected \(expectedKind)") XCTAssert(shallowMetadata.valueWitnessTable.size == sizeof(type)) XCTAssert(shallowMetadata.valueWitnessTable.stride == strideof(type)) } testShallowMetadata(type: Person.self, expectedKind: .struct) testShallowMetadata(type: Optional<Person>.self, expectedKind: .optional) testShallowMetadata(type: (String, Int).self, expectedKind: .tuple) testShallowMetadata(type: ((String) -> Int).self, expectedKind: .function) testShallowMetadata(type: Any.self, expectedKind: .existential) testShallowMetadata(type: String.Type.self, expectedKind: .metatype) testShallowMetadata(type: Any.Type.self, expectedKind: .existentialMetatype) testShallowMetadata(type: ReferencePerson.self, expectedKind: .class) } func testNominalMetadata() { func testMetadata<T : NominalType>(metadata: T, expectedName: String) { XCTAssert(metadata.nominalTypeDescriptor.numberOfFields == 3) XCTAssert(metadata.nominalTypeDescriptor.fieldNames == ["firstName", "lastName", "age"]) XCTAssertNotNil(metadata.nominalTypeDescriptor.fieldTypesAccessor) XCTAssert(metadata.fieldTypes! == [String.self, String.self, Int.self] as [Any.Type]) } if let metadata = Metadata.Struct(type: Person.self) { testMetadata(metadata: metadata, expectedName: "Person") } else { XCTFail() } if let metadata = Metadata.Class(type: ReferencePerson.self) { testMetadata(metadata: metadata, expectedName: "ReferencePerson") } else { XCTFail() } } func testTupleMetadata() { guard let metadata = Metadata.Tuple(type: (Int, name: String, Float, age: Int).self) else { return XCTFail() } for (label, expected) in zip(metadata.labels, [nil, "name", nil, "age"] as [String?]) { XCTAssert(label == expected) } } func testSuperclass() { guard let metadata = Metadata.Class(type: SubclassedPerson.self) else { return XCTFail() } XCTAssertNotNil(metadata.superclass) // ReferencePerson } } func == (lhs: [Any.Type], rhs: [Any.Type]) -> Bool { return zip(lhs, rhs).reduce(true) { $1.0 != $1.1 ? false : $0 } } extension InternalTests { public static var allTests: [(String, (InternalTests) -> () throws -> Void)] { return [ ("testShallowMetadata", testShallowMetadata), ("testNominalMetadata", testNominalMetadata), ("testTupleMetadata", testTupleMetadata), ("testSuperclass", testSuperclass), ] } }
mit
fee6b877243b051c980878009ca210fe
41.736111
126
0.641859
4.662121
false
true
false
false