repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
amrap-labs/TeamupKit
refs/heads/develop
Sources/TeamupKit/Requests/Objects/Request.swift
mit
1
// // Request.swift // TeamupKit // // Created by Merrick Sapsford on 13/06/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import Foundation import Alamofire public class Request { // MARK: Types /// The type of authentication for a request. /// /// - none: Use no authentication. /// - apiToken: Use the API token provided to Teamup. /// - userToken: Use the currently authenticated user's token. public enum Authentication { case none case apiToken case userToken } // MARK: Properties /// The URL for the request. let url: URL /// The method to use. let method: Alamofire.HTTPMethod /// The headers to send. let headers: Alamofire.HTTPHeaders? /// The parameters to send. let parameters: Alamofire.Parameters? /// The encoding to use. let encoding: Alamofire.ParameterEncoding? /// The response to the request. private(set) var response: Response? /// Whether the request is currently in progress. private(set) var inProgress: Bool = false // MARK: Init init(with url: URL, method: Alamofire.HTTPMethod, headers: Alamofire.HTTPHeaders?, parameters: Alamofire.Parameters?, encoding: Alamofire.ParameterEncoding?) { self.url = url self.method = method self.headers = headers self.parameters = parameters self.encoding = encoding } // MARK: Actions func cancel() { // Overridden in ExecutableRequest } // MARK: Hashable var hashValue: Int { return "\(method.rawValue) \(url.hashValue)".hashValue } } extension Request: Equatable { public static func ==(lhs: Request, rhs: Request) -> Bool { return lhs.hashValue == rhs.hashValue } }
3e607bd9b48f7c95bfad108f02b9bad8
23.166667
66
0.61061
false
false
false
false
saraheolson/TechEmpathy-iOS
refs/heads/master
TechEmpathy/TechEmpathy/ViewControllers/StoryViewController.swift
apache-2.0
1
// // StoryViewController.swift // TechEmpathy // // Created by Sarah Olson on 4/15/17. // Copyright © 2017 SarahEOlson. All rights reserved. // import UIKit import AVFoundation import FirebaseDatabase protocol StoryDataDelegate { func storyDataChanged(datasource: [Story]) } class StoryViewController: UIViewController { @IBOutlet fileprivate weak var collectionView: UICollectionView! @IBOutlet weak var storyTypeControl: UISegmentedControl! fileprivate var datasource: [Story] = [] private var storyDatasource = StoryDatasource() var audioPlayer: AVPlayer? override func viewDidLoad() { super.viewDidLoad() self.collectionView.register(UINib(nibName: "StoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Story") storyDatasource.delegate = self // LIFX integration if !LIFXManager.sharedInstance.hasBeenPromptedForLifx { self.present(LIFXManager.sharedInstance.askUserForLampToken(), animated: true, completion: nil) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) storyDatasource.retrieveData() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) storyDatasource.removeObservers() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } @IBAction func storyTypeChanged(_ sender: Any) { switch (storyTypeControl.selectedSegmentIndex) { case 1: datasource = storyDatasource.getDatasourceForFilter(storyType: .inclusion) case 2: datasource = storyDatasource.getDatasourceForFilter(storyType: .exclusion) default: datasource = storyDatasource.getDatasourceForFilter(storyType: .all) } collectionView.reloadData() } private class StoryDatasource { var currentDataSource: [Story] = [] var delegate: StoryViewController? var firebaseRef : FIRDatabaseReference? = nil func retrieveData() { firebaseRef = FirebaseManager.sharedInstance.firebaseRef guard let ref = firebaseRef else { return } let storiesQuery = ref.child("stories") .queryOrdered(byChild: "dateAdded") .queryLimited(toLast: 20) let _ = storiesQuery.observe(.value, with: { (snapshot) in if let JSON = snapshot.value as? [String: [String: Any]] { let storiesArray: [Story] = JSON.flatMap{ (story) in return Story(key: story.key, JSON: story.value) } self.currentDataSource = storiesArray self.delegate?.storyDataChanged(datasource: self.currentDataSource) } }) } func getDatasourceForFilter(storyType: StoryType) -> [Story] { switch (storyType) { case .exclusion: return currentDataSource.filter { $0.storyType == .exclusion } case .inclusion: return currentDataSource.filter { $0.storyType == .inclusion } default: return currentDataSource } } func removeObservers() { firebaseRef?.removeAllObservers() } } } extension StoryViewController: StoryDataDelegate { func storyDataChanged(datasource: [Story]) { self.datasource = datasource self.storyTypeControl.selectedSegmentIndex = 0 self.collectionView.reloadData() } } extension StoryViewController: UICollectionViewDataSource { internal func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return datasource.count } internal func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Story", for: indexPath) as! StoryCollectionViewCell cell.story = datasource[indexPath.row] return cell } } extension StoryViewController: UICollectionViewDelegate { internal func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let story = datasource[indexPath.row] if let audio = story.audio { if let audioURL = URL(string: audio) { let playerItem = AVPlayerItem(url: audioURL) audioPlayer = AVPlayer(playerItem:playerItem) self.audioPlayer?.play() } } LIFXManager.sharedInstance.updateAllLights(color: story.color) { [weak self] (success) in if success { DispatchQueue.main.async { guard let stories = self?.datasource else { return } let litStory = self?.datasource[indexPath.row] self?.datasource = stories.map { (story) in var mutableStory = story if let selectedStory = litStory, mutableStory.key == selectedStory.key { mutableStory.isLampLit = true //print("I saw the light") } else { mutableStory.isLampLit = false //print("So not lit") } return mutableStory } self?.collectionView.reloadData() } } } } }
99199c0f422faeb75fbb082862f6bedf
33.106145
130
0.584439
false
false
false
false
dasdom/GlobalADN
refs/heads/master
GlobalADN/Model/Post.swift
mit
1
// // Post.swift // GlobalADN // // Created by dasdom on 18.06.14. // Copyright (c) 2014 Dominik Hauser. All rights reserved. // import UIKit class Post { var canonicalURL = NSURL() var id = 0 var text = "" var threadId = 0 var user = User() var mentions = [Mention]() var attributedText = NSAttributedString() }
c9a994d829e835eb824260713e4dc883
19.25
59
0.529703
false
false
false
false
lukesutton/olpej
refs/heads/master
Olpej/Olpej/Properties-View.swift
mit
1
extension Property { public static func backgroundColor<T: UIView>(color: UIColor) -> Property<T> { return Property<T>("uiview.backgroundColor", color.hashValue) { _, mode, view in switch(mode) { case .remove: view.backgroundColor = nil case .update: view.backgroundColor = color } } } public static func hidden<T: UIView>(value: Bool) -> Property<T> { return Property<T>("uiview.button", value.hashValue) { _, mode, view in switch(mode) { case .remove: view.hidden = false case .update: view.hidden = value } } } public static func opaque<T: UIView>(value: Bool) -> Property<T> { return Property<T>("uiview.button", value.hashValue) { _, mode, view in switch(mode) { case .remove: view.opaque = false case .update: view.opaque = value } } } public static func alpha<T: UIView>(value: CGFloat) -> Property<T> { return Property<T>("uiview.isHidden", value.hashValue) { _, mode, view in switch(mode) { case .remove: view.alpha = CGFloat(1) case .update: view.alpha = value } } } public static func frame<T: UIView>(x x: Double, y: Double, width: Double, height: Double) -> Property<T> { let hashValue = x.hashValue &+ y.hashValue &+ width.hashValue &+ height.hashValue return Property<T>("uiview.frame", hashValue) { _, mode, view in switch(mode) { case .remove: view.frame = CGRect() case.update: view.frame = CGRect(x: x, y: y, width: width, height: height) } } } }
6ec30a180d29450e5bdcef9c8889c0e0
35.978723
111
0.551208
false
false
false
false
zhao765882596/XImagePickerController
refs/heads/master
XImagePickerController/Classes/XMPhotoPreviewCell.swift
mit
1
// // XMPhotoPreviewCell.swift // channel_sp // // Created by ming on 2017/10/19. // Copyright © 2017年 TiandaoJiran. All rights reserved. // import Foundation import Photos class XMAssetPreviewCell: UICollectionViewCell { var model: XMAssetModel? var singleTapGestureBlock: (() -> Void)? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.black configSubviews() NotificationCenter.default.addObserver(self, selector: #selector(self.photoPreviewCollectionViewDidScroll), name: NSNotification.Name.init("photoPreviewCollectionViewDidScroll"), object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configSubviews() { } @objc func photoPreviewCollectionViewDidScroll() { } deinit { NotificationCenter.default.removeObserver(self) } } class XMPhotoPreviewCell: XMAssetPreviewCell { var imageProgressUpdateBlock: ((Double) -> Void)? var previewView = XMPhotoPreviewView() var allowCrop = false { didSet { previewView.allowCrop = allowCrop } } var cropRect = CGRect.zero { didSet { previewView.cropRect = cropRect } } override var model: XMAssetModel? { didSet { if model == nil { return } previewView.asset = model!.asset } } override func configSubviews() { previewView.singleTapGestureBlock = { [weak self] in guard let strongSelf = self else { return } if strongSelf.singleTapGestureBlock != nil { strongSelf.singleTapGestureBlock!() } } previewView.imageProgressUpdateBlock = { [weak self] progress in guard let strongSelf = self else { return } if strongSelf.imageProgressUpdateBlock != nil { strongSelf.imageProgressUpdateBlock!(progress) } } addSubview(previewView) } func recoverSubviews() { previewView.recoverSubviews() } override func layoutSubviews() { super.layoutSubviews() previewView.frame = bounds } @objc override func photoPreviewCollectionViewDidScroll() { } } class XMVideoPreviewCell: XMAssetPreviewCell { var player: AVPlayer? var playerLayer: AVPlayerLayer? var playButton: UIButton? var cover: UIImage? override var model: XMAssetModel?{ didSet { if model == nil { return } configMoviePlayer() } } override func configSubviews() { NotificationCenter.default.addObserver(self, selector: #selector(self.photoPreviewCollectionViewDidScroll), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) } func configPlayButton() { if playButton != nil { playButton?.removeFromSuperview() } playButton = UIButton.init(type: .custom) playButton?.setImage(UIImage.imageNamedFromMyBundle(name: "MMVideoPreviewPlay"), for: .normal) playButton?.setImage(UIImage.imageNamedFromMyBundle(name: "MMVideoPreviewPlayHL"), for: .highlighted) playButton?.addTarget(self, action: #selector(self.playButtonClick), for: .touchUpInside) addSubview(playButton!) } func configMoviePlayer() { if player != nil { playerLayer?.removeFromSuperlayer() playerLayer = nil player?.pause() player = nil } XMImageManager.manager.getPhoto(asset: model!.asset, completion: {[weak self] (photo, info, isDegraded) in self!.cover = photo }) XMImageManager.manager.getVideo(asset: model!.asset) { (playerItem, info) in DispatchQueue.main.async { self.player = AVPlayer.init(playerItem: playerItem) self.playerLayer = AVPlayerLayer.init(player: self.player) self.playerLayer?.backgroundColor = UIColor.black.cgColor self.playerLayer?.frame = self.bounds self.layer.addSublayer(self.playerLayer!) self.configPlayButton() NotificationCenter.default.addObserver(self, selector: #selector(self.pausePlayerAndShowNaviBar), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) } } } override func layoutSubviews() { super.layoutSubviews() playerLayer?.frame = bounds playButton?.frame = CGRect.init(x: 0, y: 64, width: xm_width, height: xm_height - 64 - 44) } override func photoPreviewCollectionViewDidScroll() { pausePlayerAndShowNaviBar() } @objc func playButtonClick() { let currentTime = player?.currentItem?.currentTime() let durationTime = player?.currentItem?.duration if player?.rate == 0.0 { if currentTime?.value == durationTime?.value { player?.currentItem?.seek(to: CMTime.init(value: 0, timescale: 1)) player?.play() playButton?.setImage(nil, for: .normal) UIApplication.shared.isStatusBarHidden = true } if singleTapGestureBlock != nil { singleTapGestureBlock!() } } else { pausePlayerAndShowNaviBar() } } @objc func pausePlayerAndShowNaviBar() { if player?.rate != 0.0 { player?.pause() playButton?.setImage(UIImage.imageNamedFromMyBundle(name: "MMVideoPreviewPlay"), for: .normal) if singleTapGestureBlock != nil { singleTapGestureBlock!() } } } } class XMGifPreviewCell: XMAssetPreviewCell { var previewView = XMPhotoPreviewView() override var model: XMAssetModel? { didSet { if model == nil { return } previewView.model = model } } override func configSubviews() { previewView.singleTapGestureBlock = { [weak self] in guard let strongSelf = self else { return } if strongSelf.singleTapGestureBlock != nil { strongSelf.singleTapGestureBlock!() } } addSubview(previewView) } override func layoutSubviews() { super.layoutSubviews() previewView.frame = bounds } }
7afb4a0644127d10cc60ee68f4a6bd45
28.693694
199
0.600425
false
false
false
false
pawrsccouk/Stereogram
refs/heads/master
Stereogram-iPad/ImageManager.swift
mit
1
// // ImageManager.swift // Stereogram-iPad // // Created by Patrick Wallace on 21/01/2015. // Copyright (c) 2015 Patrick Wallace. All rights reserved. // import UIKit /// A collection of functions for handling images. class ImageManager { /// Load an image from the disk /// /// :param: filePath - Path to the image on disk. /// :returns: A UIImage object on success or an error object on failure class func imageFromFile(filePath: String) -> ResultOf<UIImage> { var error: NSError? let data = NSData(contentsOfFile:filePath, options:.allZeros, error:&error) if data == nil { if let e = error { return .Error(e) } return returnError("ImageManager.imageFromFile(_)" , "NSData(contentsOfFile:options:error)") } let img = UIImage(data:data!) let txt = "Unable to create the image from the data in the stored file." let userInfo = [NSLocalizedDescriptionKey: txt] if img == nil { return .Error(NSError(domain: ErrorDomain.PhotoStore.rawValue , code: ErrorCode.CouldntLoadImageProperties.rawValue , userInfo: userInfo)) } return ResultOf(img!) } /// Compose two photos to make a stereogram. /// /// :param: leftPhoto - The left image. /// :param: rightPhoto - The right image. /// :returns: A UIImage on success or an NSError on failure. class func makeStereogramWithLeftPhoto(leftPhoto: UIImage , rightPhoto: UIImage) -> ResultOf<UIImage> { assert(leftPhoto.scale == rightPhoto.scale , "Image scales \(leftPhoto.scale) and \(rightPhoto.scale) must be the same.") let stereogramSize = CGSizeMake(leftPhoto.size.width + rightPhoto.size.width , max(leftPhoto.size.height, rightPhoto.size.height)) var stereogram: UIImage? UIGraphicsBeginImageContextWithOptions(stereogramSize, false, leftPhoto.scale) // try leftPhoto.drawAtPoint(CGPointZero) rightPhoto.drawAtPoint(CGPointMake(leftPhoto.size.width, 0)) stereogram = UIGraphicsGetImageFromCurrentImageContext() // finally UIGraphicsEndImageContext() if let s = stereogram { return ResultOf(s) } return .Error(NSError(domain: ErrorDomain.PhotoStore.rawValue , code: ErrorCode.CouldntCreateStereogram.rawValue , userInfo: nil)) } /// Returns a copy of the specifed image with the viewing method swapped. /// /// :param: image The image to swap. /// :returns: The new image on success, or an NSError object on failure. /// /// Note that this only works by chopping the image in half and rearranging the halves. class func changeViewingMethod(image: UIImage) -> ResultOf<UIImage> { return and( self.getHalfOfImage(image, whichHalf: .LeftHalf), self.getHalfOfImage(image, whichHalf: .RightHalf) ) .map( { (leftImage,rightImage) in return ImageManager.makeStereogramWithLeftPhoto(rightImage, rightPhoto: leftImage) } ) } /// Enum to describe which half of an image to retrieve. /// /// - RightHalf: The right half of the image /// - LeftHalf: The left half of the image enum WhichHalf { case RightHalf, LeftHalf } /// Function to return half an image. /// /// :param: image - The image to split /// :returns: A UIImage on success or an NSError object on failure. class func getHalfOfImage(image: UIImage, whichHalf: WhichHalf) -> ResultOf<UIImage> { let rectToKeep = (whichHalf == .LeftHalf) ? CGRectMake(0, 0, image.size.width / 2.0, image.size.height) : CGRectMake(image.size.width / 2.0, 0, image.size.width / 2.0, image.size.height ) let imgPartRef = CGImageCreateWithImageInRect(image.CGImage, rectToKeep) if let i = UIImage(CGImage:imgPartRef) { return ResultOf(i) } else { return .Error(NSError.unknownErrorWithLocation("getHalfOfImage(_, whichHalf:)" , target:"CGImageCreateWithImageInRect()")) } } }
56b1396ab6b175423ef6592b893f7ba2
34.463636
90
0.685722
false
false
false
false
onevcat/CotEditor
refs/heads/develop
CotEditor/Sources/EncodingListViewController.swift
apache-2.0
1
// // EncodingListViewController.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2014-03-26. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2021 1024jp // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa final class EncodingListViewController: NSViewController, NSTableViewDelegate { // MARK: Private Properties @objc private dynamic var encodings: [CFStringEncoding] = [] { didSet { // validate restorebility self.canRestore = (encodings != UserDefaults.standard.registeredValue(for: .encodingList)) } } @objc private dynamic var canRestore = false // availability of "Restore Default" button @IBOutlet private weak var tableView: NSTableView? @IBOutlet private weak var deleteSeparatorButton: NSButton? // MARK: - // MARK: Lifecycle override func viewWillAppear() { super.viewWillAppear() self.encodings = UserDefaults.standard[.encodingList] self.tableView?.sizeToFit() } // MARK: Table View Delegate func tableView(_ tableView: NSTableView, didAdd rowView: NSTableRowView, forRow row: Int) { guard let textField = (rowView.view(atColumn: 0) as? NSTableCellView)?.textField else { return } let encoding = self.encodings[row] switch encoding { case kCFStringEncodingInvalidId: textField.stringValue = .separator case .utf8: textField.attributedStringValue = [encoding.attributedName(), encoding.attributedName(withUTF8BOM: true)].joined(separator: "\n") default: textField.attributedStringValue = encoding.attributedName() } } /// update UI just after selected rows are changed func tableViewSelectionDidChange(_ notification: Notification) { // update availability of "Delete Separator" button self.deleteSeparatorButton?.isEnabled = self.tableView!.selectedRowIndexes .contains { self.encodings[$0] == kCFStringEncodingInvalidId } } // MARK: Action Messages /// "OK" button was clicked @IBAction func save(_ sender: Any?) { // write back current encoding list userDefaults UserDefaults.standard[.encodingList] = self.encodings self.dismiss(sender) } /// restore encoding setting to default @IBAction func revertDefaultEncodings(_ sender: Any?) { self.encodings = UserDefaults.standard.registeredValue(for: .encodingList) } /// add separator below the selection @IBAction func addSeparator(_ sender: Any?) { let index = self.tableView!.selectedRow + 1 self.addSeparator(at: index) } /// remove separator @IBAction func deleteSeparator(_ sender: Any?) { let indexes = self.tableView!.selectedRowIndexes self.deleteSeparators(at: indexes) } // MARK: Private Methods /// add separator to desired row private func addSeparator(at rowIndex: Int) { guard let tableView = self.tableView else { return assertionFailure() } let indexes = IndexSet(integer: rowIndex) NSAnimationContext.runAnimationGroup({ _ in // update UI tableView.insertRows(at: indexes, withAnimation: .effectGap) }, completionHandler: { [weak self] in // update data self?.encodings.insert(kCFStringEncodingInvalidId, at: rowIndex) tableView.selectRowIndexes(indexes, byExtendingSelection: false) }) } /// remove separators at desired rows private func deleteSeparators(at rowIndexes: IndexSet) { // pick only separators up let toDeleteIndexes = rowIndexes.filteredIndexSet { self.encodings[$0] == kCFStringEncodingInvalidId } guard !toDeleteIndexes.isEmpty else { return } guard let tableView = self.tableView else { return assertionFailure() } NSAnimationContext.runAnimationGroup({ _ in // update UI tableView.removeRows(at: toDeleteIndexes, withAnimation: [.slideUp, .effectFade]) }, completionHandler: { [weak self] in // update data self?.encodings.remove(in: toDeleteIndexes) }) } } // MARK: - Private Extensions private extension CFStringEncoding { static let utf8: CFStringEncoding = CFStringBuiltInEncodings.UTF8.rawValue /// Return encoding name with style. /// /// This funciton is designed __only for__ the encoding list table. /// /// - Parameter withUTF8BOM: True when needing to attach " with BOM" to the name if the encoding is .utf8. /// - Returns: A styled encoding name. func attributedName(withUTF8BOM: Bool = false) -> NSAttributedString { assert(!withUTF8BOM || self == .utf8) let paragraphSytle = NSParagraphStyle.default.mutable paragraphSytle.lineBreakMode = .byTruncatingTail // styled encoding name let encoding = String.Encoding(cfEncoding: self) let fileEncoding = FileEncoding(encoding: encoding, withUTF8BOM: withUTF8BOM) let attrEncodingName = NSAttributedString(string: fileEncoding.localizedName, attributes: [.paragraphStyle: paragraphSytle]) let ianaName = (CFStringConvertEncodingToIANACharSetName(self) as String?) ?? "-" let attrIanaName = NSAttributedString(string: " : " + ianaName, attributes: [.foregroundColor: NSColor.secondaryLabelColor, .paragraphStyle: paragraphSytle]) return attrEncodingName + attrIanaName } }
e00d583cb8745ce4cd627d93d90be453
31.574879
118
0.605517
false
false
false
false
liuwin7/meizi_app_ios
refs/heads/master
meinv/class/login/RegisterViewController.swift
mit
1
// // RegisterViewController.swift // meinv // // Created by tropsci on 16/3/16. // Copyright © 2016年 topsci. All rights reserved. // import UIKit import Alamofire import MBProgressHUD import Argo import IQKeyboardManagerSwift class RegisterViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var nicknameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var conformPasswordTextField: UITextField! var manager: Manager! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "注册" let config = NSURLSessionConfiguration.defaultSessionConfiguration() config.timeoutIntervalForRequest = 10 self.manager = Manager(configuration: config) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) IQKeyboardManager.sharedManager().enable = true IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) IQKeyboardManager.sharedManager().enable = false } // MARK: - IBActions @IBAction func registerAction(sender: UIButton) { guard let username = usernameTextField.text, nickname = usernameTextField.text, password = passwordTextField.text, conformPassword = conformPasswordTextField.text else { let hud = MBProgressHUD.showHUDAddedTo(view, animated: true) hud.mode = .Text hud.labelText = "用户名、昵称、密码、确认密码,不能为空" hud.hide(true, afterDelay: 0.25) return } var desc: String = "" if password.characters.count < 6 { desc = "密码长度小于六位" } if password != conformPassword { desc = "密码和确认密码不一致" } if desc.characters.count > 0 { let hud = MBProgressHUD.showHUDAddedTo(view, animated: true) hud.mode = .Text hud.labelText = desc hud.hide(true, afterDelay: 0.25) return } let parameters = ["username": username, "password": password, "nickname":nickname] let hud = MBProgressHUD.showHUDAddedTo(view , animated: true) hud.mode = .Text hud.labelText = "正在注册" self.manager.request(.POST, GlobalConstant.kAPI_Register, parameters: parameters, encoding: .JSON).responseJSON { (response) -> Void in guard let value = response.result.value else { hud.labelText = NSLocalizedString("Network Error", comment: "Network Error") hud.hide(true, afterDelay: 0.5) return } let result:RequestResult = Argo.decode(value)! switch result.code { case .InvalidUsername: hud.labelText = "无效的用户名" case .UsernameHasBeenUsed: hud.labelText = "用户名已经被人占用" case .InvalidPassword: hud.labelText = "密码无效" default: hud.labelText = "注册成功,请登录" self.navigationController?.popViewControllerAnimated(true) } hud.hide(true, afterDelay: 0.5) } } }
cd41ab9fcef1072af3b171278124e2e2
31.894231
143
0.599532
false
true
false
false
nielstj/GLChat
refs/heads/master
GLChatPlayground.playground/Pages/Bubble.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation import GLChat import PlaygroundSupport struct DefaultTextStyle: TextStyleProviderType { var font = UIFont(name: "Helvetica-Light", size: 12.0)! var color = UIColor.white var backgroundColor = UIColor.purple var cornerRadius: CGFloat = 12.0 } let defaultStyle = DefaultTextStyle() struct ChatBubbleStyles { static func incomingChatStyle(_ label : UILabel) { let s = DefaultTextStyle() label.backgroundColor = s.backgroundColor label.font = s.font label.textColor = s.color label.layer.cornerRadius = s.cornerRadius label.layer.masksToBounds = true } } let m: String = "Lorem ipsum dorem." let f: UIFont = defaultStyle.font let w: CGFloat = 250.0 var lbl = BubbleLabel(message: m, width: w, font: f, padding: 8.0) var timestampLayout = lbl.withDate(Date()) let x = UIView(frame: CGRect(x: 0, y: 0, width: w, height: lbl.bounds.height + 20.0)) for view in timestampLayout.contents { if let label = view as? BubbleLabel { label.apply(style: ChatBubbleStyles.incomingChatStyle) } x.addSubview(view) } timestampLayout.layout(in: x.bounds) PlaygroundPage.current.liveView = x //: [Next](@next)
c9086a0dc6f52e06ecf4607f2a24d3de
24.8125
85
0.691687
false
false
false
false
gcirone/Mama-non-mama
refs/heads/master
Mama non mama/FlowerPink.swift
mit
1
// // FlowerPink.swift // TestSpriteFlowers // // Created by Cirone, Gianluca on 10/02/15. // Copyright (c) 2015 freshdev. All rights reserved. // import SpriteKit class FlowerPink: SKNode { let atlas = SKTextureAtlas(named: "flower-pink") deinit { //println("FlowerPink.deinit") } override init(){ super.init() name = "flower" let pistillo = SKSpriteNode(texture: atlas.textureNamed("31_pistillo")) pistillo.name = "pistillo" pistillo.position = CGPointMake(0.0, 0.0) //pistillo.size = CGSizeMake(90.0, 90.0) pistillo.zRotation = 0.0 pistillo.zPosition = 10.0 addChild(pistillo) let gambo = SKSpriteNode(texture: atlas.textureNamed("31_gambo")) gambo.name = "gambo" gambo.position = CGPointMake(0.0, 0.0) gambo.anchorPoint = CGPointMake(0.5, 1) //gambo = CGSizeMake(22.0, 367.0) gambo.zRotation = 0.0 gambo.zPosition = -1.0 addChild(gambo) let petalo_0 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_0")) petalo_0.name = "petalo" petalo_0.position = CGPointMake(-72.627799987793, -27.7642211914062) //petalo_0.size = CGSizeMake(98.0, 30.0) petalo_0.zRotation = 0.479760855436325 petalo_0.zPosition = 3.0 addChild(petalo_0) let petalo_1 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_1")) petalo_1.name = "petalo" petalo_1.position = CGPointMake(-76.5903396606445, 8.46768188476562) //petalo_1.size = CGSizeMake(99.0, 31.0) petalo_1.zRotation = 0.0 petalo_1.zPosition = 3.0 addChild(petalo_1) let petalo_2 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_2")) petalo_2.name = "petalo" petalo_2.position = CGPointMake(-69.1255798339844, 32.6385803222656) //petalo_2.size = CGSizeMake(97.0, 30.0) petalo_2.zRotation = -0.363067835569382 petalo_2.zPosition = 2.0 addChild(petalo_2) let petalo_3 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_3")) petalo_3.name = "petalo" petalo_3.position = CGPointMake(-47.2764434814453, 59.8580627441406) //petalo_3.size = CGSizeMake(29.0, 95.0) petalo_3.zRotation = 0.706677973270416 petalo_3.zPosition = 3.0 addChild(petalo_3) let petalo_4 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_4")) petalo_4.name = "petalo" petalo_4.position = CGPointMake(-2.15827941894531, 75.2708740234375) //petalo_4.size = CGSizeMake(29.0, 94.0) petalo_4.zRotation = 0.0 petalo_4.zPosition = 3.0 addChild(petalo_4) let petalo_5 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_5")) petalo_5.name = "petalo" petalo_5.position = CGPointMake(-22.1246490478516, 72.4426574707031) //petalo_5.size = CGSizeMake(29.0, 92.0) petalo_5.zRotation = 0.335041642189026 petalo_5.zPosition = 2.0 addChild(petalo_5) let petalo_6 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_6")) petalo_6.name = "petalo" petalo_6.position = CGPointMake(-52.3308258056641, 47.2386779785156) //petalo_6.size = CGSizeMake(90.0, 34.0) petalo_6.zRotation = -0.651017606258392 petalo_6.zPosition = 1.0 addChild(petalo_6) let petalo_7 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_7")) petalo_7.name = "petalo" petalo_7.position = CGPointMake(43.82763671875, -65.5964202880859) //petalo_7.size = CGSizeMake(29.0, 99.0) petalo_7.zRotation = 0.652929544448853 petalo_7.zPosition = 3.0 addChild(petalo_7) let petalo_8 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_8")) petalo_8.name = "petalo" petalo_8.position = CGPointMake(-48.9131698608398, -56.7787933349609) //petalo_8.size = CGSizeMake(28.0, 96.0) petalo_8.zRotation = -0.613186120986938 petalo_8.zPosition = 3.0 addChild(petalo_8) let petalo_9 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_9")) petalo_9.name = "petalo" petalo_9.position = CGPointMake(-73.6861877441406, -6.11056518554688) //petalo_9.size = CGSizeMake(96.0, 26.0) petalo_9.zRotation = 0.144854202866554 petalo_9.zPosition = 2.0 addChild(petalo_9) let petalo_10 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_10")) petalo_10.name = "petalo" petalo_10.position = CGPointMake(-57.4043121337891, -47.2994995117188) //petalo_10.size = CGSizeMake(28.0, 97.0) petalo_10.zRotation = -0.728766739368439 petalo_10.zPosition = 2.0 addChild(petalo_10) let petalo_11 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_11")) petalo_11.name = "petalo" petalo_11.position = CGPointMake(-30.2350463867188, -71.1099395751953) //petalo_11.size = CGSizeMake(29.0, 94.0) petalo_11.zRotation = -0.336944311857224 petalo_11.zPosition = 2.0 addChild(petalo_11) let petalo_12 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_12")) petalo_12.name = "petalo" petalo_12.position = CGPointMake(-0.107711791992188, -75.2673645019531) //petalo_12.size = CGSizeMake(31.0, 96.0) petalo_12.zRotation = 0.000864179630298167 petalo_12.zPosition = 1.0 addChild(petalo_12) let petalo_13 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_13")) petalo_13.name = "petalo" petalo_13.position = CGPointMake(27.1640167236328, -73.3287658691406) //petalo_13.size = CGSizeMake(32.0, 97.0) petalo_13.zRotation = 0.30914369225502 petalo_13.zPosition = 0.0 addChild(petalo_13) let petalo_14 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_14")) petalo_14.name = "petalo" petalo_14.position = CGPointMake(73.0106201171875, -26.8544616699219) //petalo_14.size = CGSizeMake(95.0, 31.0) petalo_14.zRotation = -0.3441102206707 petalo_14.zPosition = 3.0 addChild(petalo_14) let petalo_15 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_15")) petalo_15.name = "petalo" petalo_15.position = CGPointMake(60.8752746582031, -48.6043243408203) //petalo_15.size = CGSizeMake(30.0, 98.0) petalo_15.zRotation = 0.906754195690155 petalo_15.zPosition = 0.0 addChild(petalo_15) let petalo_16 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_16")) petalo_16.name = "petalo" petalo_16.position = CGPointMake(80.3223266601562, 18.8720397949219) //petalo_16.size = CGSizeMake(95.0, 27.0) petalo_16.zRotation = 0.252619832754135 petalo_16.zPosition = 3.0 addChild(petalo_16) let petalo_17 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_17")) petalo_17.name = "petalo" petalo_17.position = CGPointMake(78.8992309570312, -0.594451904296875) //petalo_17.size = CGSizeMake(92.0, 27.0) petalo_17.zRotation = -0.0387234911322594 petalo_17.zPosition = 1.0 addChild(petalo_17) let petalo_18 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_18")) petalo_18.name = "petalo" petalo_18.position = CGPointMake(64.1389923095703, 53.3252563476562) //petalo_18.size = CGSizeMake(31.0, 101.0) petalo_18.zRotation = -0.793990731239319 petalo_18.zPosition = 3.0 addChild(petalo_18) let petalo_19 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_19")) petalo_19.name = "petalo" petalo_19.position = CGPointMake(71.4255065917969, 39.3387756347656) //petalo_19.size = CGSizeMake(94.0, 28.0) petalo_19.zRotation = 0.588323354721069 petalo_19.zPosition = 1.0 addChild(petalo_19) let petalo_20 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_20")) petalo_20.name = "petalo" petalo_20.position = CGPointMake(31.2721710205078, 72.760009765625) //petalo_20.size = CGSizeMake(31.0, 91.0) petalo_20.zRotation = -0.39888322353363 petalo_20.zPosition = 3.0 addChild(petalo_20) let petalo_21 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_21")) petalo_21.name = "petalo" petalo_21.position = CGPointMake(20.5424957275391, 73.6123962402344) //petalo_21.size = CGSizeMake(27.0, 85.0) petalo_21.zRotation = -0.207954958081245 petalo_21.zPosition = 2.0 addChild(petalo_21) let petalo_22 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_22")) petalo_22.name = "petalo" petalo_22.position = CGPointMake(48.2252349853516, 63.6234741210938) //petalo_22.size = CGSizeMake(28.0, 96.0) petalo_22.zRotation = -0.650420904159546 petalo_22.zPosition = 1.0 addChild(petalo_22) // petalo speciale let petalo_23 = SKSpriteNode(texture: atlas.textureNamed("31_petalo_22")) petalo_23.name = "petalo_mama" petalo_23.position = CGPointMake(66.5204620361328, -38.9328155517578) //petalo_23.size = CGSizeMake(28.0, 96.0) petalo_23.zRotation = -2.04170322418213 petalo_23.zPosition = 0.0 addChild(petalo_23) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
1c754cc7ab88b2d57f5017eceb2a834d
36.804511
81
0.603421
false
false
false
false
wunshine/FoodStyle
refs/heads/master
FoodStyle/FoodStyle/Classes/View/DiaryTableViewCell.swift
mit
1
// // DiaryTableViewCell.swift // FoodStyle // // Created by Woz Wong on 16/3/23. // Copyright © 2016年 code4Fun. All rights reserved. // import UIKit class DiaryCell : UITableViewCell { var model:DiaryCellModel{ get{ return DiaryCellModel() } set{ self.model = newValue } } var picture:UIImageView = { var pic = UIImageView(image: UIImage(named: "coreAnimation")) return pic }() var diaryName:UILabel = { let name = UILabel() name.text = "奶油蛋糕" name.sizeToFit() return name }() var title:UILabel = { let title = UILabel() title.font = UIFont.systemFontOfSize(10) title.text = "#吃货志#" title.sizeToFit() return title }() var zan:UIButton = { var zan = UIButton() zan.layer.cornerRadius = 3 zan.backgroundColor = GLOBAL_COLOR() zan.setTitle("赞", forState: UIControlState.Normal) zan.setTitle("已赞", forState: UIControlState.Selected) zan.setImage(UIImage(named: "diary_liked"), forState: UIControlState.Selected) zan.setImage(UIImage(named: "diary_like"), forState: UIControlState.Normal) return zan }() var comment:UIButton = { var comment = UIButton() comment.layer.cornerRadius = 3 comment.backgroundColor = GLOBAL_COLOR() comment.setTitle("评论", forState: UIControlState.Normal) comment.setImage(UIImage(named: "diary_comment"), forState: UIControlState.Normal) return comment }() var more:UIButton = { var more = UIButton() more.backgroundColor = UIColor.lightGrayColor() more.layer.cornerRadius = 3 more.setImage(UIImage(named: "diary_menu"), forState: UIControlState.Normal) return more }() var zanedPeople:UICollectionView = { var layout = UICollectionViewFlowLayout() layout.itemSize = CGSizeMake(SCREEN_RECT().width-20/8,44) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 var people = UICollectionView(frame: CGRectMake(0,0,SCREEN_RECT().width-20,44), collectionViewLayout: layout) var item = UICollectionViewCell() people.backgroundColor = UIColor.yellowColor() people.contentSize = CGSizeMake(SCREEN_RECT().width-20,44) item.contentView.addSubview(UIButton()) return people }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(picture) addSubview(title) addSubview(diaryName) addSubview(zan) addSubview(zanedPeople) addSubview(comment) addSubview(more) } required init?(coder aDecoder: NSCoder) { fatalError("not imped") } override func layoutSubviews() { super.layoutSubviews() picture.snp_makeConstraints { (make) -> Void in make.width.equalTo(self) make.height.equalTo(200) make.top.equalTo(self.snp_top) } diaryName.snp_makeConstraints { (make) -> Void in make.top.equalTo(picture.snp_bottom).offset(20) make.left.equalTo(self).offset(20) make.height.equalTo(20) } title.snp_makeConstraints { (make) -> Void in make.top.equalTo(diaryName.snp_bottom).offset(10) make.left.equalTo(diaryName.snp_left) make.height.equalTo(20) } zanedPeople.snp_makeConstraints { (make) -> Void in make.top.equalTo(title.snp_bottom).offset(20) make.centerX.equalTo(self.snp_centerX) } zan.snp_makeConstraints { (make) -> Void in make.top.equalTo(zanedPeople.snp_bottom).offset(10) make.left.equalTo(diaryName.snp_left) make.width.equalTo(60) make.height.equalTo(25) } comment.snp_makeConstraints { (make) -> Void in make.left.equalTo(zan.snp_right).offset(20) make.top.equalTo(zan.snp_top) make.height.width.equalTo(zan) } more.snp_makeConstraints { (make) -> Void in make.right.equalTo(self).offset(-10) make.top.equalTo(comment.snp_top) make.width.equalTo(40) make.height.equalTo(comment) } } }
aede92914bbecfe193a050a30968a908
30.048951
117
0.604054
false
false
false
false
keitaito/HackuponApp
refs/heads/master
HackuponApp/Networking/Parser.swift
mit
1
// // Parser.swift // HackuponApp // // Created by Keita Ito on 3/14/16. // Copyright © 2016 Keita Ito. All rights reserved. // import Foundation // TODO: Update the parse method to be a Generic function. struct Parser { /// Parse the passed NSData object, and returned Array<Person>?. static func parse(data: NSData?) -> [Person]? { // Check if data is non-nil value. guard let data = data else { return nil } // Try JSON-serializing. var jsonObject: AnyObject? do { jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) } catch { // If error is catched, print out. print("Failed JSON serializing. Error: \(error)") } // Type cast jsonObject to an array of type Dictionary of type String key and AnyObject value. guard let people = jsonObject as? Array<Dictionary<String, AnyObject>> else { return nil } // Map Array<[String : AnyObject]> to Array<Person>. let mappedPeople: [Person] = people.map { // TODO: Change the else clause not to return a Person object. return a nil, or error. // Check if values are non-nil. guard let personName = $0["name"] as? String else { return Person(name: "", id: 0) } guard let personId = $0["id"] as? Int else { return Person(name: "", id: 0) } // Instantiate a Person object with values. return Person(name: personName, id: personId) } return mappedPeople } }
12edb3191242999e4d3a0d62f9579873
38.317073
122
0.6067
false
false
false
false
mariopavlovic/codility-lessons
refs/heads/master
codility-lessons/codility-lessons/Lesson11.swift
mit
1
import Foundation public class Lesson11 { public func numSemiprimes(N: Int, P: [Int], Q: [Int]) -> [Int] { let primeNumbers = primes(N) let semiprimeNumbers = semiprimes(primeNumbers) var result = [Int]() for i in 0 ..< P.count { let p = P[i] let q = Q[i] var count = 0 for semiprime in semiprimeNumbers { if (semiprime >= p) && (semiprime <= q) { count += 1 } } result.append(count) } return result } } extension Lesson11 { func primes(N: Int) -> [Int] { guard N > 1 else { return [] } var numbers = Array(count: N+1, repeatedValue: true) numbers[0] = false numbers[1] = false //find primes let rootN = Int(ceil(sqrt(Double(N)))) for i in 2 ... rootN { if numbers[i] { var multiple = i+i while multiple < N { numbers[multiple] = false multiple += i } } } //transform primes from bools -> ints by //getting indexes of true values (primes) var primes = [Int]() for (index, value) in numbers.enumerate() { if value { primes.append(index) } } return primes } func semiprimes(primes: [Int]) -> [Int] { var semiprimes = Set<Int>() for i in 0 ..< primes.count { let base = primes[i] for j in i ..< primes.count { let next = primes[j] semiprimes.insert(base * next) } } return Array(semiprimes) } }
661802d0ede453d47a31535ed76e3982
24.589041
68
0.425281
false
false
false
false
naoto0822/transient-watch-ios
refs/heads/master
TransientWatch/Presentation/View/HomeCell.swift
gpl-3.0
1
// // HomeCell.swift // TransientWatch // // Created by naoto yamaguchi on 2015/04/11. // Copyright (c) 2015年 naoto yamaguchi. All rights reserved. // import UIKit class HomeCell: UITableViewCell { // MARK: - Property @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var raLabel: UILabel! @IBOutlet weak var decLabel: UILabel! @IBOutlet weak var classLabel: UILabel! @IBOutlet weak var fluxChangeLabel: UILabel! var astroObj: AstroObj? { didSet { if let astro = self.astroObj { self.nameLabel.text = astro.name self.raLabel.text = astro.ra?.description self.decLabel.text = astro.dec?.description self.classLabel.text = astro.astroClassId?.description if let rate = astro.fluxRate?.description { self.fluxChangeLabel.text = rate + "%" } } } } // MARK: - LifeCycle override func awakeFromNib() { super.awakeFromNib() // Initialization code self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) self.textLabel?.textColor = UIColor.whiteColor() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
4a6584e78eb9ff9b60916bfbbf964c00
26.5
77
0.59021
false
false
false
false
ZhipingYang/FlappyBird
refs/heads/master
FlappyBrid/FlappyBrid/AppDelegate.swift
mit
1
// // AppDelegate.swift // FlappyBrid // // Created by Daniel on 2/2/16. // Copyright © 2016 XcodeYang. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // var newWindow: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { ScreenMirror.share.start() if #available(iOS 14.0, *) { HapticsManager.share.start() } return true } // @available(iOS 13.0, *) // func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // print(UIApplication.shared.connectedScenes) // // let scene = UIWindowScene(session: connectingSceneSession, connectionOptions: options) // newWindow = UIWindow().then { // $0.rootViewController = GameViewController() // $0.windowScene = scene // $0.isHidden = false // } // return UISceneConfiguration(name: "External configuration", sessionRole: connectingSceneSession.role) // } }
7f3ad4ec4053e1f79fc45be228003df6
33.777778
181
0.678115
false
true
false
false
ZevEisenberg/Padiddle
refs/heads/main
Padiddle/Padiddle/Utilities/Log.swift
mit
1
// // Log.swift // Padiddle // // Created by Zev Eisenberg on 3/5/16. // Copyright © 2016 Zev Eisenberg. All rights reserved. // import Foundation struct Log { static let isDebugging: Bool = { #if DEBUG return true #else return false #endif }() private static func log(_ object: Any?, title: String, _ fileName: String, _ functionName: String, _ line: Int) { let objectName = URL(fileURLWithPath: fileName).lastPathComponent var objectDebugDescription: String = "" if object != nil { debugPrint(object!, to: &objectDebugDescription) } let preambleString = title + objectName + ": " + functionName + "(\(line))" if isDebugging { print(preambleString) if object != nil { print(objectDebugDescription) } } else { print(preambleString) if object != nil { print(objectDebugDescription) } } } static func error(_ object: Any? = nil, _ fileName: String = #file, _ functionName: String = #function, _ line: Int = #line) { log(object, title: "ERROR-> ", fileName, functionName, line) } static func warning(_ object: Any? = nil, _ fileName: String = #file, _ functionName: String = #function, _ line: Int = #line) { log(object, title: "WARNING-> ", fileName, functionName, line) } static func info(_ object: Any? = nil, _ fileName: String = #file, _ functionName: String = #function, _ line: Int = #line) { log(object, title: "Info-> ", fileName, functionName, line) } static func debug(_ object: Any? = nil, _ fileName: String = #file, _ functionName: String = #function, _ line: Int = #line) { if isDebugging { log(object, title: "Debug-> ", fileName, functionName, line) } } }
6e89eb1df97648cb2cd3c0b47739e369
29.983871
132
0.563248
false
false
false
false
KiiPlatform/thing-if-iOSSample
refs/heads/master
SampleProject/TriggeredServerCodeResultViewController.swift
mit
1
import UIKit import ThingIFSDK class TriggeredServerCodeResultViewController: KiiBaseTableViewController { var serverCodeResults = [TriggeredServerCodeResult]() var trigger: Trigger? = nil override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) serverCodeResults.removeAll() self.tableView.reloadData() self.showActivityView(true) getServerCodeResults(nil) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return serverCodeResults.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ServerCodeResultCell") let result = serverCodeResults[indexPath.row] if result.succeeded { cell!.textLabel?.text = "Succeeded" }else { cell!.textLabel?.text = "Failed:" + (result.error!.errorMessage ?? "") } let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss" cell!.detailTextLabel?.text = dateFormatter.stringFromDate(result.executedAt) return cell! } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func getServerCodeResults(nextPaginationKey: String?){ if iotAPI != nil && target != nil { showActivityView(true) // use default bestEffortLimit iotAPI!.listTriggeredServerCodeResults((self.trigger?.triggerID)!, bestEffortLimit: 0, paginationKey: nextPaginationKey, completionHandler: { (results, paginationKey, error) -> Void in self.showActivityView(false) if results != nil { for result in results! { self.serverCodeResults.append(result) } // paginationKey is nil, then there is not more triggers, reload table if paginationKey == nil { self.tableView.reloadData() self.showActivityView(false) }else { self.getServerCodeResults(paginationKey) } }else { self.showAlert("Get ServerCodeResults Failed", error: error, completion: nil) } }) } } }
ec3a4dd6bebc7f8dfd30bb81aaa48069
38.9375
196
0.609002
false
false
false
false
eric1202/LZJ_Coin
refs/heads/master
DinDinShopDemo/Pods/XCGLogger/Sources/XCGLogger/XCGLogger.swift
mit
3
// // XCGLogger.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright © 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // #if os(macOS) import AppKit #elseif os(iOS) || os(tvOS) || os(watchOS) import UIKit #endif // MARK: - XCGLogger /// The main logging class open class XCGLogger: CustomDebugStringConvertible { // MARK: - Constants public struct Constants { /// Prefix identifier to use for all other identifiers public static let baseIdentifier = "com.cerebralgardens.xcglogger" /// Identifier for the default instance of XCGLogger public static let defaultInstanceIdentifier = "\(baseIdentifier).defaultInstance" /// Identifer for the Xcode console destination public static let baseConsoleDestinationIdentifier = "\(baseIdentifier).logdestination.console" /// Identifier for the Apple System Log destination public static let systemLogDestinationIdentifier = "\(baseIdentifier).logdestination.console.nslog" /// Identifier for the file logging destination public static let fileDestinationIdentifier = "\(baseIdentifier).logdestination.file" /// Identifier for the default dispatch queue public static let logQueueIdentifier = "\(baseIdentifier).queue" /// UserInfo Key - tags public static let userInfoKeyTags = "\(baseIdentifier).tags" /// UserInfo Key - devs public static let userInfoKeyDevs = "\(baseIdentifier).devs" /// UserInfo Key - internal public static let userInfoKeyInternal = "\(baseIdentifier).internal" /// Library version number public static let versionString = "5.0.1" /// Internal userInfo internal static let internalUserInfo: [String: Any] = [XCGLogger.Constants.userInfoKeyInternal: true] /// Extended file attributed key to use when storing the logger's identifier on an archived log file public static let extendedAttributeArchivedLogIdentifierKey = "\(baseIdentifier).archived.by" /// Extended file attributed key to use when storing the time a log file was archived public static let extendedAttributeArchivedLogTimestampKey = "\(baseIdentifier).archived.at" } // MARK: - Enums /// Enum defining our log levels public enum Level: Int, Comparable, CustomStringConvertible { case verbose case debug case info case warning case error case severe case none public var description: String { switch self { case .verbose: return "Verbose" case .debug: return "Debug" case .info: return "Info" case .warning: return "Warning" case .error: return "Error" case .severe: return "Severe" case .none: return "None" } } public static let all: [Level] = [.verbose, .debug, .info, .warning, .error, .severe] } // MARK: - Default instance /// The default XCGLogger object open static var `default`: XCGLogger = { struct Statics { static let instance: XCGLogger = XCGLogger(identifier: XCGLogger.Constants.defaultInstanceIdentifier) } return Statics.instance }() // MARK: - Properties /// Identifier for this logger object (should be unique) open var identifier: String = "" /// The log level of this logger, any logs received at this level or higher will be output to the destinations open var outputLevel: Level = .debug { didSet { for index in 0 ..< destinations.count { destinations[index].outputLevel = outputLevel } } } /// Option: a closure to execute whenever a logging method is called without a log message open var noMessageClosure: () -> Any? = { return "" } /// Option: override descriptions of log levels open var levelDescriptions: [XCGLogger.Level: String] = [:] /// Array of log formatters to apply to messages before they're output open var formatters: [LogFormatterProtocol]? = nil /// Array of log filters to apply to messages before they're output open var filters: [FilterProtocol]? = nil /// The default dispatch queue used for logging open class var logQueue: DispatchQueue { struct Statics { static var logQueue = DispatchQueue(label: XCGLogger.Constants.logQueueIdentifier, attributes: []) } return Statics.logQueue } /// A custom date formatter object to use when displaying the dates of log messages (internal storage) internal var _customDateFormatter: DateFormatter? = nil /// The date formatter object to use when displaying the dates of log messages open var dateFormatter: DateFormatter? { get { guard _customDateFormatter == nil else { return _customDateFormatter } struct Statics { static var dateFormatter: DateFormatter = { let defaultDateFormatter = DateFormatter() defaultDateFormatter.locale = NSLocale.current defaultDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" return defaultDateFormatter }() } return Statics.dateFormatter } set { _customDateFormatter = newValue } } /// Array containing all of the destinations for this logger open var destinations: [DestinationProtocol] = [] // MARK: - Life Cycle public init(identifier: String = "", includeDefaultDestinations: Bool = true) { self.identifier = identifier if includeDefaultDestinations { // Setup a standard console destination add(destination: ConsoleDestination(identifier: XCGLogger.Constants.baseConsoleDestinationIdentifier)) } } // MARK: - Setup methods /// A shortcut method to configure the default logger instance. /// /// - Note: The function exists to get you up and running quickly, but it's recommended that you use the advanced usage configuration for most projects. See https://github.com/DaveWoodCom/XCGLogger/blob/master/README.md#advanced-usage-recommended /// /// - Parameters: /// - level: The log level of this logger, any logs received at this level or higher will be output to the destinations. **Default:** Debug /// - showLogIdentifier: Whether or not to output the log identifier. **Default:** false /// - showFunctionName: Whether or not to output the function name that generated the log. **Default:** true /// - showThreadName: Whether or not to output the thread's name the log was created on. **Default:** false /// - showLevel: Whether or not to output the log level of the log. **Default:** true /// - showFileNames: Whether or not to output the fileName that generated the log. **Default:** true /// - showLineNumbers: Whether or not to output the line number where the log was generated. **Default:** true /// - showDate: Whether or not to output the date the log was created. **Default:** true /// - writeToFile: FileURL or path (as String) to a file to log all messages to (this file is overwritten each time the logger is created). **Default:** nil => no log file /// - fileLevel: An alternate log level for the file destination. **Default:** nil => use the same log level as the console destination /// /// - Returns: Nothing /// open class func setup(level: Level = .debug, showLogIdentifier: Bool = false, showFunctionName: Bool = true, showThreadName: Bool = false, showLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: Any? = nil, fileLevel: Level? = nil) { self.default.setup(level: level, showLogIdentifier: showLogIdentifier, showFunctionName: showFunctionName, showThreadName: showThreadName, showLevel: showLevel, showFileNames: showFileNames, showLineNumbers: showLineNumbers, showDate: showDate, writeToFile: writeToFile) } /// A shortcut method to configure the logger. /// /// - Note: The function exists to get you up and running quickly, but it's recommended that you use the advanced usage configuration for most projects. See https://github.com/DaveWoodCom/XCGLogger/blob/master/README.md#advanced-usage-recommended /// /// - Parameters: /// - level: The log level of this logger, any logs received at this level or higher will be output to the destinations. **Default:** Debug /// - showLogIdentifier: Whether or not to output the log identifier. **Default:** false /// - showFunctionName: Whether or not to output the function name that generated the log. **Default:** true /// - showThreadName: Whether or not to output the thread's name the log was created on. **Default:** false /// - showLevel: Whether or not to output the log level of the log. **Default:** true /// - showFileNames: Whether or not to output the fileName that generated the log. **Default:** true /// - showLineNumbers: Whether or not to output the line number where the log was generated. **Default:** true /// - showDate: Whether or not to output the date the log was created. **Default:** true /// - writeToFile: FileURL or path (as String) to a file to log all messages to (this file is overwritten each time the logger is created). **Default:** nil => no log file /// - fileLevel: An alternate log level for the file destination. **Default:** nil => use the same log level as the console destination /// /// - Returns: Nothing /// open func setup(level: Level = .debug, showLogIdentifier: Bool = false, showFunctionName: Bool = true, showThreadName: Bool = false, showLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: Any? = nil, fileLevel: Level? = nil) { outputLevel = level if let standardConsoleDestination = destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination { standardConsoleDestination.showLogIdentifier = showLogIdentifier standardConsoleDestination.showFunctionName = showFunctionName standardConsoleDestination.showThreadName = showThreadName standardConsoleDestination.showLevel = showLevel standardConsoleDestination.showFileName = showFileNames standardConsoleDestination.showLineNumber = showLineNumbers standardConsoleDestination.showDate = showDate standardConsoleDestination.outputLevel = level } if let writeToFile: Any = writeToFile { // We've been passed a file to use for logging, set up a file logger let standardFileDestination: FileDestination = FileDestination(writeToFile: writeToFile, identifier: XCGLogger.Constants.fileDestinationIdentifier) standardFileDestination.showLogIdentifier = showLogIdentifier standardFileDestination.showFunctionName = showFunctionName standardFileDestination.showThreadName = showThreadName standardFileDestination.showLevel = showLevel standardFileDestination.showFileName = showFileNames standardFileDestination.showLineNumber = showLineNumbers standardFileDestination.showDate = showDate standardFileDestination.outputLevel = fileLevel ?? level add(destination: standardFileDestination) } logAppDetails() } // MARK: - Logging methods /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing /// open class func logln(_ closure: @autoclosure () -> Any?, level: Level = .debug, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(level, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing /// open class func logln(_ level: Level = .debug, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(level, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing /// open class func logln(_ level: Level = .debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(level, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing /// open func logln(_ closure: @autoclosure () -> Any?, level: Level = .debug, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(level, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing /// open func logln(_ level: Level = .debug, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { logln(level, functionName: String(describing: functionName), fileName: String(describing: fileName), lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing /// open func logln(_ level: Level = .debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { let enabledDestinations = destinations.filter({$0.isEnabledFor(level: level)}) guard enabledDestinations.count > 0 else { return } guard let closureResult = closure() else { return } let logDetails: LogDetails = LogDetails(level: level, date: Date(), message: String(describing: closureResult), functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo) for destination in enabledDestinations { destination.process(logDetails: logDetails) } } /// Execute some code only when at the specified log level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func exec(_ level: Level = .debug, closure: () -> () = {}) { self.default.exec(level, closure: closure) } /// Execute some code only when at the specified log level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func exec(_ level: Level = .debug, closure: () -> () = {}) { guard isEnabledFor(level:level) else { return } closure() } /// Generate logs to display your app's vitals (app name, version, etc) as well as XCGLogger's version and log level. /// /// - Parameters: /// - selectedDestination: A specific destination to log the vitals on, if omitted, will log to all destinations /// /// - Returns: Nothing. /// open func logAppDetails(selectedDestination: DestinationProtocol? = nil) { let date = Date() var buildString = "" if let infoDictionary = Bundle.main.infoDictionary { if let CFBundleShortVersionString = infoDictionary["CFBundleShortVersionString"] as? String { buildString = "Version: \(CFBundleShortVersionString) " } if let CFBundleVersion = infoDictionary["CFBundleVersion"] as? String { buildString += "Build: \(CFBundleVersion) " } } let processInfo: ProcessInfo = ProcessInfo.processInfo let XCGLoggerVersionNumber = XCGLogger.Constants.versionString var logDetails: [LogDetails] = [] logDetails.append(LogDetails(level: .info, date: date, message: "\(processInfo.processName) \(buildString)PID: \(processInfo.processIdentifier)", functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo)) logDetails.append(LogDetails(level: .info, date: date, message: "XCGLogger Version: \(XCGLoggerVersionNumber) - Level: \(outputLevel)", functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo)) for var destination in (selectedDestination != nil ? [selectedDestination!] : destinations) where !destination.haveLoggedAppDetails { for logDetail in logDetails { guard destination.isEnabledFor(level:.info) else { continue } destination.haveLoggedAppDetails = true destination.processInternal(logDetails: logDetail) } } } // MARK: - Convenience logging methods // MARK: * Verbose /// Log something at the Verbose log level. This format of verbose() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func verbose(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Verbose log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func verbose(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Verbose log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func verbose(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Verbose log level. This format of verbose() isn't provided the object to log, instead the property *`noMessageClosure`* is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func verbose(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Verbose log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func verbose(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Verbose log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func verbose(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Debug /// Log something at the Debug log level. This format of debug() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func debug(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Debug log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func debug(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Debug log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func debug(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Debug log level. This format of debug() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func debug(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Debug log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func debug(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Debug log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func debug(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Info /// Log something at the Info log level. This format of info() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func info(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Info log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func info(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Info log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func info(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Info log level. This format of info() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func info(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Info log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func info(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Info log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func info(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Warning /// Log something at the Warning log level. This format of warning() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func warning(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Warning log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func warning(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Warning log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func warning(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Warning log level. This format of warning() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func warning(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Warning log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func warning(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Warning log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func warning(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Error /// Log something at the Error log level. This format of error() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func error(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Error log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func error(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Error log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func error(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Error log level. This format of error() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func error(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Error log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func error(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Error log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func error(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Severe /// Log something at the Severe log level. This format of severe() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func severe(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Severe log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func severe(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Severe log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func severe(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Severe log level. This format of severe() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func severe(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Severe log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func severe(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Severe log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func severe(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: - Exec Methods // MARK: * Verbose /// Execute some code only when at the Verbose log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func verboseExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.verbose, closure: closure) } /// Execute some code only when at the Verbose log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func verboseExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.verbose, closure: closure) } // MARK: * Debug /// Execute some code only when at the Debug or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func debugExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.debug, closure: closure) } /// Execute some code only when at the Debug or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func debugExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.debug, closure: closure) } // MARK: * Info /// Execute some code only when at the Info or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func infoExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.info, closure: closure) } /// Execute some code only when at the Info or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func infoExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.info, closure: closure) } // MARK: * Warning /// Execute some code only when at the Warning or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func warningExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.warning, closure: closure) } /// Execute some code only when at the Warning or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func warningExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.warning, closure: closure) } // MARK: * Error /// Execute some code only when at the Error or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func errorExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.error, closure: closure) } /// Execute some code only when at the Error or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func errorExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.error, closure: closure) } // MARK: * Severe /// Execute some code only when at the Severe log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func severeExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.severe, closure: closure) } /// Execute some code only when at the Severe log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func severeExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.severe, closure: closure) } // MARK: - Log destination methods /// Get the destination with the specified identifier. /// /// - Parameters: /// - identifier: Identifier of the destination to return. /// /// - Returns: The destination with the specified identifier, if one exists, nil otherwise. /// open func destination(withIdentifier identifier: String) -> DestinationProtocol? { for destination in destinations { if destination.identifier == identifier { return destination } } return nil } /// Add a new destination to the logger. /// /// - Parameters: /// - destination: The destination to add. /// /// - Returns: /// - true: Log destination was added successfully. /// - false: Failed to add the destination. /// @discardableResult open func add(destination: DestinationProtocol) -> Bool { var destination = destination let existingDestination: DestinationProtocol? = self.destination(withIdentifier: destination.identifier) if existingDestination != nil { return false } if let previousOwner = destination.owner { previousOwner.remove(destination: destination) } destination.owner = self destinations.append(destination) return true } /// Remove the destination from the logger. /// /// - Parameters: /// - destination: The destination to remove. /// /// - Returns: /// - true: Log destination was removed successfully. /// - false: Failed to remove the destination. /// @discardableResult open func remove(destination: DestinationProtocol) -> Bool { guard destination.owner === self else { return false } let existingDestination: DestinationProtocol? = self.destination(withIdentifier: destination.identifier) guard existingDestination != nil else { return false } // Make our parameter mutable var destination = destination destination.owner = nil destinations = destinations.filter({$0.owner != nil}) return true } /// Remove the destination with the specified identifier from the logger. /// /// - Parameters: /// - identifier: The identifier of the destination to remove. /// /// - Returns: /// - true: Log destination was removed successfully. /// - false: Failed to remove the destination. /// @discardableResult open func remove(destinationWithIdentifier identifier: String) -> Bool { guard let destination = destination(withIdentifier: identifier) else { return false } return remove(destination: destination) } // MARK: - Misc methods /// Check if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: The log level to check. /// /// - Returns: /// - true: Logger is at the log level specified or lower. /// - false: Logger is at a higher log levelss. /// open func isEnabledFor(level: XCGLogger.Level) -> Bool { return level >= self.outputLevel } // MARK: - Private methods /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - message: Message to log. /// - level: Specified log level. /// - source: The destination calling this method /// /// - Returns: Nothing /// internal func _logln(_ message: String, level: Level = .debug, source sourceDestination: DestinationProtocol? = nil) { let logDetails: LogDetails = LogDetails(level: level, date: Date(), message: message, functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo) for destination in self.destinations { if level >= .error && sourceDestination?.identifier == destination.identifier { continue } if (destination.isEnabledFor(level: level)) { destination.processInternal(logDetails: logDetails) } } } // MARK: - DebugPrintable open var debugDescription: String { get { var description: String = "\(extractTypeName(self)): \(identifier) - destinations: \r" for destination in destinations { description += "\t \(destination.debugDescription)\r" } return description } } } // Implement Comparable for XCGLogger.Level public func < (lhs: XCGLogger.Level, rhs: XCGLogger.Level) -> Bool { return lhs.rawValue < rhs.rawValue }
b28696d368233146ddd9ecca450df81a
49.398687
299
0.625594
false
false
false
false
riehs/bitcoin-trainer
refs/heads/master
Bitcoin Trainer/Bitcoin Trainer/ReceiveBitcoinViewController.swift
mit
1
// // ReceiveBitcoinViewController.swift // Bitcoin Trainer // // Created by Daniel Riehs on 8/29/15. // Copyright (c) 2015 Daniel Riehs. All rights reserved. // import UIKit class ReceiveBitcoinViewController: UIViewController { @IBOutlet weak var addressDisplay: UITextField! @IBOutlet weak var imgQRCode: UIImageView! @IBAction func dimissReceiveBitcoin(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } var qrCodeImage: CIImage! override func viewDidLoad() { super.viewDidLoad() addressDisplay.text = BitcoinAddress.sharedInstance().address //Convert the Bitcoin address to a QR code. let data = addressDisplay.text!.data(using: String.Encoding.isoLatin1, allowLossyConversion: false) let filter = CIFilter(name: "CIQRCodeGenerator") filter!.setValue(data, forKey: "inputMessage") //The "Q" represents the level of error-correction data included in the QR code. filter!.setValue("Q", forKey: "inputCorrectionLevel") qrCodeImage = filter!.outputImage //Determine appropriate scale factor for image. let scaleX = imgQRCode.frame.size.width / qrCodeImage.extent.size.width let scaleY = imgQRCode.frame.size.height / qrCodeImage.extent.size.height //Apply scale factor to image. let transformedImage = qrCodeImage.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY)) //Convert the Core Image to a UIImage. imgQRCode.image = UIImage(ciImage: transformedImage) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
cfd72e35d5624ca4cb78339748d66968
27.796296
101
0.747267
false
false
false
false
volochaev/firebase-and-facebook
refs/heads/master
firebase-example/DataService.swift
mit
1
// // DataService.swift // firebase-example // // Created by Nikolai Volochaev on 02/11/15. // Copyright © 2015 Nikolai Volochaev. All rights reserved. // import Foundation import Firebase let BASE_URL = "https://fiery-torch-5814.firebaseio.com" class DataService { static let sharedInstance = DataService() private var _REF_BASE = Firebase(url: "\(BASE_URL)") private var _REF_POSTS = Firebase(url: "\(BASE_URL)/posts") private var _REF_USERS = Firebase(url: "\(BASE_URL)/users") var REF_BASE: Firebase { return _REF_BASE } var REF_POSTS: Firebase { return _REF_POSTS } var REF_USERS: Firebase { return _REF_USERS } func createFirebaseUser(uid: String, user: Dictionary<String, String>) { REF_USERS.childByAppendingPath(uid).setValue(user) } }
d3fc5de3cf72c056146c9249cee0daf6
28.035714
76
0.672414
false
false
false
false
coderQuanjun/RxSwift-Table-Collection
refs/heads/master
RxSwift-Table-Collection1/RxSwift-Table-Collection/UITableView/Controllers/RxTableViewController.swift
mit
1
// // RxTableViewController.swift // RxSwift-Table-Collection // // Created by iOS_Tian on 2017/9/18. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit import RxSwift import RxCocoa fileprivate let kCellID: String = "rxCell" class RxTableViewController: UIViewController { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var rxTableView: UITableView! fileprivate lazy var bag = DisposeBag() fileprivate lazy var heroArr = [HeroModel]() fileprivate lazy var heroVM: HeroViewModel = HeroViewModel(searchText: self.searchText) var searchText: Observable<String> { //输入后间隔0.5秒搜索,在主线程运行 return searchBar.rx.text.orEmpty.throttle(0.5, scheduler: MainScheduler.instance) } override func viewDidLoad() { super.viewDidLoad() title = "UITableView" //1.加载tableViewCell rxTableView.rowHeight = 80 rxTableView.register(UINib(nibName: "RxTableViewCell", bundle: nil), forCellReuseIdentifier: kCellID) //2.给tableView绑定数据 heroVM.heroVariable.asDriver().drive(rxTableView.rx.items(cellIdentifier: kCellID, cellType: RxTableViewCell.self)) { (_, hero, cell) in cell.heroModel = hero }.addDisposableTo(bag) // 3.监听UITableView的点击 rxTableView.rx.modelSelected(HeroModel.self).subscribe { (event: Event<HeroModel>) in print(event.element?.name ?? "") }.addDisposableTo(bag) //4.设置自身代理 // rxTableView.rx.setDelegate(self).addDisposableTo(bag) } } extension RxTableViewController: UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } }
ad901a75b22a23d04abb5c910bba279a
26.923077
144
0.655096
false
false
false
false
rcasanovan/Social-Feed
refs/heads/master
Social Feed/Social Feed/UI/Feed List/View/Cell/SFTwitterFeedTableViewCell.swift
apache-2.0
1
// // SFTwitterFeedTableViewCell.swift // Social Feed // // Created by Ricardo Casanova on 04/08/2017. // Copyright © 2017 Social Feed. All rights reserved. // import UIKit //__ Haneke import Haneke class SFTwitterFeedTableViewCell: UITableViewCell { //__ IBOutlets @IBOutlet weak private var itemFeedUserImageView: UIImageView? @IBOutlet weak private var itemFeedUsernameLabel: UILabel? @IBOutlet weak private var itemFeedTextLabel: UILabel? @IBOutlet weak private var itemFeedTextHeightConstraint: NSLayoutConstraint? @IBOutlet weak private var itemFeedCreatedAtLabel : UILabel? override func awakeFromNib() { super.awakeFromNib() setupViewCell() } override func prepareForReuse() { super.prepareForReuse() self.itemFeedUserImageView?.image = nil self.itemFeedTextLabel?.text = "" self.itemFeedTextHeightConstraint?.constant = 18.0 self.itemFeedCreatedAtLabel?.text = "" } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } private func setupViewCell() { self.selectionStyle = UITableViewCellSelectionStyle.none } func heightForItem(text: String, font: UIFont) -> CGFloat { return (font.sizeOfString(string: text, constrainedToWidth: Double(self.frame.size.width - 64.0)).height) } //__ DVATableViewModelProtocol method func bind(withModel viewModel: DVATableViewModelProtocol!) { //__ Get the view model for cell let model : SFFeedViewObject = (viewModel as? SFFeedViewObject)! //__ Configure outlets self.itemFeedUserImageView?.contentMode = UIViewContentMode.scaleAspectFill self.itemFeedUserImageView?.clipsToBounds = true self.itemFeedUserImageView?.layer.cornerRadius = (self.itemFeedUserImageView?.frame.size.height)! / 2.0 itemFeedUserImageView?.hnk_setImageFromURL((model.itemUserImageURL?.absoluteURL)!) self.itemFeedUsernameLabel?.text = model.itemUsername self.itemFeedCreatedAtLabel?.text = model.itemCreatedAt self.itemFeedTextLabel?.font = model.itemTextFont self.itemFeedTextLabel?.text = model.itemText self.itemFeedTextLabel?.numberOfLines = 0 self.itemFeedTextHeightConstraint?.constant = 10.0 + heightForItem(text: model.itemText, font: model.itemTextFont) } }
3f360ebdbe6b579bdbca8a3aebb39eed
36.272727
122
0.702439
false
false
false
false
fireflyexperience/TransitioningKit
refs/heads/master
TransitioningKit/PSViewControllerTransitioningDelegate.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Adam Michela, The Puffin Supply Project // // 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 PSViewControllerTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate { public init( presentAnimator: UIViewControllerAnimatedTransitioning? = nil, dismissAnimator: UIViewControllerAnimatedTransitioning? = nil, interactionController: UIPercentDrivenInteractiveTransition? = nil, presentationController: UIPresentationController? = nil ) { self.presentAnimator = presentAnimator self.dismissAnimator = dismissAnimator self.interactionController = interactionController self.presentationController = presentationController super.init() } // MARK: Public var interactionController: UIPercentDrivenInteractiveTransition? public func animationControllerForPresentedController( presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController ) -> UIViewControllerAnimatedTransitioning? { return presentAnimator } public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return dismissAnimator } public func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactionController } public func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactionController } public func presentationControllerForPresentedViewController( presented: UIViewController, presentingViewController presenting: UIViewController!, sourceViewController source: UIViewController ) -> UIPresentationController? { return presentationController } // MARK: Private private let presentAnimator: UIViewControllerAnimatedTransitioning? private let dismissAnimator: UIViewControllerAnimatedTransitioning? private let presentationController: UIPresentationController? }
4774dc9e7b88b19a8bc6d1ff253d09d6
38.855422
146
0.769649
false
false
false
false
FuckBoilerplate/RxCache
refs/heads/master
Sources/Core/internal/cache/Action.swift
mit
1
// Action.swift // RxCache // // Copyright (c) 2016 Victor Albertos https://github.com/VictorAlbertos // // 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. private let PrefixDynamicKey = "$d$d$d$" private let PrefixDynamicKeyGroup = "$g$g$g$" protocol Action { var memory : Memory {get} } extension Action { func composeKey(_ providerKey: String, dynamicKey : DynamicKey?, dynamicKeyGroup : DynamicKeyGroup?) -> String { var dynamicKeyValue = "" var dynamicKeyGroupValue = "" if dynamicKey != nil { dynamicKeyValue = dynamicKey!.dynamicKey } if dynamicKeyGroup != nil { dynamicKeyValue = dynamicKeyGroup!.dynamicKey dynamicKeyGroupValue = dynamicKeyGroup!.group } return providerKey + PrefixDynamicKey + dynamicKeyValue + PrefixDynamicKeyGroup + dynamicKeyGroupValue } func getKeysMatchingProviderKey(_ providerKey: String) -> [String] { var keysMatchingProviderKey = [String]() memory.keys().forEach { (composedKeyMemory) -> () in let keyPartProviderMemory = getPartOfTarget(target: PrefixDynamicKey, composedKeyMemory: composedKeyMemory) if providerKey == keyPartProviderMemory { keysMatchingProviderKey.append(composedKeyMemory) } } return keysMatchingProviderKey } func getKeysMatchingDynamicKey(_ providerKey: String, dynamicKey : DynamicKey?) -> [String] { var dynamicKeyValue = "" if dynamicKey != nil { dynamicKeyValue = dynamicKey!.dynamicKey } var keysMatchingDynamicKey = [String]() let composedProviderKeyAndDynamicKey = providerKey + PrefixDynamicKey + dynamicKeyValue memory.keys().forEach { (composedKeyMemory) -> () in let keyPartProviderAndDynamicKeyMemory = getPartOfTarget(target: PrefixDynamicKeyGroup, composedKeyMemory: composedKeyMemory) if composedProviderKeyAndDynamicKey == keyPartProviderAndDynamicKeyMemory { keysMatchingDynamicKey.append(composedKeyMemory) } } return keysMatchingDynamicKey } func getKeyMatchingDynamicKeyGroup(_ providerKey: String, dynamicKey : DynamicKey?, dynamicKeyGroup : DynamicKeyGroup?) -> String { return composeKey(providerKey, dynamicKey: dynamicKey, dynamicKeyGroup: dynamicKeyGroup) } private func getPartOfTarget(target: String, composedKeyMemory: String) -> String? { if let range = composedKeyMemory.range(of: target, options: .backwards) { let indexPrefixDynamicKey = composedKeyMemory.distance(from: composedKeyMemory.startIndex, to: range.lowerBound) let endPositionKey = composedKeyMemory.characters.count - indexPrefixDynamicKey let finalIndex = composedKeyMemory.index(composedKeyMemory.endIndex, offsetBy: -endPositionKey) return composedKeyMemory.substring(with: Range<String.Index>(composedKeyMemory.startIndex..<finalIndex)) } else { return nil } } }
3079668c69f9a0282ff9d86b4af380e4
40.54902
138
0.683577
false
false
false
false
dalonng/hellos
refs/heads/master
swift.hello/hello.playground/section-1.swift
gpl-2.0
1
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var myVariable = 42 myVariable = 50 let myConstant = 42 let label = "The width is " let width = 94 let widthLabel = label + String(width) let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit."
dbe9c937057380d1f249d990d781abba
20.111111
64
0.707124
false
false
false
false
bitjammer/swift
refs/heads/master
test/SILGen/objc_extensions.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_extensions_helper class Sub : Base {} extension Sub { override var prop: String! { didSet { // Ignore it. } // Make sure that we are generating the @objc thunk and are calling the actual method. // // CHECK-LABEL: sil hidden [thunk] @_T015objc_extensions3SubC4propSQySSGfgTo : $@convention(objc_method) (Sub) -> @autoreleased Optional<NSString> { // CHECK: bb0([[SELF:%.*]] : $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[GETTER_FUNC:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGfg : $@convention(method) (@guaranteed Sub) -> @owned Optional<String> // CHECK: apply [[GETTER_FUNC]]([[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGfgTo' // Then check the body of the getter calls the super_method. // CHECK-LABEL: sil hidden @_T015objc_extensions3SubC4propSQySSGfg : $@convention(method) (@guaranteed Sub) -> @owned Optional<String> { // CHECK: bb0([[SELF:%.*]] : $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[SELF_COPY_CAST:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!getter.1.foreign // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[SELF_COPY_CAST]]) // CHECK: bb3( // CHECK: destroy_value [[SELF_COPY]] // CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGfg' // Then check the setter @objc thunk. // // CHECK-LABEL: sil hidden [thunk] @_T015objc_extensions3SubC4propSQySSGfsTo : $@convention(objc_method) (Optional<NSString>, Sub) -> () { // CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $Sub): // CHECK: [[NEW_VALUE_COPY:%.*]] = copy_value [[NEW_VALUE]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Sub // CHECK: switch_enum [[NEW_VALUE_COPY]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL_BB:bb[0-9]+]] // CHECK: [[SUCC_BB]]([[STR:%.*]] : $NSString): // CHECK: [[FAIL_BB]]: // CHECK: bb3([[BRIDGED_NEW_VALUE:%.*]] : $Optional<String>): // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NORMAL_FUNC:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGfs : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () // CHECK: apply [[NORMAL_FUNC]]([[BRIDGED_NEW_VALUE]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGfsTo' // Then check the body of the actually setter value and make sure that we // call the didSet function. // CHECK-LABEL: sil hidden @_T015objc_extensions3SubC4propSQySSGfs : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () { // First we get the old value. // CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<String>, [[SELF:%.*]] : $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[GET_SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!getter.1.foreign : (Base) -> () -> String!, $@convention(objc_method) (Base) -> @autoreleased Optional<NSString> // CHECK: [[OLD_NSSTRING:%.*]] = apply [[GET_SUPER_METHOD]]([[UPCAST_SELF_COPY]]) // CHECK: bb3([[OLD_NSSTRING_BRIDGED:%.*]] : $Optional<String>): // This next line is completely not needed. But we are emitting it now. // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[BORROWED_NEW_VALUE:%.*]] = begin_borrow [[NEW_VALUE]] // CHECK: [[NEW_VALUE_COPY:%.*]] = copy_value [[BORROWED_NEW_VALUE]] // CHECK: [[SET_SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!setter.1.foreign : (Base) -> (String!) -> (), $@convention(objc_method) (Optional<NSString>, Base) -> () // CHECK: switch_enum [[NEW_VALUE_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: bb4([[OLD_STRING:%.*]] : $String): // CHECK: bb6([[BRIDGED_NEW_STRING:%.*]] : $Optional<NSString>): // CHECK: apply [[SET_SUPER_METHOD]]([[BRIDGED_NEW_STRING]], [[UPCAST_SELF_COPY]]) // CHECK: destroy_value [[BRIDGED_NEW_STRING]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[DIDSET_NOTIFIER:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGfW : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () // CHECK: [[BORROWED_OLD_NSSTRING_BRIDGED:%.*]] = begin_borrow [[OLD_NSSTRING_BRIDGED]] // CHECK: [[COPIED_OLD_NSSTRING_BRIDGED:%.*]] = copy_value [[BORROWED_OLD_NSSTRING_BRIDGED]] // CHECK: end_borrow [[BORROWED_OLD_NSSTRING_BRIDGED]] from [[OLD_NSSTRING_BRIDGED]] // This is an identity cast that should be eliminated by SILGen peepholes. // CHECK: apply [[DIDSET_NOTIFIER]]([[COPIED_OLD_NSSTRING_BRIDGED]], [[SELF]]) // CHECK: destroy_value [[OLD_NSSTRING_BRIDGED]] // CHECK: destroy_value [[NEW_VALUE]] // CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGfs' } func foo() { } override func objCBaseMethod() {} } // CHECK-LABEL: sil hidden @_T015objc_extensions20testOverridePropertyyAA3SubCF func testOverrideProperty(_ obj: Sub) { // CHECK: bb0([[ARG:%.*]] : $Sub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: = class_method [volatile] [[BORROWED_ARG]] : $Sub, #Sub.prop!setter.1.foreign : (Sub) -> (String!) -> () obj.prop = "abc" } // CHECK: } // end sil function '_T015objc_extensions20testOverridePropertyyAA3SubCF' testOverrideProperty(Sub()) // CHECK-LABEL: sil shared [thunk] @_T015objc_extensions3SubC3fooyyFTc // CHECK: function_ref @_T015objc_extensions3SubC3fooyyFTD // CHECK: } // end sil function '_T015objc_extensions3SubC3fooyyFTc' // CHECK: sil shared [transparent] [thunk] @_T015objc_extensions3SubC3fooyyFTD // CHECK: bb0([[SELF:%.*]] : $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: class_method [volatile] [[SELF_COPY]] : $Sub, #Sub.foo!1.foreign // CHECK: } // end sil function '_T015objc_extensions3SubC3fooyyFTD' func testCurry(_ x: Sub) { _ = x.foo } extension Sub { var otherProp: String { get { return "hello" } set { } } } class SubSub : Sub { // CHECK-LABEL: sil hidden @_T015objc_extensions03SubC0C14objCBaseMethodyyF // CHECK: bb0([[SELF:%.*]] : $SubSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: super_method [volatile] [[SELF_COPY]] : $SubSub, #Sub.objCBaseMethod!1.foreign : (Sub) -> () -> (), $@convention(objc_method) (Sub) -> () // CHECK: } // end sil function '_T015objc_extensions03SubC0C14objCBaseMethodyyF' override func objCBaseMethod() { super.objCBaseMethod() } } extension SubSub { // CHECK-LABEL: sil hidden @_T015objc_extensions03SubC0C9otherPropSSfs // CHECK: bb0([[NEW_VALUE:%.*]] : $String, [[SELF:%.*]] : $SubSub): // CHECK: [[SELF_COPY_1:%.*]] = copy_value [[SELF]] // CHECK: = super_method [volatile] [[SELF_COPY_1]] : $SubSub, #Sub.otherProp!getter.1.foreign // CHECK: [[SELF_COPY_2:%.*]] = copy_value [[SELF]] // CHECK: = super_method [volatile] [[SELF_COPY_2]] : $SubSub, #Sub.otherProp!setter.1.foreign // CHECK: } // end sil function '_T015objc_extensions03SubC0C9otherPropSSfs' override var otherProp: String { didSet { // Ignore it. } } } // SR-1025 extension Base { fileprivate static var x = 1 } // CHECK-LABEL: sil hidden @_T015objc_extensions19testStaticVarAccessyyF func testStaticVarAccess() { // CHECK: [[F:%.*]] = function_ref @_T0So4BaseC15objc_extensionsE1x33_1F05E59585E0BB585FCA206FBFF1A92DLLSifau // CHECK: [[PTR:%.*]] = apply [[F]]() // CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]] _ = Base.x }
a94018b1247051bb6c565fcbda852a70
50.46988
212
0.622191
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/NSUserActivity+Extensions.swift
mit
1
import Foundation public extension NSUserActivity { @objc var shouldSkipOnboarding: Bool { guard let path = webpageURL?.wikiResourcePath, let languageCode = webpageURL?.wmf_languageCode else { return false } let namespaceAndTitle = path.namespaceAndTitleOfWikiResourcePath(with: languageCode) let namespace = namespaceAndTitle.0 let title = namespaceAndTitle.1 return namespace == .special && title == "ReadingLists" } }
b21fd53a99aeba4b295a99269da90d76
30.625
92
0.66996
false
false
false
false
liuxuan30/Charts
refs/heads/master
Pods/Charts/Source/Charts/Utils/Platform+Accessibility.swift
apache-2.0
3
// // Platform+Accessibility.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation #if os(iOS) || os(tvOS) #if canImport(UIKit) import UIKit #endif internal func accessibilityPostLayoutChangedNotification(withElement element: Any? = nil) { UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: element) } internal func accessibilityPostScreenChangedNotification(withElement element: Any? = nil) { UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: element) } /// A simple abstraction over UIAccessibilityElement and NSAccessibilityElement. open class NSUIAccessibilityElement: UIAccessibilityElement { private weak var containerView: UIView? final var isHeader: Bool = false { didSet { accessibilityTraits = isHeader ? UIAccessibilityTraits.header : UIAccessibilityTraits.none } } final var isSelected: Bool = false { didSet { accessibilityTraits = isSelected ? UIAccessibilityTraits.selected : UIAccessibilityTraits.none } } override public init(accessibilityContainer container: Any) { // We can force unwrap since all chart views are subclasses of UIView containerView = (container as! UIView) super.init(accessibilityContainer: container) } override open var accessibilityFrame: CGRect { get { return super.accessibilityFrame } set { guard let containerView = containerView else { return } super.accessibilityFrame = containerView.convert(newValue, to: UIScreen.main.coordinateSpace) } } } extension NSUIView { /// An array of accessibilityElements that is used to implement UIAccessibilityContainer internally. /// Subclasses **MUST** override this with an array of such elements. @objc open func accessibilityChildren() -> [Any]? { return nil } public final override var isAccessibilityElement: Bool { get { return false } // Return false here, so we can make individual elements accessible set { } } open override func accessibilityElementCount() -> Int { return accessibilityChildren()?.count ?? 0 } open override func accessibilityElement(at index: Int) -> Any? { return accessibilityChildren()?[index] } open override func index(ofAccessibilityElement element: Any) -> Int { guard let axElement = element as? NSUIAccessibilityElement else { return NSNotFound } return (accessibilityChildren() as? [NSUIAccessibilityElement])? .firstIndex(of: axElement) ?? NSNotFound } } #endif #if os(OSX) #if canImport(AppKit) import AppKit #endif internal func accessibilityPostLayoutChangedNotification(withElement element: Any? = nil) { guard let validElement = element else { return } NSAccessibility.post(element: validElement, notification: .layoutChanged) } internal func accessibilityPostScreenChangedNotification(withElement element: Any? = nil) { // Placeholder } /// A simple abstraction over UIAccessibilityElement and NSAccessibilityElement. open class NSUIAccessibilityElement: NSAccessibilityElement { private weak var containerView: NSView? final var isHeader: Bool = false { didSet { setAccessibilityRole(isHeader ? .staticText : .none) } } final var isSelected: Bool = false { didSet { setAccessibilitySelected(isSelected) } } open var accessibilityLabel: String { get { return accessibilityLabel() ?? "" } set { setAccessibilityLabel(newValue) } } open var accessibilityFrame: NSRect { get { return accessibilityFrame() } set { guard let containerView = containerView else { return } let bounds = NSAccessibility.screenRect(fromView: containerView, rect: newValue) // This works, but won't auto update if the window is resized or moved. // setAccessibilityFrame(bounds) // using FrameInParentSpace allows for automatic updating of frame when windows are moved and resized. // However, there seems to be a bug right now where using it causes an offset in the frame. // This is a slightly hacky workaround that calculates the offset and removes it from frame calculation. setAccessibilityFrameInParentSpace(bounds) let axFrame = accessibilityFrame() let widthOffset = abs(axFrame.origin.x - bounds.origin.x) let heightOffset = abs(axFrame.origin.y - bounds.origin.y) let rect = NSRect(x: bounds.origin.x - widthOffset, y: bounds.origin.y - heightOffset, width: bounds.width, height: bounds.height) setAccessibilityFrameInParentSpace(rect) } } public init(accessibilityContainer container: Any) { // We can force unwrap since all chart views are subclasses of NSView containerView = (container as! NSView) super.init() setAccessibilityParent(containerView) setAccessibilityRole(.row) } } /// - Note: setAccessibilityRole(.list) is called at init. See Platform.swift. extension NSUIView: NSAccessibilityGroup { open override func accessibilityLabel() -> String? { return "Chart View" } open override func accessibilityRows() -> [Any]? { return accessibilityChildren() } } #endif
099477d8e8451f07628ee8f9bdf2ab3c
26.67907
116
0.653672
false
false
false
false
KevinZhouRafael/ActiveSQLite
refs/heads/master
ActiveSQLiteTests/models/ProductM.swift
mit
1
// // ProductM.swift // ActiveSQLite // // Created by Kevin Zhou on 05/06/2017. // Copyright © 2017 [email protected]. All rights reserved. // import Foundation import SQLite @testable import ActiveSQLite class ProductM:ASModel{ var name:String = "" var price:NSNumber = NSNumber(value:0.0) var desc:String? var code:NSNumber? var publish_date:NSDate? var version:NSNumber? static let name = Expression<String>("product_name") static let price = Expression<Double>("product_price") static let desc = Expression<String?>("desc") static let code = Expression<NSNumber>("code") //Tests add column var type:NSNumber? static let type = Expression<NSNumber?>("type") override class var nameOfTable: String{ return "Product" } override func doubleTypes() -> [String]{ return ["price"] } override func mapper() -> [String:String]{ return ["name":"product_name","price":"product_price"]; } override func transientTypes() -> [String]{ return ["version"] } override class var isSaveDefaulttimestamp:Bool{ return true } }
7cccb63efc636d3d7efe6e4ecd463cf4
20.890909
63
0.622924
false
false
false
false
Asura19/SwiftAlgorithm
refs/heads/master
SwiftAlgorithm/SwiftAlgorithm/BinarySearchTree.swift
mit
1
// // BinarySearchTree.swift // SwiftAlgorithm // // Created by Phoenix on 2019/9/2. // Copyright © 2019 Phoenix. All rights reserved. // import Foundation public class BinarySearchTree<E: Comparable> { fileprivate(set) public var value: E fileprivate(set) public weak var parent: BinarySearchTree? fileprivate(set) public var left: BinarySearchTree? fileprivate(set) public var right: BinarySearchTree? public init(value: E) { self.value = value } public convenience init(array: [E]) { precondition(array.count > 0) self.init(value: array.first!) for v in array.dropFirst() { insert(v) } } public var isRoot: Bool { return parent == nil } public var isLeaf: Bool { return left == nil && right == nil } public var isLeftChild: Bool { return parent?.left === self } public var isRightChild: Bool { return parent?.right === self } public var hasLeftChild: Bool { return left != nil } public var hasRightChild: Bool { return right != nil } public var hasAnyChild: Bool { return hasLeftChild || hasRightChild } public var hasBothChild: Bool { return hasLeftChild && hasRightChild } public var count: Int { return (left?.count ?? 0) + 1 + (right?.count ?? 0) } } extension BinarySearchTree { public func insert(_ value: E) { if value < self.value { if let left = left { left.insert(value) } else { left = BinarySearchTree(value: value) left?.parent = self } } else { if let right = right { right.insert(value) } else { right = BinarySearchTree(value: value) right?.parent = self } } } @discardableResult public func remove() -> BinarySearchTree? { let replacement: BinarySearchTree? if let right = right { replacement = right.minimum() } else if let left = left { replacement = left.maximum() } else { replacement = nil } replacement?.remove() replacement?.right = right replacement?.left = left right?.parent = replacement left?.parent = replacement if let parent = parent { if isLeftChild { parent.left = replacement } else { parent.right = replacement } replacement?.parent = parent } parent = nil left = nil right = nil return replacement } } extension BinarySearchTree { public func search(_ value: E) -> BinarySearchTree? { var node: BinarySearchTree? = self while let nd = node { if value < nd.value { node = nd.left } else if value > nd.value { node = nd.right } else { node = nd } } return nil } public func contains(_ value: E) -> Bool { return search(value) != nil } public func minimum() -> BinarySearchTree { var node = self while let next = node.left { node = next } return node } public func maximum() -> BinarySearchTree { var node = self while let next = node.right { node = next } return node } public func depth() -> Int { var node = self var depth = 0 while let parent = node.parent { node = parent depth += 1 } return depth } public func height() -> Int { if isLeaf { return 0 } else { return 1 + max(left?.height() ?? 0, right?.height() ?? 0) } } public func predecessor() -> BinarySearchTree? { if let left = left { return left.maximum() } else { var node = self while let parent = node.parent { if parent.value < value { return parent } node = parent } } return nil } public func successor() -> BinarySearchTree? { if let right = right { return right.minimum() } else { var node = self while let parent = node.parent { if parent.value > value { return parent } node = parent } } return nil } } // MARK: - Traversal extension BinarySearchTree { public func traverseInOrder(process: (E) -> Void) { left?.traverseInOrder(process: process) process(value) right?.traverseInOrder(process: process) } public func traversePreOrder(process: (E) -> Void) { process(value) left?.traversePreOrder(process: process) right?.traversePreOrder(process: process) } public func traversePostOrder(process: (E) -> Void) { left?.traversePostOrder(process: process) right?.traversePostOrder(process: process) process(value) } } extension BinarySearchTree: CustomStringConvertible { public var description: String { var s = "" if let left = left { s += "(\(left.description)) <- " } s += "\(value)" if let right = right { s += " -> (\(right.description))" } return s } }
fa5e738e10f4916daf65e6b5b2ac289c
22.436508
69
0.489164
false
false
false
false
rzrasel/SwiftLocalNotificationOne
refs/heads/master
SwiftLocalNotificationOne/SwiftLocalNotificationOne/ViewController.swift
apache-2.0
3
// // ViewController.swift // SwiftLocalNotificationOne // // Created by NextDot on 1/31/16. // Copyright © 2016 RzRasel. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 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. } @IBAction func sysBtnOnClickNotifyMe(sender: AnyObject) { let settings = UIApplication.sharedApplication().currentUserNotificationSettings() if settings!.types == .None { let alertController = UIAlertController(title: "Can't schedule", message: "Either we don't have permission to schedule notifications, or we haven't asked yet.", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(alertController, animated: true, completion: nil) //return } let currDate = NSDate(); let dateComp = NSDateComponents(); dateComp.second = 10; let cal = NSCalendar.currentCalendar(); let fireDate: NSDate = cal.dateByAddingComponents(dateComp, toDate: currDate, options: NSCalendarOptions(rawValue: 0))!; let notification: UILocalNotification = UILocalNotification(); notification.alertTitle = "Rz Local Notification" notification.alertBody = "This is a local notification"; notification.alertAction = "Be Awesome!" notification.soundName = UILocalNotificationDefaultSoundName notification.fireDate = fireDate; UIApplication.sharedApplication().scheduleLocalNotification(notification); } }
1b85e755e2ebe79ced171a691e6573f8
39.5
196
0.684211
false
false
false
false
jbannister/VirtualTourist
refs/heads/master
VirtualTourist/VirtualTourist/Flickr.swift
mit
1
// // Flickr.swift // VirtualTourist // // Created by Jan Bannister on 20/10/2015. // Copyright © 2015 JB. All rights reserved. // import Foundation import CoreData class Flickr { let base = "https://api.flickr.com/services/rest/" //let photo = "https://farm.staticflickr.com/" lazy var sharedContext: NSManagedObjectContext = { return CoreDataStack.Instance().managedObjectContext }() func escapedParameters(parameters: [String : AnyObject]) -> String { var urlVars = [String]() for (key, value) in parameters { /* Make sure that it is a string value */ let stringValue = "\(value)" /* Escape it */ let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) /* Append it */ urlVars += [key + "=" + "\(escapedValue!)"] } return (!urlVars.isEmpty ? "?" : "") + urlVars.joinWithSeparator("&") } func pageRandom() -> Int { return 3 } func flickrPin(pin: Location, completionHandler: (photos: [Photo]?, error: String?) -> Void) { let methodArguments : [String : AnyObject] = [ "method": "flickr.photos.search", "api_key": "42dc7942a9c93422dceee70bdbcc419a", "format": "json", "lat": pin.latitude, "lon": pin.longitude, "nojsoncallback": 1, "safe_search": 1, "page": pageRandom() ] let session = NSURLSession.sharedSession() let urlString = base + escapedParameters(methodArguments) print("urlString: \(urlString)") let url = NSURL(string: urlString)! let request = NSURLRequest(URL: url) let task = session.dataTaskWithRequest(request) {data, response, error in if let e = error { completionHandler(photos: nil, error: e.description) } else { let parsed = try! NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary if let photos = parsed.valueForKey("photos") as? [String : AnyObject] { if let photo = photos["photo"] as? [[String : AnyObject]] { var output : [Photo]! self.sharedContext.performBlockAndWait { output = [Photo]() for p0 in photo { let p1 = Photo(dict: p0, context: self.sharedContext) if let p = p1 { //p1.pin = pin // Crush :( output.append(p) } } completionHandler(photos: output, error: nil) } } else { completionHandler(photos: nil, error: "Not Photo") } } else { completionHandler(photos: nil, error: "Not Photos") } } } task.resume() } func flickrPhoto(photo: Photo, completionHandler: (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void) { let photoBase = "https://farm\(photo.farm).staticflickr.com/\(photo.server)/\(photo.id)_\(photo.secret).jpg" let urlString = photoBase let url = NSURL(string: urlString)! let request = NSURLRequest(URL: url) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) {data, response, error in if response != nil { completionHandler(data: data, response: nil, error: nil) } else { completionHandler(data: nil, response: nil, error: error) } } task.resume() } }
851cbaaeb3ee5f829772ecd928933de6
35.946903
139
0.496885
false
false
false
false
Asura19/My30DaysOfSwift
refs/heads/master
TabbarApp/TabbarApp/ThirdViewController.swift
mit
1
// // ThirdViewController.swift // TabbarApp // // Created by Phoenix on 2017/4/25. // Copyright © 2017年 Phoenix. All rights reserved. // import UIKit class ThirdViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() navigationController?.isNavigationBarHidden = true self.profileImageView.alpha = 0 self.profileImageView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 0.5, delay: 0.1, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseIn, animations: { () -> Void in self.profileImageView.transform = CGAffineTransform(scaleX: 1, y: 1) self.profileImageView.alpha = 1 }, completion: nil ) } }
e57f2a04610c45184d4c836ec0151307
29.21875
159
0.648397
false
false
false
false
Ivacker/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01170-getselftypeforcontainer.swift
apache-2.0
10
// RUN: not %target-swift-frontend %s -parse // REQUIRES: asserts // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class k<g>: d { var f: g init(f: g) { l. d { typealias j = je: Int -> Int = { } let d: Int = { c, b in }(f, e) } class d { func l<j where j: h, j: d>(l: j) { } func i(k: b) -> <j>(() -> j) -> b { } class j { func y((Any, j))(v: (Any, AnyObject)) { } } func w(j: () -> ()) { } class v { l _ = w() { } } func v<x>() -> (x, x -> x) -> x { l y j s<q : l, y: l m y.n == q.n> { } o l { } y q<x> { } o n { } class r { func s() -> p { } } class w: r, n { } func b<c { enum b { } } } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { } protocol e { } protocol i : d { func d
4163a7151a00eb1a916afd2fb4e360fb
12.816667
87
0.512666
false
false
false
false
thankmelater23/relliK
refs/heads/master
relliK/GameOverScene.swift
unlicense
1
// // GameOverScene.swift // TillTheeEnd // // Created by Andre Villanueva on 7/19/15. // Copyright © 2015 Bang Bang Studios. All rights reserved. // import Foundation import SpriteKit class GameOverScene: SKScene { let won: Bool init(size: CGSize, won: Bool) { self.won = won super.init(size: size) } override func didMove(to view: SKView) { var background: SKSpriteNode if(won) { background = SKSpriteNode(imageNamed: "YouWin") run(SKAction.sequence([ SKAction.wait(forDuration: 0.1), SKAction.playSoundFileNamed("win.wav", waitForCompletion: false) ])) } else { background = SKSpriteNode(imageNamed: "YouLose") run(SKAction.sequence([ SKAction.wait(forDuration: 0.1), SKAction.playSoundFileNamed("lose.wave", waitForCompletion: false) ])) } background.position = CGPoint(x: self.size.width/2, y: self.size.height/2) self.addChild(background) let wait = SKAction.wait(forDuration: 3.0) let block = SKAction.run { let myScene = MainMenuScene(size: self.size) myScene.scaleMode = self.scaleMode let reveal = SKTransition.flipHorizontal(withDuration: 0.5) self.view?.presentScene(myScene, transition: reveal) } self.run(SKAction.sequence([wait, block])) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
a83993af0dc1ed34de01d52ba1cc9ac5
29.148148
82
0.58231
false
false
false
false
bykoianko/omim
refs/heads/master
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/UGC/UGCReviewCell.swift
apache-2.0
5
@objc(MWMUGCReviewCell) final class UGCReviewCell: MWMTableViewCell { @IBOutlet private weak var titleLabel: UILabel! { didSet { titleLabel.font = UIFont.bold14() titleLabel.textColor = UIColor.blackPrimaryText() } } @IBOutlet private weak var dateLabel: UILabel! { didSet { dateLabel.font = UIFont.regular12() dateLabel.textColor = UIColor.blackSecondaryText() } } @IBOutlet private weak var ratingView: RatingSummaryView! { didSet { ratingView.defaultConfig() ratingView.textFont = UIFont.bold16() ratingView.textSize = 16 } } @IBOutlet private weak var reviewLabel: ExpandableTextView! { didSet { reviewLabel.textFont = UIFont.regular14() reviewLabel.textColor = UIColor.blackPrimaryText() reviewLabel.expandText = L("placepage_more_button") reviewLabel.expandTextColor = UIColor.linkBlue() } } @objc func config(review: UGCReview, onUpdate: @escaping () -> Void) { titleLabel.text = review.title dateLabel.text = review.date reviewLabel.text = review.text reviewLabel.onUpdate = onUpdate ratingView.value = review.rating.value ratingView.type = review.rating.type isSeparatorHidden = true } }
a945c45c04a5cf245f28326604987b29
28
72
0.692061
false
false
false
false
irealme/MapManager
refs/heads/master
Maptest/Maptest/ViewController.swift
mit
1
// // ViewController.swift // Maptest // // Created by Jimmy Jose on 18/08/14. // // // 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 MapKit class ViewController: UIViewController,UITextFieldDelegate,MKMapViewDelegate,UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate{ @IBOutlet var mapView:MKMapView? = MKMapView() @IBOutlet var textfieldTo:UITextField? = UITextField() @IBOutlet var textfieldFrom:UITextField? = UITextField() @IBOutlet var textfieldToCurrentLocation:UITextField? = UITextField() @IBOutlet var textView:UITextView? = UITextView() @IBOutlet var tableView:UITableView? = UITableView() var tableData = NSArray() var mapManager = MapManager() var locationManager: CLLocationManager! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLoad() { super.viewDidLoad() //[CLLocationManager requestWhenInUseAuthorization]; //[CLLocationManager requestAlwaysAuthorization] let address = "1 Infinite Loop, CA, USA" textfieldTo?.delegate = self textfieldFrom?.delegate = self self.mapView?.delegate = self } func mapViewWillStartLocatingUser(mapView: MKMapView!) { } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if overlay is MKPolyline { var polylineRenderer = MKPolylineRenderer(overlay: overlay) polylineRenderer.strokeColor = UIColor.blueColor() polylineRenderer.lineWidth = 5 println("done") return polylineRenderer } return nil } func numberOfSectionsInTableView(tableView: UITableView) -> Int{ return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return tableData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "direction") var idx:Int = indexPath.row var dictTable:NSDictionary = tableData[idx] as NSDictionary var instruction = dictTable["instructions"] as NSString var distance = dictTable["distance"] as NSString var duration = dictTable["duration"] as NSString var detail = "distance:\(distance) duration:\(duration)" cell.textLabel.text = instruction cell.backgroundColor = UIColor.clearColor() cell.textLabel.font = UIFont(name: "Helvetica Neue Light", size: 15.0) cell.selectionStyle = UITableViewCellSelectionStyle.None //cell.textLabel.font= [UIFont fontWithName:"Helvetica Neue-Light" size:15]; cell.detailTextLabel!.text = detail return cell } @IBAction func usingGoogleButtonPressed(sender:UIButton){ var origin = textfieldFrom?.text var destination = textfieldTo?.text origin = origin?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) destination = destination?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if(origin == nil || (countElements(origin!) == 0) || destination == nil || countElements(destination!) == 0) { println("enter to and from") return } self.view.endEditing(true) mapManager.directionsUsingGoogle(from: origin!, to: destination!) { (route,directionInformation, boundingRegion, error) -> () in if(error != nil){ println(error) }else{ var pointOfOrigin = MKPointAnnotation() pointOfOrigin.coordinate = route!.coordinate pointOfOrigin.title = directionInformation?.objectForKey("start_address") as NSString pointOfOrigin.subtitle = directionInformation?.objectForKey("duration") as NSString var pointOfDestination = MKPointAnnotation() pointOfDestination.coordinate = route!.coordinate pointOfDestination.title = directionInformation?.objectForKey("end_address") as NSString pointOfDestination.subtitle = directionInformation?.objectForKey("distance") as NSString var start_location = directionInformation?.objectForKey("start_location") as NSDictionary var originLat = start_location.objectForKey("lat")?.doubleValue var originLng = start_location.objectForKey("lng")?.doubleValue var end_location = directionInformation?.objectForKey("end_location") as NSDictionary var destLat = end_location.objectForKey("lat")?.doubleValue var destLng = end_location.objectForKey("lng")?.doubleValue var coordOrigin = CLLocationCoordinate2D(latitude: originLat!, longitude: originLng!) var coordDesitination = CLLocationCoordinate2D(latitude: destLat!, longitude: destLng!) pointOfOrigin.coordinate = coordOrigin pointOfDestination.coordinate = coordDesitination if let web = self.mapView?{ dispatch_async(dispatch_get_main_queue()) { self.removeAllPlacemarkFromMap(shouldRemoveUserLocation: true) web.addOverlay(route!) web.addAnnotation(pointOfOrigin) web.addAnnotation(pointOfDestination) web.setVisibleMapRect(boundingRegion!, animated: true) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableData = directionInformation?.objectForKey("steps") as NSArray self.tableView?.reloadData() } } } } } @IBAction func usingAppleButtonPressed(sender:UIButton){ var destination = textfieldToCurrentLocation?.text if(destination == nil || countElements(destination!) == 0) { println("enter to and from") return } self.view.endEditing(true) locationManager = CLLocationManager() locationManager.delegate = self // locationManager.locationServicesEnabled locationManager.desiredAccuracy = kCLLocationAccuracyBest if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) { //locationManager.requestAlwaysAuthorization() // add in plist NSLocationAlwaysUsageDescription locationManager.requestWhenInUseAuthorization() // add in plist NSLocationWhenInUseUsageDescription } //var location = self.mapView?.userLocation //var from = location?.coordinate } func getDirectionsUsingApple() { var destination = textfieldToCurrentLocation?.text mapManager.directionsFromCurrentLocation(to: destination!) { (route, directionInformation, boundingRegion, error) -> () in if (error? != nil) { println(error!) }else{ if let web = self.mapView?{ dispatch_async(dispatch_get_main_queue()) { self.removeAllPlacemarkFromMap(shouldRemoveUserLocation: true) web.addOverlay(route!) web.setVisibleMapRect(boundingRegion!, animated: true) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableData = directionInformation?.objectForKey("steps") as NSArray self.tableView?.reloadData() } } } } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var hasAuthorised = false var locationStatus:NSString = "" var verboseKey = status switch status { case CLAuthorizationStatus.Restricted: locationStatus = "Restricted Access" case CLAuthorizationStatus.Denied: locationStatus = "Denied access" case CLAuthorizationStatus.NotDetermined: locationStatus = "Not determined" default: locationStatus = "Allowed access" hasAuthorised = true } if(hasAuthorised == true){ getDirectionsUsingApple() }else { println("locationStatus \(locationStatus)") } } func removeAllPlacemarkFromMap(#shouldRemoveUserLocation:Bool){ if let mapView = self.mapView { for annotation in mapView.annotations{ if shouldRemoveUserLocation { if annotation as? MKUserLocation != mapView.userLocation { mapView.removeAnnotation(annotation as MKAnnotation) } } } } } }
f7d8a4135a0c5928645915723cf34015
35.006309
145
0.580953
false
false
false
false
nderkach/FlightKit
refs/heads/master
Pod/Classes/ResultsViewController.swift
mit
1
// // ResultsViewController.swift // Pods // // Created by Nikolay Derkach on 10/4/15. // // import UIKit import Alamofire import SwiftyJSON class ResultsViewController: UITableViewController { var fromAirport: String? var toAirport: String? var departDate: NSDate? var results: [JSON]? = [] { didSet { if let _ = self.results { self.tableView.reloadData() } } } var backgroundView = UIImageView() override func viewDidLoad() { super.viewDidLoad() backgroundView.frame = self.tableView.frame self.tableView.backgroundView = backgroundView self.tableView.tableFooterView = UIView(frame: CGRectZero) print("load") self.setImageForAirport(toAirport!) SwiftSpinner.show("Connecting to satellite...") print(self.fromAirport, self.toAirport, self.departDate) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "YYYY-MM-dd" let departDateString = dateFormatter.stringFromDate(departDate!) Alamofire.request(.GET, "https://booq-api.herokuapp.com/search", headers: ["Accept": "application/json"], parameters: ["departureAirport": self.fromAirport!, "arrivalAirport": self.toAirport!, "departureDate": departDateString]) .responseJSON { (_, _, data) in if (data.isFailure) { print("error") } else { self.results = JSON(data.value!).array print(self.results) SwiftSpinner.hide() } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } func setImageForAirport(airport: String) { backgroundView.imageFromUrl(("https://media.expedia.com/mobiata/mobile/apps/ExpediaBooking/FlightDestinations/images/\(airport).jpg")) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ResultCell") as! ResultsTableViewCell cell.priceLabel.text = self.results![indexPath.row]["totalFarePrice"]["formattedPrice"].stringValue cell.typeLabel.text = self.results![indexPath.row]["type"].stringValue return cell; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let results = self.results { return results.count } else { return 0 } } } public class ResultsTableViewCell: UITableViewCell { @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) as UIVisualEffectView override public func awakeFromNib() { super.awakeFromNib() self.visualEffectView.frame = self.frame self.insertSubview(self.visualEffectView, atIndex: 0) } }
4487f4d5dfff12101634d1cb70409113
30.887755
236
0.62624
false
false
false
false
LuckyChen73/CW_WEIBO_SWIFT
refs/heads/master
WeiBo/WeiBo/Classes/View(视图)/Main(主控制器)/WBMainController.swift
mit
1
// // WBMainController.swift // WeiBo // // Created by chenWei on 2017/4/2. // Copyright © 2017年 陈伟. All rights reserved. // import UIKit class WBMainController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() //创建及设置 UI setupUI() //设置tabbar的阴影线条 setupShadowImage() //添加新特性和欢迎页 addNewFeatureAndWelcomeView() } //添加新特性和欢迎页 func addNewFeatureAndWelcomeView() { let isNewFeature = Bundle.main.isNewFeature //判断是否有新特性 // let isNewFeature = true //判断是否是新特性界面 if (WBUserAccount.shared.isLogIn == true) { if isNewFeature == true { //展示新特性界面 let newFeatureView = WBNewFetureView() self.view.addSubview(newFeatureView) }else { //展示欢迎页 let welcomeView = WBWelcomeView() self.view.addSubview(welcomeView) } } } /// 设置tabbar的阴影线条, 下面的两个属性必须都要设 func setupShadowImage () { tabBar.backgroundImage = UIImage(named: "tabbar_background") tabBar.shadowImage = UIImage.pureImage(color: UIColor(white: 0.9, alpha: 0.9)) } } // MARK: - 点击事件 extension WBMainController { ///一旦事件使用了 fileprivate 或 private修饰,就必须加一个 @objc 修饰 @objc fileprivate func composeMessage(button: UIButton) { if WBUserAccount.shared.isLogIn { let compose = WBComposeViewController() let nav = UINavigationController(rootViewController: compose) present(nav, animated: true, completion: nil) } else { let login = WBLogInController() let nav = UINavigationController(rootViewController: login) present(nav, animated: true, completion: nil) } } } // MARK: - 创建 UI extension WBMainController { //创建 UI fileprivate func setupUI() { view.backgroundColor = UIColor.white //添加子控制器 addChildVC() //添加发布按钮 addComposeButton() } //添加发布按钮 fileprivate func addComposeButton() { let button = UIButton(title: nil, target: self, selector: #selector(composeMessage(button:)), events: UIControlEvents.touchUpInside, image: "tabbar_compose_icon_add", bgImage: "tabbar_compose_button") //设置 frame let width = tabBar.frame.width / 5 //insetBy:以 tabbar 的中心点为原点,向内或向外扩张,所以此处必须调用 bounds button.frame = tabBar.bounds.insetBy(dx: width*2 - 3, dy: 6) tabBar.addSubview(button) } //添加子控制器 fileprivate func addChildVC() { //解析 json 文件 //获取 json 文件 if let url = Bundle.main.url(forResource: "main.json", withExtension: nil), //将 url 文件转化成数据 let object = try? Data(contentsOf: url), //反序列化得到可选Any值,进行强转成字典数组 let dictArr = try? JSONSerialization.jsonObject(with: object, options: []) as! [[String: Any]] { //存储导航控制器的数组 var viewControllers: [UINavigationController] = [] for dict in dictArr { if let nav = generateSingleVC(dict: dict) { viewControllers.append(nav) } } self.viewControllers = viewControllers } } //创建单个子控制器 fileprivate func generateSingleVC(dict: [String: Any]) -> UINavigationController? { if let clsName = dict["clsName"] { //在 swift 中,字符串转换成类前面要添加类名 let className = "WeiBo" + "." + "\(clsName as! String)" //as? UIViewController.Type 以什么类型的样式 if let cls = NSClassFromString(className) as? WBRootController.Type { let controller = cls.init() controller.title = dict["title"] as! String? controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.gray], for: .normal) //这里设置底部 tabbar 的图标样式的时候,设置的是 button 的样式,所以要根据 button 来设置 controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected) if let imageName = dict["imageName"] { //tabbar_home let image = UIImage(named: "tabbar_\(imageName)") controller.tabBarItem.image = image?.withRenderingMode(.alwaysOriginal) //tabbar_home_selected let selectImage = UIImage(named: "tabbar_\(imageName)_selected") controller.tabBarItem.selectedImage = selectImage?.withRenderingMode(.alwaysOriginal) } //将访客视图文本和图标的信息赋值给 controller controller.visitorDic = dict["visitorInfo"] as? [String: Any] return UINavigationController(rootViewController: controller) } } return nil } }
a732e0c58630c16d53332d8762e7b340
28.085227
208
0.560656
false
false
false
false
kandelvijaya/XcodeFormatter
refs/heads/master
XcodeFormatterTests/CodeBlockAnalyzerTests.swift
mit
1
// // CodeAnalyzerTests.swift // Swinter // // Created by Vijaya Prakash Kandel on 9/20/16. // Copyright © 2016 Vijaya Prakash Kandel. All rights reserved. // import XCTest @testable import XcodeFormatter extension CodePosition: Equatable { static func ==(lhs: CodePosition, rhs: CodePosition) -> Bool { let conditions = [lhs.line == rhs.line, lhs.indicator == rhs.indicator, lhs.section == rhs.section, lhs.lineContent == rhs.lineContent] let satisfied = conditions.filter { $0 } return satisfied.count == conditions.count } } class CodeBlockAnalyzerTests: XCTestCase { func testThat_AnEmptyClass_IsCountedAsSingleCodeBlock() { let input = ["class A{\n", "}\n"] let opening = CodePosition(lineContent: "class A{\n", line: 0, section: 7, indicator: .opening) let closing = CodePosition(lineContent: "}\n", line: 1, section: 0, indicator: .closing) let expected = CodeBlock(startPosition: opening, endPosition: closing) guard let output = CodeBlockAnalyzer().codeBlocks(for: input).first else { XCTFail("Couldnt get codeblock from a empty class declaration") return } XCTAssertEqual(expected.start, output.start) XCTAssertEqual(expected.end, output.end) XCTAssertEqual(expected.type, output.type) } func testThat_IncompleteClassDeclaration_IsNotCountedAsCodeBlock() { let input = ["class A{\n", "private let x:Int"] let output = CodeBlockAnalyzer().codeBlocks(for: input) XCTAssert(output.count == 0) } func testThat_EmptyProtocolDefinedInOneLine_IsCountedAsCodeBlock() { let input = ["protocol Empty { }\n"] let opening = CodePosition(lineContent: "protocol Empty { }\n", line: 0, section: 15, indicator: .opening) let closing = CodePosition(lineContent: "protocol Empty { }\n", line: 0, section: 17, indicator: .closing) let expected = CodeBlock(startPosition: opening, endPosition: closing) guard let output = CodeBlockAnalyzer().codeBlocks(for: input).first else { XCTFail("Couldnt get codeblock from a empty class declaration") return } XCTAssertEqual(expected.start, output.start) XCTAssertEqual(expected.end, output.end) XCTAssertEqual(output.type, CodeBlockType.ProtocolKind) } func testThat_FunctionDeclaration_HasTypeOfFunctionKind() { let input = ["func do(){\n","}\n"] guard let output = CodeBlockAnalyzer().codeBlocks(for: input).first else { XCTFail("Something went wrong during code analyzation") return } XCTAssert(output.type == CodeBlockType.FunctionKind) } func testThat_IfElseBlock_HasTypeOfOther() { let input = ["if isThat(){\n","}else{\n", "}\n"] let outputs = CodeBlockAnalyzer().codeBlocks(for: input) outputs.forEach{ XCTAssertNotNil($0.type) XCTAssertEqual($0.type!, CodeBlockType.OtherKind) } } func testThat_StructDeclaration_HasStructType() { let input = ["struct A { }\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input).first! XCTAssertNotNil(output.type) XCTAssertEqual(output.type!, CodeBlockType.StructKind) } func testThat_EnumDeclaration_HasEnumType() { let input = ["enum A { case .a; }\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input).first! XCTAssertNotNil(output.type) XCTAssertEqual(output.type!, CodeBlockType.EnumKind) } func testThat_ExtensionHas_ExtensionType() { let input = ["extension A: AnyObject { }\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input).first! XCTAssertNotNil(output.type) XCTAssertEqual(output.type!, CodeBlockType.ExtensionKind) } //Complex tests with inner blocks func testThat_InnerClass_IsAlsoIdentifiedAsCodeBlock() { let input = ["class A{ class B{} }\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input) XCTAssert(output.count == 2) output.forEach { XCTAssertEqual($0.type!, CodeBlockType.ClassKind) } } //Nested codeblocks are identified from inside out. //Innermost will be identified and inserted first than the outermost. func testThat_NestedEnumInsideAStruct_IsIdentified() { let input = ["struct A {\n", "enum Type{\n", "case .a, .b\n", "}\n", "}\n", "\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input) let enumCodeBlock = output[0] let structCodeBlock = output[1] XCTAssert(structCodeBlock.type! == CodeBlockType.StructKind) XCTAssert(enumCodeBlock.type! == CodeBlockType.EnumKind) } func testThat_ProtocolConformingToClass_IsIdentified() { let input = ["protocol A: class {\n", " }\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input) XCTAssert(output[0].type! == CodeBlockType.ProtocolKind) } func testPerformanceOfCodeBlockAnalyzer() { let singleItem = ["struct A {\n", "enum Type{\n", "case .a, .b\n", "}\n", "}\n", "\n"] let inputCode = (0..<1000).map{_ in singleItem }.reduce([String]()) { $0 + $1 } self.measure { let output = CodeBlockAnalyzer().codeBlocks(for: inputCode) XCTAssert(output.count == 2000) } } func testThat_DeclarationInsideAStringQuote_AreNotCounted() { let input = ["let a = \"protocol A: class {\"\n", "\" }\"\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input) XCTAssert(output.count == 0) } func testThat_DeclarationInsideAStringQuote_Mismatched_AreNotCounted() { let input = ["let a = \"protocol A: class {\"\n", "}\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input) XCTAssert(output.count == 0) } func testThat_DeclarationInsideSingleComment_AreNotCounted() { let input = ["/// protocol A: class {\n", "/// }\n"] let output = CodeBlockAnalyzer().codeBlocks(for: input) XCTAssert(output.count == 0) } }
f57a080cc0e5fde410d0f02471339518
34.184783
143
0.609206
false
true
false
false
easyui/EZPlayer
refs/heads/master
EZPlayer/EZPlayerAudibleLegibleViewController.swift
mit
1
// // EZPlayerAudibleLegibleViewController.swift // EZPlayer // // Created by yangjun zhu on 2016/12/28. // Copyright © 2016年 yangjun zhu. All rights reserved. // import UIKit import AVFoundation public struct MediaTypes: OptionSet { public let rawValue: Int public static let audios = MediaTypes(rawValue: 1 << 0) public static let closedCaption = MediaTypes(rawValue: 1 << 1) public static let subtitles = MediaTypes(rawValue: 1 << 2) public init(rawValue: Int) { self.rawValue = rawValue } } open class EZPlayerAudibleLegibleViewController: UIViewController { fileprivate let mediaTypeTableViewIdentifier = "mediaTypeTableViewIdentifier" fileprivate let audioTitle = "Audios" fileprivate let subtitleTitle = "Subtitles" fileprivate let closedCaptionTitle = "CC" fileprivate let sectionHeight: CGFloat = 44.0 fileprivate let cellHeight: CGFloat = 44.0 fileprivate weak var player: EZPlayer! fileprivate var audios: [(audio: AVMediaSelectionOption,localDisplayName: String)]? fileprivate var closedCaption: [AVMediaSelectionOption]? fileprivate var subtitles: [(subtitle: AVMediaSelectionOption,localDisplayName: String)]? fileprivate var mediaTypes: MediaTypes = [] // MARK: - Life cycle init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?,player: EZPlayer, sourceView: UIView? = nil ,barButtonItem:UIBarButtonItem? = nil) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.modalPresentationStyle = .popover guard let popoverPresentationController = self.popoverPresentationController else { return } if sourceView != nil { popoverPresentationController.sourceView = sourceView popoverPresentationController.sourceRect = sourceView!.bounds } if barButtonItem != nil { popoverPresentationController.barButtonItem = barButtonItem } popoverPresentationController.permittedArrowDirections = .down popoverPresentationController.backgroundColor = UIColor.white popoverPresentationController.delegate = self self.player = player self.audios = self.player.playerasset?.audios self.closedCaption = self.player.playerasset?.closedCaption self.subtitles = self.player.playerasset?.subtitles if let audios = self.audios ,audios.count > 0{ self.mediaTypes = mediaTypes.union([.audios]) } if let subtitles = self.subtitles ,subtitles.count > 0{ self.mediaTypes = mediaTypes.union([.subtitles]) } if let closedCaption = self.closedCaption ,closedCaption.count > 0{ self.mediaTypes = mediaTypes.union([.closedCaption]) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.player.pause() } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.player.play() } open override var preferredContentSize: CGSize{ get{ var lines = (self.audios?.count ?? 0) lines += lines > 0 ? 1 : 0 var secendLines = (self.subtitles?.count ?? 0) + (self.closedCaption?.count ?? 0) secendLines += secendLines > 0 ? 2 : 0 return CGSize(width: CGFloat(480), height: CGFloat( (lines + secendLines + 1) * 44 )) } set{ super.preferredContentSize = newValue } } // MARK: - Orientations override open var shouldAutorotate : Bool { return true } override open var supportedInterfaceOrientations : UIInterfaceOrientationMask { return [.all] } } extension EZPlayerAudibleLegibleViewController: UIPopoverPresentationControllerDelegate { public func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { if UIDevice.current.userInterfaceIdiom == .pad { return .none }else{ return .fullScreen } } public func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { if UIDevice.current.userInterfaceIdiom == .pad { return .none }else{ return .fullScreen } } public func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? { let navigationController = UINavigationController(rootViewController: controller.presentedViewController) let btnDone = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.dismissPop)) navigationController.topViewController!.navigationItem.rightBarButtonItem = btnDone return navigationController } @objc func dismissPop() { self.dismiss(animated: true, completion: nil) } } extension EZPlayerAudibleLegibleViewController: UITableViewDataSource,UITableViewDelegate { public func numberOfSections(in tableView: UITableView) -> Int { var num = 0 if self.mediaTypes.contains(.audios) { num += 1 } if self.mediaTypes.contains(.subtitles) || self.mediaTypes.contains(.closedCaption){ num += 1 } return num } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = "" if section == 0{ if self.mediaTypes.contains(.audios) { title = self.audioTitle return title } } if self.mediaTypes.contains(.subtitles) { title = self.subtitleTitle } if self.mediaTypes.contains(.closedCaption) { title += (title == "" ? self.closedCaptionTitle : "&\(self.closedCaptionTitle)") } return title } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{ return self.sectionHeight } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{ return 0 } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.cellHeight } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var num = 0 if section == 0{ if self.mediaTypes.contains(.audios) { return self.audios?.count ?? 0 } } if self.mediaTypes.contains(.subtitles) { num = self.subtitles?.count ?? 0 } if self.mediaTypes.contains(.closedCaption) { num += self.closedCaption?.count ?? 0 } return num + 1 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: self.mediaTypeTableViewIdentifier) if cell == nil{ cell = UITableViewCell(style: .default, reuseIdentifier: self.mediaTypeTableViewIdentifier) } if indexPath.section == 0{ if self.mediaTypes.contains(.audios) { if let audio = self.audios?[indexPath.row]{ cell.textLabel?.text = "\(audio.localDisplayName) (\(audio.audio.displayName))" cell.accessoryType = audio.audio == self.player.playerItem?.selectedMediaCharacteristicAudibleOption ? .checkmark : .none } return cell } } if indexPath.row == 0 { cell.textLabel?.text = "None" cell.accessoryType = self.player.playerItem?.selectedMediaCharacteristicLegibleOption == nil ? .checkmark : .none return cell } var row = indexPath.row - 1 if self.mediaTypes.contains(.subtitles) && self.mediaTypes.contains(.closedCaption){ if let subtitles = self.subtitles , let closedCaption = self.closedCaption{ if row < subtitles.count { let subtitle = subtitles[row] cell.textLabel?.text = "\(subtitle.localDisplayName) (\(subtitle.subtitle.displayName))" cell.accessoryType = subtitle.subtitle == self.player.playerItem?.selectedSubtitleOption ? .checkmark : .none }else{ row = row - subtitles.count let closedCaption = closedCaption[row] cell.textLabel?.text = "\(closedCaption.displayName)\(row)" cell.accessoryType = closedCaption == self.player.playerItem?.selectedClosedCaptionOption ? .checkmark : .none } } }else if self.mediaTypes.contains(.subtitles) { if let subtitle = self.subtitles?[row] { cell.textLabel?.text = "\(subtitle.localDisplayName) (\(subtitle.subtitle.displayName))" cell.accessoryType = subtitle.subtitle == self.player.playerItem?.selectedSubtitleOption ? .checkmark : .none } }else if self.mediaTypes.contains(.closedCaption) { if let closedCaption = self.closedCaption?[row]{ cell.textLabel?.text = "\(closedCaption.displayName)\(row)" cell.accessoryType = closedCaption == self.player.playerItem?.selectedClosedCaptionOption ? .checkmark : .none } } return cell } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0{ if self.mediaTypes.contains(.audios) { if let audio = self.audios?[indexPath.row]{ self.player.playerItem?.selectedMediaCharacteristicAudibleOption = audio.audio tableView.reloadSections(IndexSet(integer: indexPath.section), with: .none) } return } } if indexPath.row == 0 { self.player.playerItem?.selectedMediaCharacteristicLegibleOption = nil tableView.reloadSections(IndexSet(integer: indexPath.section), with: .none) return } var row = indexPath.row - 1 if self.mediaTypes.contains(.subtitles) && self.mediaTypes.contains(.closedCaption){ if let subtitles = self.subtitles , let closedCaption = self.closedCaption{ if row < subtitles.count { let subtitle = subtitles[row] self.player.playerItem?.selectedSubtitleOption = subtitle.subtitle }else{ row = row - subtitles.count let closedCaption = closedCaption[row] self.player.playerItem?.selectedClosedCaptionOption = closedCaption } } }else if self.mediaTypes.contains(.subtitles) { if let subtitle = self.subtitles?[row] { self.player.playerItem?.selectedSubtitleOption = subtitle.subtitle } }else if self.mediaTypes.contains(.closedCaption) { if let closedCaption = self.closedCaption?[row]{ self.player.playerItem?.selectedClosedCaptionOption = closedCaption } } tableView.reloadSections(IndexSet(integer: indexPath.section), with: .none) } }
d81b644852f7e4dfb9e7fb5bc1d98c42
37.477564
177
0.634985
false
false
false
false
jimhqin/JQImageViewController
refs/heads/master
JQImageViewControllerDemo/RootViewController.swift
mit
1
// // RootViewController.swift // JQImageViewControllerDemo // // Created by JQ@Onbeep on 11/4/15. // Copyright © 2015 Jim Qin. All rights reserved. // import UIKit final class RootViewController: UIViewController, RootViewDelegate { override func loadView() { let contentView = RootView(frame: UIScreen.mainScreen().bounds) contentView.delegate = self view = contentView } func didPressDemoButton() { let imageViewController = JQImageViewController() let navigationController = UINavigationController(rootViewController: imageViewController) navigationController.navigationBar.topItem?.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .Cancel, target: self, action: "didPressCancel" ) navigationController.modalPresentationStyle = .OverCurrentContext presentViewController(navigationController, animated: true, completion: nil) } func didPressCancel() { dismissViewControllerAnimated(true, completion: nil) } }
484cefcda611cff59b5e568fb612ec6d
29.6
98
0.702148
false
false
false
false
danpratt/On-the-Map
refs/heads/master
On the Map/Reachability.swift
mit
1
// // Reachability.swift // On the Map // // Found at http://stackoverflow.com/questions/25398664/check-for-internet-connection-availability-in-swift // // Adapted by Daniel Pratt on 4/6/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } /* Only Working for WIFI let isReachable = flags == .reachable let needsConnection = flags == .connectionRequired return isReachable && !needsConnection */ // Working for Cellular and WIFI let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } }
4b82d90931c87e00366c22c495e2f4ec
34.829787
143
0.637173
false
false
false
false
ludoded/ReceiptBot
refs/heads/master
ReceiptBot/Helper/Formatter/DateFormaters.swift
lgpl-3.0
1
// // DateFormaters.swift // ReceiptBot // // Created by Haik Ampardjian on 4/5/17. // Copyright © 2017 receiptbot. All rights reserved. // import Foundation struct DateFormatters { static var mdytaFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "MMM dd yyyy HH:mma" return formatter } static var mFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "MMM" return formatter } static var mdySpaceFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "MMM dd yyyy" return formatter } static var mdyFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "MM/dd/yyyy" return formatter } static var myFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "MM/yyyy" return formatter } }
9083b7f7452f269f86410a8ee93960b7
22
53
0.606805
false
false
false
false
grandiere/box
refs/heads/master
box/View/Help/VHelpCell.swift
mit
1
import UIKit class VHelpCell:UICollectionViewCell { private weak var imageView:UIImageView! private weak var label:UILabel! private weak var layoutLabelHeight:NSLayoutConstraint! private let drawingOptions:NSStringDrawingOptions private let labelMargin2:CGFloat private let kLabelMargin:CGFloat = 20 private let kLabelMaxHeight:CGFloat = 900 private let kImageHeight:CGFloat = 240 override init(frame:CGRect) { drawingOptions = NSStringDrawingOptions([ NSStringDrawingOptions.usesLineFragmentOrigin, NSStringDrawingOptions.usesFontLeading]) labelMargin2 = kLabelMargin + kLabelMargin super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear isUserInteractionEnabled = false let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = UIViewContentMode.center imageView.clipsToBounds = true self.imageView = imageView let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.textAlignment = NSTextAlignment.center label.numberOfLines = 0 self.label = label addSubview(label) addSubview(imageView) NSLayoutConstraint.topToTop( view:imageView, toView:self) NSLayoutConstraint.height( view:imageView, constant:kImageHeight) NSLayoutConstraint.equalsHorizontal( view:imageView, toView:self) NSLayoutConstraint.topToBottom( view:label, toView:imageView) layoutLabelHeight = NSLayoutConstraint.height( view:label) NSLayoutConstraint.equalsHorizontal( view:label, toView:self, margin:kLabelMargin) } required init?(coder:NSCoder) { return nil } //MARK: public func config(model:MHelpProtocol) { imageView.image = model.image let attributedText:NSAttributedString = model.message label.attributedText = model.message let width:CGFloat = bounds.maxX let usableWidth:CGFloat = width - labelMargin2 let usableSize:CGSize = CGSize( width:usableWidth, height:kLabelMaxHeight) let textRect:CGRect = attributedText.boundingRect( with:usableSize, options:drawingOptions, context:nil) let textHeight:CGFloat = ceil(textRect.size.height) layoutLabelHeight.constant = textHeight } }
e0b9dad484ddbfe634434c145e2bb66e
30.791209
67
0.64224
false
false
false
false
Motsai/neblina-motiondemo-swift
refs/heads/master
ExerciseMotionTracker/iOS/ExerciseMotionTracker/AppDelegate.swift
mit
2
// // AppDelegate.swift // ExerciseMotionTracker // // Created by Hoan Hoang on 2015-11-24. // Copyright © 2015 Hoan Hoang. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self 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:. } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.nebdev == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
bfa7a29b1ec4aa27007f23f1b222b98a
51.196721
279
0.796168
false
false
false
false
lukevanin/onthemap
refs/heads/master
OnTheMap/User.swift
mit
1
// // User.swift // OnTheMap // // Created by Luke Van In on 2017/01/14. // Copyright © 2017 Luke Van In. All rights reserved. // // Information specific to the user, e.g. name and surname. // import Foundation struct User { let firstName: String let lastName: String } // // Extension for serializing a user to JSON compatible data. // extension User: JSONEntity { init(json: Any) throws { guard let entity = json as? [String: Any] else { throw JSONError.format("dictionary") } guard let user = entity["user"] as? [String: Any] else { throw JSONError.field("user") } guard let firstName = user["first_name"] as? String else { throw JSONError.field("user.first_name") } guard let lastName = user["last_name"] as? String else { throw JSONError.field("user.last_name") } self.firstName = firstName self.lastName = lastName } }
9df1f4476e3f5eef6fa35c3d76ab906b
24.736842
66
0.600204
false
false
false
false
russellladd/CardsAgainstHumanity
refs/heads/master
CardsAgainstHumanity/Browser.swift
mit
1
// // Browser.swift // CardsAgainstHumanity // // Created by Russell Ladd on 10/18/14. // Copyright (c) 2014 GRL5. All rights reserved. // import Foundation import MultipeerConnectivity struct Device { let peerID: MCPeerID let type: UIUserInterfaceIdiom let name: String } protocol BrowserDelegate: class { func browser(browser: Browser, didNotStartBrowsingError error: NSError) func browser(browser: Browser, insertDeviceAtIndex index: Int) func browser(browser: Browser, deleteDeviceAtIndex index: Int) } class Browser: NSObject, MCNearbyServiceBrowserDelegate { // MARK: Initialization init(session: MCSession, deviceType: UIUserInterfaceIdiom) { self.session = session super.init() browser.delegate = self browser.startBrowsingForPeers() } deinit { browser.stopBrowsingForPeers() } // MARK: Delegate weak var delegate: BrowserDelegate? // MARK: Session let session: MCSession // MARK: Discovered devices var discoveredDevices = [Device]() // MARK: Browser let browser = MCNearbyServiceBrowser(peer: DevicePeerID, serviceType: ServiceType) func inviteDevice(device: Device) { browser.invitePeer(device.peerID, toSession: session, withContext: nil, timeout: 15.0) } // MARK: Browser delegate func browser(browser: MCNearbyServiceBrowser!, didNotStartBrowsingForPeers error: NSError!) { delegate?.browser(self, didNotStartBrowsingError: error) } func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!) { if let dictionary = info as? [String: String] { var type = UIUserInterfaceIdiom.Unspecified switch dictionary["deviceType"]! { case "Phone": type = .Phone case "Pad": type = .Pad default: () } let device = Device(peerID: peerID, type: type, name: dictionary["deviceName"]!) discoveredDevices += [device] delegate?.browser(self, insertDeviceAtIndex: discoveredDevices.count - 1) } } func browser(browser: MCNearbyServiceBrowser!, lostPeer peerID: MCPeerID!) { var index: Int? for i in 0..<discoveredDevices.count { if discoveredDevices[i].peerID == peerID { index = i break; } } if let index = index { discoveredDevices.removeAtIndex(index) delegate?.browser(self, deleteDeviceAtIndex: index) } } }
dcf0071227e0ee12ab592ebbdae7855d
25.027273
130
0.588893
false
false
false
false
dvxiaofan/Pro-Swift-Learning
refs/heads/master
Part-02/18-TupleComparison.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit let singer = (first: "xiaofan", last: "fanfan") let alien = (first: "xiaoming", last: "big") if singer == alien { print("match") } else { print("no match") } let bird = (name: "xiaofan", breed: "fanfan") if singer == bird { print("match") } else { print("no match") }
f35edcc131c3b4d7109e9702cb91cdfb
15.952381
52
0.601124
false
false
false
false
atrick/swift
refs/heads/main
stdlib/public/core/StringGuts.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // // StringGuts is a parameterization over String's representations. It provides // functionality and guidance for efficiently working with Strings. // @frozen public // SPI(corelibs-foundation) struct _StringGuts: @unchecked Sendable { @usableFromInline internal var _object: _StringObject @inlinable @inline(__always) internal init(_ object: _StringObject) { self._object = object _invariantCheck() } // Empty string @inlinable @inline(__always) init() { self.init(_StringObject(empty: ())) } } // Raw extension _StringGuts { @inlinable @inline(__always) internal var rawBits: _StringObject.RawBitPattern { return _object.rawBits } } // Creation extension _StringGuts { @inlinable @inline(__always) internal init(_ smol: _SmallString) { self.init(_StringObject(smol)) } @inlinable @inline(__always) internal init(_ bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) { self.init(_StringObject(immortal: bufPtr, isASCII: isASCII)) } @inline(__always) internal init(_ storage: __StringStorage) { self.init(_StringObject(storage)) } internal init(_ storage: __SharedStringStorage) { self.init(_StringObject(storage)) } internal init( cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int ) { self.init(_StringObject( cocoa: cocoa, providesFastUTF8: providesFastUTF8, isASCII: isASCII, length: length)) } } // Queries extension _StringGuts { // The number of code units @inlinable @inline(__always) internal var count: Int { return _object.count } @inlinable @inline(__always) internal var isEmpty: Bool { return count == 0 } @inlinable @inline(__always) internal var isSmall: Bool { return _object.isSmall } @inline(__always) internal var isSmallASCII: Bool { return _object.isSmall && _object.smallIsASCII } @inlinable @inline(__always) internal var asSmall: _SmallString { return _SmallString(_object) } @inlinable @inline(__always) internal var isASCII: Bool { return _object.isASCII } @inlinable @inline(__always) internal var isFastASCII: Bool { return isFastUTF8 && _object.isASCII } @inline(__always) internal var isNFC: Bool { return _object.isNFC } @inline(__always) internal var isNFCFastUTF8: Bool { // TODO(String micro-performance): Consider a dedicated bit for this return _object.isNFC && isFastUTF8 } internal var hasNativeStorage: Bool { return _object.hasNativeStorage } internal var hasSharedStorage: Bool { return _object.hasSharedStorage } // Whether this string has breadcrumbs internal var hasBreadcrumbs: Bool { return hasSharedStorage || (hasNativeStorage && _object.nativeStorage.hasBreadcrumbs) } } // extension _StringGuts { // Whether we can provide fast access to contiguous UTF-8 code units @_transparent @inlinable internal var isFastUTF8: Bool { return _fastPath(_object.providesFastUTF8) } // A String which does not provide fast access to contiguous UTF-8 code units @inlinable @inline(__always) internal var isForeign: Bool { return _slowPath(_object.isForeign) } @inlinable @inline(__always) internal func withFastUTF8<R>( _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { _internalInvariant(isFastUTF8) if self.isSmall { return try _SmallString(_object).withUTF8(f) } defer { _fixLifetime(self) } return try f(_object.fastUTF8) } @inlinable @inline(__always) internal func withFastUTF8<R>( range: Range<Int>, _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { wholeUTF8 in return try f(UnsafeBufferPointer(rebasing: wholeUTF8[range])) } } @inlinable @inline(__always) internal func withFastCChar<R>( _ f: (UnsafeBufferPointer<CChar>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { utf8 in return try utf8.withMemoryRebound(to: CChar.self, f) } } } // Internal invariants extension _StringGuts { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { #if arch(i386) || arch(arm) || arch(arm64_32) || arch(wasm32) _internalInvariant(MemoryLayout<String>.size == 12, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #else _internalInvariant(MemoryLayout<String>.size == 16, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #endif } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { _object._dump() } } // C String interop extension _StringGuts { @inlinable @inline(__always) // fast-path: already C-string compatible internal func withCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { if _slowPath(!_object.isFastZeroTerminated) { return try _slowWithCString(body) } return try self.withFastCChar { return try body($0.baseAddress._unsafelyUnwrappedUnchecked) } } @inline(never) // slow-path @usableFromInline internal func _slowWithCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { _internalInvariant(!_object.isFastZeroTerminated) return try String(self).utf8CString.withUnsafeBufferPointer { let ptr = $0.baseAddress._unsafelyUnwrappedUnchecked return try body(ptr) } } } extension _StringGuts { // Copy UTF-8 contents. Returns number written or nil if not enough space. // Contents of the buffer are unspecified if nil is returned. @inlinable internal func copyUTF8(into mbp: UnsafeMutableBufferPointer<UInt8>) -> Int? { let ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked if _fastPath(self.isFastUTF8) { return self.withFastUTF8 { utf8 in guard utf8.count <= mbp.count else { return nil } let utf8Start = utf8.baseAddress._unsafelyUnwrappedUnchecked ptr.initialize(from: utf8Start, count: utf8.count) return utf8.count } } return _foreignCopyUTF8(into: mbp) } @_effects(releasenone) @usableFromInline @inline(never) // slow-path internal func _foreignCopyUTF8( into mbp: UnsafeMutableBufferPointer<UInt8> ) -> Int? { #if _runtime(_ObjC) // Currently, foreign means NSString if let res = _cocoaStringCopyUTF8(_object.cocoaObject, into: UnsafeMutableRawBufferPointer(start: mbp.baseAddress, count: mbp.count)) { return res } // If the NSString contains invalid UTF8 (e.g. unpaired surrogates), we // can get nil from cocoaStringCopyUTF8 in situations where a character by // character loop would get something more useful like repaired contents var ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked var numWritten = 0 for cu in String(self).utf8 { guard numWritten < mbp.count else { return nil } ptr.initialize(to: cu) ptr += 1 numWritten += 1 } return numWritten #else fatalError("No foreign strings on Linux in this version of Swift") #endif } @inline(__always) internal var utf8Count: Int { if _fastPath(self.isFastUTF8) { return count } return String(self).utf8.count } } // Index extension _StringGuts { @usableFromInline internal typealias Index = String.Index @inlinable @inline(__always) internal var startIndex: String.Index { // The start index is always `Character` aligned. Index(_encodedOffset: 0)._characterAligned._encodingIndependent } @inlinable @inline(__always) internal var endIndex: String.Index { // The end index is always `Character` aligned. markEncoding(Index(_encodedOffset: self.count)._characterAligned) } } // Encoding extension _StringGuts { /// Returns whether this string has a UTF-8 storage representation. /// If this returns false, then the string is encoded in UTF-16. /// /// This always returns a value corresponding to the string's actual encoding. @_alwaysEmitIntoClient @inline(__always) internal var isUTF8: Bool { _object.isUTF8 } @_alwaysEmitIntoClient // Swift 5.7 @inline(__always) internal func markEncoding(_ i: String.Index) -> String.Index { isUTF8 ? i._knownUTF8 : i._knownUTF16 } /// Returns true if the encoding of the given index isn't known to be in /// conflict with this string's encoding. /// /// If the index was created by code that was built on a stdlib below 5.7, /// then this check may incorrectly return true on a mismatching index, but it /// is guaranteed to never incorrectly return false. If all loaded binaries /// were built in 5.7+, then this method is guaranteed to always return the /// correct value. @_alwaysEmitIntoClient @inline(__always) internal func hasMatchingEncoding(_ i: String.Index) -> Bool { i._hasMatchingEncoding(isUTF8: isUTF8) } /// Return an index whose encoding can be assumed to match that of `self`, /// trapping if `i` has an incompatible encoding. /// /// If `i` is UTF-8 encoded, but `self` is an UTF-16 string, then trap. /// /// If `i` is UTF-16 encoded, but `self` is an UTF-8 string, then transcode /// `i`'s offset to UTF-8 and return the resulting index. This allows the use /// of indices from a bridged Cocoa string after the string has been converted /// to a native Swift string. (Such indices are technically still considered /// invalid, but we allow this specific case to keep compatibility with /// existing code that assumes otherwise.) /// /// Detecting an encoding mismatch isn't always possible -- older binaries did /// not set the flags that this method relies on. However, false positives /// cannot happen: if this method detects a mismatch, then it is guaranteed to /// be a real one. @_alwaysEmitIntoClient @inline(__always) internal func ensureMatchingEncoding(_ i: Index) -> Index { if _fastPath(hasMatchingEncoding(i)) { return i } if let i = _slowEnsureMatchingEncoding(i) { return i } // Note that this trap is not guaranteed to trigger when the process // includes client binaries compiled with a previous Swift release. // (`i._canBeUTF16` can sometimes return true in that case even if the index // actually came from an UTF-8 string.) However, the trap will still often // trigger in this case, as long as the index was initialized by code that // was compiled with 5.7+. // // This trap will rarely if ever trigger on OSes that have stdlibs <= 5.6, // because those versions never set the `isKnownUTF16` flag in // `_StringObject`. (The flag may still be set within inlinable code, // though.) _preconditionFailure("Invalid string index") } /// Return an index that corresponds to the same position as `i`, but whose /// encoding can be assumed to match that of `self`, returning `nil` if `i` /// has incompatible encoding. /// /// If `i` is UTF-8 encoded, but `self` is an UTF-16 string, then return nil. /// /// If `i` is UTF-16 encoded, but `self` is an UTF-8 string, then transcode /// `i`'s offset to UTF-8 and return the resulting index. This allows the use /// of indices from a bridged Cocoa string after the string has been converted /// to a native Swift string. (Such indices are technically still considered /// invalid, but we allow this specific case to keep compatibility with /// existing code that assumes otherwise.) /// /// Detecting an encoding mismatch isn't always possible -- older binaries did /// not set the flags that this method relies on. However, false positives /// cannot happen: if this method detects a mismatch, then it is guaranteed to /// be a real one. internal func ensureMatchingEncodingNoTrap(_ i: Index) -> Index? { if hasMatchingEncoding(i) { return i } return _slowEnsureMatchingEncoding(i) } @_alwaysEmitIntoClient @inline(never) @_effects(releasenone) internal func _slowEnsureMatchingEncoding(_ i: Index) -> Index? { guard isUTF8 else { // Attempt to use an UTF-8 index on a UTF-16 string. Strings don't usually // get converted to UTF-16 storage, so it seems okay to reject this case // -- the index most likely comes from an unrelated string. (This may // still turn out to affect binary compatibility with broken code in // existing binaries running with new stdlibs. If so, we can replace this // with the same transcoding hack as in the UTF-16->8 case below.) return nil } // Attempt to use an UTF-16 index on a UTF-8 string. // // This can happen if `self` was originally verbatim-bridged, and someone // mistakenly attempts to keep using an old index after a mutation. This is // technically an error, but trapping here would trigger a lot of broken // code that previously happened to work "fine" on e.g. ASCII strings. // Instead, attempt to convert the offset to UTF-8 code units by transcoding // the string. This can be slow, but it often results in a usable index, // even if non-ASCII characters are present. (UTF-16 breadcrumbs help reduce // the severity of the slowdown.) // FIXME: Consider emitting a runtime warning here. // FIXME: Consider performing a linked-on-or-after check & trapping if the // client executable was built on some particular future Swift release. let utf16 = String.UTF16View(self) var r = utf16.index(utf16.startIndex, offsetBy: i._encodedOffset) if i.transcodedOffset != 0 { r = r.encoded(offsetBy: i.transcodedOffset) } else { // Preserve alignment bits if possible. r = r._copyingAlignment(from: i) } return r._knownUTF8 } } // Old SPI(corelibs-foundation) extension _StringGuts { @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousASCII: Bool { return !isSmall && isFastUTF8 && isASCII } @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousUTF16: Bool { return false } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startASCII: UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer(mutating: _object.fastUTF8.baseAddress!) } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { fatalError("Not contiguous UTF-16") } } @available(*, deprecated) public // SPI(corelibs-foundation) func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let bytesToCopy = UTF8._nullCodeUnitOffset(in: s) + 1 // +1 for the terminating NUL let result = [CChar](unsafeUninitializedCapacity: bytesToCopy) { buf, initedCount in buf.baseAddress!.assign(from: s, count: bytesToCopy) initedCount = bytesToCopy } return result }
ca2cfae5f73c44acd38ac93ac13fa6a5
32.693966
86
0.685365
false
false
false
false
AceWangLei/BYWeiBo
refs/heads/master
BYWeiBo/BYStatusCell.swift
apache-2.0
1
// // BYStatusCell.swift // BYWeiBo // // Created by qingyun on 16/1/28. // Copyright © 2016年 lit. All rights reserved. // import UIKit import SnapKit /** float cell 里面控件公用的间距 */ let BYStatusCellMargin: CGFloat = 8 /** float 头像大小 */ let BYStatusCellHeadImageWH: CGFloat = 35 class BYStatusCell: UITableViewCell { var toolBarTopCons: Constraint? var statusViewModel: BYStatusViewModel? { didSet { // 把数据源传给原创微博的view originalView.statusViewModel = statusViewModel statusToolBar.statusViewModel = statusViewModel if statusViewModel?.status?.retweeted_status != nil { /** 有转发的微博 */ retweetView.hidden = false retweetView.statusViewModel = statusViewModel // 干掉之前的约束 self.toolBarTopCons?.uninstall() self.statusToolBar.snp_updateConstraints(closure: { (make) -> Void in self.toolBarTopCons = make.top.equalTo(retweetView.snp_bottom).constraint }) } else { retweetView.hidden = true self.toolBarTopCons?.uninstall() self.statusToolBar.snp_updateConstraints(closure: { (make) -> Void in self.toolBarTopCons = make.top.equalTo(originalView.snp_bottom).constraint }) } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { selectionStyle = .None backgroundColor = UIColor(white: 240/250, alpha: 1) // 1. 添加控件 contentView.addSubview(originalView) contentView.addSubview(retweetView) contentView.addSubview(statusToolBar) // 2. 添加约束 originalView.snp_makeConstraints { make in make.leading.equalTo(contentView) make.top.equalTo(contentView).offset(BYStatusCellMargin) make.trailing.equalTo(contentView) } retweetView.snp_makeConstraints { make in make.leading.equalTo(originalView) make.top.equalTo(originalView.snp_bottom) make.trailing.equalTo(originalView) } statusToolBar.snp_makeConstraints { make in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.height.equalTo(36) self.toolBarTopCons = make.top.equalTo(retweetView.snp_bottom).constraint } contentView.snp_makeConstraints { make in make.leading.equalTo(self) make.top.equalTo(self) make.trailing.equalTo(self) make.bottom.equalTo(statusToolBar) } } // MARK: - 懒加载控件 private lazy var originalView: BYOriginalStatusView = BYOriginalStatusView() private lazy var retweetView: BYRetweetStatusView = BYRetweetStatusView() private lazy var statusToolBar: BYStatusToolBar = BYStatusToolBar() }
6c85344706b5486ac2083cacc7ed23f2
30.609524
94
0.593552
false
false
false
false
narner/AudioKit
refs/heads/master
Examples/macOS/RandomClips/RandomClips/ViewController.swift
mit
1
// // ViewController.swift // RandomClips // // Created by David O'Neill on 9/8/17. // Copyright © 2017 AudioKit. All rights reserved. // import Cocoa import AudioKit import AudioKitUI class ViewController: NSViewController { let drumPlayer = AKClipPlayer() let guitarPlayer = AKClipPlayer() let mixer = AKMixer() var drumLooper: AKAudioPlayer? let playButton = AKButton() let guitarDelay = AVAudioUnitDelay() let reverb = AKReverb() let highPass = AKHighPassFilter() override func viewDidLoad() { super.viewDidLoad() guard let drumURL = Bundle.main.url(forResource: "drumloop", withExtension: "wav"), let guitarURL = Bundle.main.url(forResource: "leadloop", withExtension: "wav"), let guitarLoopURL = Bundle.main.url(forResource: "guitarloop", withExtension: "wav"), let drumFile = try? AKAudioFile(forReading: drumURL), let guitarFile = try? AKAudioFile(forReading: guitarURL), let guitarLoopFile = try? AKAudioFile(forReading: guitarLoopURL), let drumLooper = try? AKAudioPlayer(file: drumFile, looping: true), let guitarLooper = try? AKAudioPlayer(file: guitarLoopFile, looping: true) else { print("missing resources!") return } [drumPlayer >>> highPass, guitarPlayer >>> guitarDelay >>> reverb, drumLooper, guitarLooper] >>> mixer guitarDelay.delayTime = guitarFile.duration / 8 guitarDelay.feedback = 1 guitarDelay.wetDryMix = 0.6 reverb.loadFactoryPreset(.cathedral) reverb.dryWetMix = 0.8 highPass.cutoffFrequency = 600 drumPlayer.volume = 1 guitarPlayer.volume = 0.6 guitarLooper.volume = 0.3 drumPlayer.volume = 0.6 AudioKit.output = mixer AudioKit.start() playButton.title = "Play" playButton.frame = view.bounds view.addSubview(playButton) let drumChops = 32 let guitarChops = 16 let loops = 100 func randomChopClips(audioFile: AKAudioFile, chops: Int, count: Int) -> [AKFileClip] { let duration = audioFile.duration / Double(chops) let randomOffset: () -> Double = { let btwn0andChop = arc4random_uniform(UInt32(chops)) return duration * Double(btwn0andChop) } var clips = [AKFileClip(audioFile: audioFile, time: 0, offset: randomOffset(), duration: duration)] for _ in 0..<count { guard let lastClip = clips.last else { fatalError() } clips.append(AKFileClip(audioFile: audioFile, time: lastClip.endTime, offset: randomOffset(), duration: duration)) } return clips } playButton.callback = { [drumPlayer, guitarPlayer] button in if drumPlayer.isPlaying { drumPlayer.stop() guitarPlayer.stop() guitarLooper.stop() drumLooper.stop() button.title = drumPlayer.isPlaying ? "Stop" : "Play" } else { drumPlayer.clips = randomChopClips(audioFile: drumFile, chops: drumChops, count: loops * drumChops) guitarPlayer.clips = randomChopClips(audioFile: guitarFile, chops: guitarChops, count: loops * guitarChops) drumPlayer.currentTime = 0 guitarPlayer.currentTime = 0 drumPlayer.prepare(withFrameCount: 44_100) guitarPlayer.prepare(withFrameCount: 44_100) drumLooper.schedule(from: 0, to: drumLooper.duration, avTime: nil) guitarLooper.schedule(from: 0, to: guitarLooper.duration, avTime: nil) let twoRendersTime = AKSettings.ioBufferDuration * 2 let futureTime = AVAudioTime.now() + twoRendersTime drumLooper.play(at: futureTime) guitarLooper.play(at: futureTime) let loopDur = drumFile.duration drumPlayer.play(at: futureTime + loopDur) guitarPlayer.play(at: futureTime + loopDur * 2) } button.title = drumPlayer.isPlaying ? "Stop" : "Play" } } }
fd674c99e172a538a5d0ea8dbb39c8f7
36.0625
97
0.544688
false
false
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
Pods/HTagView/HTagView/Classes/HTagView.swift
mit
1
// // HTagView.swift // Pods // // Created by Chang, Hao on 5/16/16. // // import UIKit /** HTagViewDelegate is a protocol to implement for responding to user interactions to the HTagView. */ @objc public protocol HTagViewDelegate: class { /** Called when user did cancel tag at index */ @objc optional func tagView(_ tagView: HTagView, didCancelTagAtIndex index: Int) @objc optional func tagView(_ tagView: HTagView, tagSelectionDidChange selectedIndices: [Int]) } /** HTagViewDataSource is a protocol to implement for data source of the HTagView. */ public protocol HTagViewDataSource: class { func numberOfTags(_ tagView: HTagView) -> Int func tagView(_ tagView: HTagView, titleOfTagAtIndex index: Int) -> String func tagView(_ tagView: HTagView, tagTypeAtIndex index: Int) -> HTagType func tagView(_ tagView: HTagView, tagWidthAtIndex index: Int) -> CGFloat } public extension HTagViewDataSource { func tagView(_ tagView: HTagView, tagWidthAtIndex index: Int) -> CGFloat { return .HTagAutoWidth } } /** HTag comes with two types, `.cancel` and `.select`. */ public enum HTagType{ case cancel, select } /** HTagView is customized tag view sublassing UIView where tag could be either with cancel button or seletable. */ @IBDesignable open class HTagView: UIView { // MARK: - DataSource /** HTagViewDataSource */ open weak var dataSource : HTagViewDataSource?{ didSet{ reloadData() } } // MARK: - Delegate /** HTagViewDelegate */ open weak var delegate : HTagViewDelegate? // MARK: - HTagView Configuration /** HTagView multiselect */ @IBInspectable open var multiselect : Bool = true /** HTagView margin */ @IBInspectable open var marg : CGFloat = 20 /** Distance between tags in the same line */ @IBInspectable open var btwTags : CGFloat = 8 /** Distance between lines */ @IBInspectable open var btwLines : CGFloat = 8 // MARK: - HTag Configuration /** Main background color of tags */ @IBInspectable open var tagMainBackColor : UIColor = UIColor(red: 100/255, green: 200/255, blue: 205/255, alpha: 1) { didSet { tags.forEach { $0.tagMainBackColor = tagMainBackColor } } } /** Main text color of tags */ @IBInspectable open var tagMainTextColor : UIColor = UIColor.white { didSet { tags.forEach { $0.tagMainTextColor = tagMainTextColor } } } /** Secondary background color of tags */ @IBInspectable open var tagSecondBackColor : UIColor = UIColor.lightGray { didSet { tags.forEach { $0.tagSecondBackColor = tagSecondBackColor } } } /** Secondary text color of tags */ @IBInspectable open var tagSecondTextColor : UIColor = UIColor.darkText { didSet { tags.forEach { $0.tagSecondTextColor = tagSecondTextColor } } } /** The border width to height ratio of HTags. */ @IBInspectable open var tagBorderWidth :CGFloat = CGFloat(0){ didSet{ tags.forEach { $0.tagBorderWidth = tagBorderWidth } for tag in tags{ tag.layer.borderWidth = tagBorderWidth } layoutIfNeeded() } } /** The border color to height ratio of HTags. */ @IBInspectable open var tagBorderColor :CGColor? = nil{ didSet{ tags.forEach { $0.tagBorderColor = tagBorderColor } for tag in tags{ tag.layer.borderColor = tagBorderColor } layoutIfNeeded() } } /** Maximum Width of Tag */ open var tagMaximumWidth: CGFloat? = .HTagAutoMaximumWidth { didSet { tags.forEach { $0.tagMaximumWidth = tagMaximumWidth } layoutIfNeeded() } } /** The corner radius to height ratio of HTags. */ @IBInspectable open var tagCornerRadiusToHeightRatio :CGFloat = CGFloat(0.2){ didSet{ tags.forEach { $0.tagCornerRadiusToHeightRatio = tagCornerRadiusToHeightRatio } for tag in tags{ tag.layer.cornerRadius = tag.frame.height * tagCornerRadiusToHeightRatio } layoutIfNeeded() } } /** The content EdgeInsets of HTags, which would automatically adjust the position in `.cancel` type. On the other word, usages are the same in both types. */ @IBInspectable open var tagContentEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) { didSet{ for tag in tags{ tag.tagContentEdgeInsets = tagContentEdgeInsets } } } /** The distance between cancel icon and text */ @IBInspectable open var tagCancelIconRightMargin: CGFloat = 4 { didSet{ for tag in tags{ tag.tagCancelIconRightMargin = tagCancelIconRightMargin } } } /** The Font of HTags. */ @IBInspectable open var tagFont : UIFont = UIFont.systemFont(ofSize: 17) { didSet{ for tag in tags { tag.tagFont = tagFont } layoutIfNeeded() invalidateIntrinsicContentSize() } } /** Indices of selected tags. */ open var selectedIndices: [Int]{ get{ var selectedIndexes = [Int]() for (index, tag) in tags.enumerated(){ if tag.tagType == .select && tag.isSelected{ selectedIndexes.append(index) } } return selectedIndexes } } var tags: [HTag] = [] // MARK: - init override public init(frame: CGRect){ super.init(frame: frame) configure() reloadData(false) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() reloadData(false) } func configure(){ } // MARK: - reload open func reloadData(_ preserveSelectionState: Bool = true){ guard let dataSource = dataSource else { return } let selection = selectedIndices for tag in tags { tag.removeFromSuperview() } tags = [] for index in 0 ..< dataSource.numberOfTags(self) { let tag = HTag() tag.delegate = self tag.tagType = dataSource.tagView(self, tagTypeAtIndex: index) if tag.tagType == .select { tag.setSelected(preserveSelectionState ? selection.contains(index) : false) } tag.tagContentEdgeInsets = tagContentEdgeInsets tag.tagFont = tagFont tag.tagMainBackColor = tagMainBackColor tag.tagSecondBackColor = tagSecondBackColor tag.tagMainTextColor = tagMainTextColor tag.tagSecondTextColor = tagSecondTextColor tag.tagBorderColor = tagBorderColor tag.tagBorderWidth = tagBorderWidth tag.tagCornerRadiusToHeightRatio = tagCornerRadiusToHeightRatio tag.tagCancelIconRightMargin = tagCancelIconRightMargin tag.tagMaximumWidth = tagMaximumWidth tag.tagTitle = dataSource.tagView(self, titleOfTagAtIndex: index) addSubview(tag) tags.append(tag) } layoutSubviews() invalidateIntrinsicContentSize() } // MARK: - Subclassing UIView override open func layoutSubviews() { guard let dataSource = dataSource else { return } if dataSource.numberOfTags(self) == 0 { self.frame.size = CGSize(width: self.frame.width, height: 0) }else{ var x = marg var y = marg for index in 0..<tags.count{ if dataSource.tagView(self, tagWidthAtIndex: index) != .HTagAutoWidth { tags[index].tagSpecifiedWidth = dataSource.tagView(self, tagWidthAtIndex: index) } else { tags[index].tagSpecifiedWidth = nil } if tagMaximumWidth == .HTagAutoMaximumWidth { tags[index].tagMaximumWidth = frame.width - 2 * marg } if tags[index].frame.width + x > frame.width - marg{ y += tags[index].frame.height + btwLines x = marg } tags[index].frame.origin = CGPoint(x: x, y: y) x += tags[index].frame.width + btwTags } self.frame.size = CGSize(width: self.frame.width, height: y + (tags.last?.frame.height ?? 0) + marg ) } } override open var intrinsicContentSize : CGSize { if tags.count == 0{ return CGSize(width: UIViewNoIntrinsicMetric, height: 0) }else{ let height = (tags.last?.frame.origin.y ?? 0) + (tags.last?.frame.height ?? 0) + marg return CGSize(width: UIViewNoIntrinsicMetric, height: height ) } } // MARK: - Manipulate Tags /** Select on tag with titles in `.select` type HTagView. The delegate method `tagView(_:tagSelectionDidChange:)` will be called. */ open func selectTagAtIndex(_ index: Int){ for (i, tag) in tags.enumerated() { guard let type = dataSource?.tagView(self, tagTypeAtIndex: i), type == .select else { continue } if i == index { tag.setSelected(true) } else if !multiselect { tag.setSelected(false) } } } /** Deselect on tag with titles in `.select` type HTagView. The delegate method `tagView(_:tagSelectionDidChange:)` will be called. */ open func deselectTagAtIndex(_ index: Int){ guard let type = dataSource?.tagView(self, tagTypeAtIndex: index) , type == .select else { return } tags[index].setSelected(false) } } extension HTagView: HTagDelegate { func tagClicked(_ sender: HTag) { guard let index = tags.index(of: sender) else{ return } if dataSource?.tagView(self, tagTypeAtIndex: index) == .select{ if sender.isSelected { deselectTagAtIndex(index) }else{ selectTagAtIndex(index) } } delegate?.tagView?(self, tagSelectionDidChange: selectedIndices) } func tagCancelled(_ sender: HTag) { guard let index = tags.index(of: sender) else{ return } delegate?.tagView?(self, didCancelTagAtIndex: index) } }
e4567d7f51e9ba0b12b5d002ef4821fc
27.866667
132
0.558181
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
refs/heads/master
RedBus/RedBus/Common/ToastManager.swift
apache-2.0
1
// // ToastManager.swift // RedBus // // Created by Anirudh Das on 8/24/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import Foundation import UIKit import ObjectiveC public enum ToastPosition { case top case center case bottom } /** Toast is a Swift extension that adds toast notifications to the `UIView` object class. It is intended to be simple, lightweight, and easy to use. Most toast notifications can be triggered with a single line of code. The `makeToast` methods create a new view and then display it as toast. The `showToast` methods display any view as toast. */ public extension UIView { /** Keys used for associated objects. */ fileprivate struct ToastKeys { static var Timer = "CSToastTimerKey" static var Duration = "CSToastDurationKey" static var Position = "CSToastPositionKey" static var Completion = "CSToastCompletionKey" static var ActiveToast = "CSToastActiveToastKey" static var ActivityView = "CSToastActivityViewKey" static var Queue = "CSToastQueueKey" } /** Swift closures can't be directly associated with objects via the Objective-C runtime, so the (ugly) solution is to wrap them in a class that can be used with associated objects. */ fileprivate class ToastCompletionWrapper { var completion: ((Bool) -> Void)? init(_ completion: ((Bool) -> Void)?) { self.completion = completion } } fileprivate enum ToastError: Error { case insufficientData } fileprivate var queue: NSMutableArray { get { if let queue = objc_getAssociatedObject(self, &ToastKeys.Queue) as? NSMutableArray { return queue } else { let queue = NSMutableArray() objc_setAssociatedObject(self, &ToastKeys.Queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return queue } } } // MARK: - Make Toast Methods /** Creates and presents a new toast view with a message and displays it with the default duration and position. Styled using the shared style. @param message The message to be displayed */ public func makeToast(_ message: String) { self.makeToast(message, duration: ToastManager.shared.duration, position: ToastManager.shared.position) } /** Creates and presents a new toast view with a message. Duration and position can be set explicitly. Styled using the shared style. @param message The message to be displayed @param duration The toast duration @param position The toast's position */ public func makeToast(_ message: String, duration: TimeInterval, position: ToastPosition) { self.makeToast(message, duration: duration, position: position, style: nil) } /** Creates and presents a new toast view with a message. Duration and position can be set explicitly. Styled using the shared style. @param message The message to be displayed @param duration The toast duration @param position The toast's center point */ public func makeToast(_ message: String, duration: TimeInterval, position: CGPoint) { self.makeToast(message, duration: duration, position: position, style: nil) } /** Creates and presents a new toast view with a message. Duration, position, and style can be set explicitly. @param message The message to be displayed @param duration The toast duration @param position The toast's position @param style The style. The shared style will be used when nil */ public func makeToast(_ message: String, duration: TimeInterval, position: ToastPosition, style: ToastStyle?) { self.makeToast(message, duration: duration, position: position, title: nil, image: nil, style: style, completion: nil) } /** Creates and presents a new toast view with a message. Duration, position, and style can be set explicitly. @param message The message to be displayed @param duration The toast duration @param position The toast's center point @param style The style. The shared style will be used when nil */ public func makeToast(_ message: String, duration: TimeInterval, position: CGPoint, style: ToastStyle?) { self.makeToast(message, duration: duration, position: position, title: nil, image: nil, style: style, completion: nil) } /** Creates and presents a new toast view with a message, title, and image. Duration, position, and style can be set explicitly. The completion closure executes when the toast completes presentation. `didTap` will be `true` if the toast view was dismissed from a tap. @param message The message to be displayed @param duration The toast duration @param position The toast's position @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func makeToast(_ message: String?, duration: TimeInterval, position: ToastPosition, title: String?, image: UIImage?, style: ToastStyle?, completion: ((_ didTap: Bool) -> Void)?) { var toastStyle = ToastManager.shared.style if let style = style { toastStyle = style } do { let toast = try self.toastViewForMessage(message, title: title, image: image, style: toastStyle) self.showToast(toast, duration: duration, position: position, completion: completion) } catch ToastError.insufficientData { } catch {} } /** Creates and presents a new toast view with a message, title, and image. Duration, position, and style can be set explicitly. The completion closure executes when the toast completes presentation. `didTap` will be `true` if the toast view was dismissed from a tap. @param message The message to be displayed @param duration The toast duration @param position The toast's center point @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func makeToast(_ message: String?, duration: TimeInterval, position: CGPoint, title: String?, image: UIImage?, style: ToastStyle?, completion: ((_ didTap: Bool) -> Void)?) { var toastStyle = ToastManager.shared.style if let style = style { toastStyle = style } do { let toast = try self.toastViewForMessage(message, title: title, image: image, style: toastStyle) self.showToast(toast, duration: duration, position: position, completion: completion) } catch ToastError.insufficientData { } catch {} } // MARK: - Show Toast Methods /** Displays any view as toast using the default duration and position. @param toast The view to be displayed as toast */ public func showToast(_ toast: UIView) { self.showToast(toast, duration: ToastManager.shared.duration, position: ToastManager.shared.position, completion: nil) } /** Displays any view as toast at a provided position and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param position The toast's position @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func showToast(_ toast: UIView, duration: TimeInterval, position: ToastPosition, completion: ((_ didTap: Bool) -> Void)?) { let point = self.centerPointForPosition(position, toast: toast) self.showToast(toast, duration: duration, position: point, completion: completion) } /** Displays any view as toast at a provided position and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param position The toast's center point @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func showToast(_ toast: UIView, duration: TimeInterval, position: CGPoint, completion: ((_ didTap: Bool) -> Void)?) { objc_setAssociatedObject(toast, &ToastKeys.Completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let _ = objc_getAssociatedObject(self, &ToastKeys.ActiveToast) as? UIView, ToastManager.shared.queueEnabled { objc_setAssociatedObject(toast, &ToastKeys.Duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(toast, &ToastKeys.Position, NSValue(cgPoint: position), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.queue.add(toast) } else { self.showToast(toast, duration: duration, position: position) } } // MARK: - Activity Methods /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param position The toast's position */ public func makeToastActivity(_ position: ToastPosition) { // sanity if let _ = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView { return } let toast = self.createToastActivityView() let point = self.centerPointForPosition(position, toast: toast) self.makeToastActivity(toast, position: point) } /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param position The toast's center point */ public func makeToastActivity(_ position: CGPoint) { // sanity if let _ = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView { return } let toast = self.createToastActivityView() self.makeToastActivity(toast, position: position) } /** Dismisses the active toast activity indicator view. */ public func hideToastActivity() { if let toast = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView { UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { () -> Void in toast.alpha = 0.0 }, completion: { (finished: Bool) -> Void in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.ActivityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }) } } // MARK: - Private Activity Methods fileprivate func makeToastActivity(_ toast: UIView, position: CGPoint) { toast.alpha = 0.0 toast.center = position objc_setAssociatedObject(self, &ToastKeys.ActivityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in toast.alpha = 1.0 }, completion: nil) } fileprivate func createToastActivityView() -> UIView { let style = ToastManager.shared.style let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height)) activityView.backgroundColor = style.backgroundColor activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] activityView.layer.cornerRadius = style.cornerRadius if style.displayShadow { activityView.layer.shadowColor = style.shadowColor.cgColor activityView.layer.shadowOpacity = style.shadowOpacity activityView.layer.shadowRadius = style.shadowRadius activityView.layer.shadowOffset = style.shadowOffset } let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0) activityView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() return activityView } // MARK: - Private Show/Hide Methods fileprivate func showToast(_ toast: UIView, duration: TimeInterval, position: CGPoint) { toast.center = position toast.alpha = 0.0 if ToastManager.shared.tapToDismissEnabled { let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:))) toast.addGestureRecognizer(recognizer) toast.isUserInteractionEnabled = true toast.isExclusiveTouch = true } objc_setAssociatedObject(self, &ToastKeys.ActiveToast, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { () -> Void in toast.alpha = 1.0 }) { (finished) -> Void in let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false) RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) objc_setAssociatedObject(toast, &ToastKeys.Timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate func hideToast(_ toast: UIView) { self.hideToast(toast, fromTap: false) } fileprivate func hideToast(_ toast: UIView, fromTap: Bool) { UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { () -> Void in toast.alpha = 0.0 }) { (didFinish: Bool) -> Void in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.ActiveToast, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.Completion) as? ToastCompletionWrapper, let completion = wrapper.completion { completion(fromTap) } if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.Duration) as? NSNumber, let position = objc_getAssociatedObject(nextToast, &ToastKeys.Position) as? NSValue { self.queue.removeObject(at: 0) self.showToast(nextToast, duration: duration.doubleValue, position: position.cgPointValue) } } } // MARK: - Events @objc func handleToastTapped(_ recognizer: UITapGestureRecognizer) { if let toast = recognizer.view, let timer = objc_getAssociatedObject(toast, &ToastKeys.Timer) as? Timer { timer.invalidate() self.hideToast(toast, fromTap: true) } } @objc func toastTimerDidFinish(_ timer: Timer) { if let toast = timer.userInfo as? UIView { self.hideToast(toast) } } // MARK: - Toast Construction /** Creates a new toast view with any combination of message, title, and image. The look and feel is configured via the style. Unlike the `makeToast` methods, this method does not present the toast view automatically. One of the `showToast` methods must be used to present the resulting view. @warning if message, title, and image are all nil, this method will throw `ToastError.InsufficientData` @param message The message to be displayed @param title The title @param image The image @param style The style. The shared style will be used when nil @throws `ToastError.InsufficientData` when message, title, and image are all nil @return The newly created toast view */ public func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView { // sanity if message == nil && title == nil && image == nil { throw ToastError.insufficientData } var messageLabel: UILabel? var titleLabel: UILabel? var imageView: UIImageView? let wrapperView = UIView() wrapperView.backgroundColor = style.backgroundColor wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] wrapperView.layer.cornerRadius = style.cornerRadius if style.displayShadow { wrapperView.layer.shadowColor = UIColor.black.cgColor wrapperView.layer.shadowOpacity = style.shadowOpacity wrapperView.layer.shadowRadius = style.shadowRadius wrapperView.layer.shadowOffset = style.shadowOffset } if let image = image { imageView = UIImageView(image: image) imageView?.contentMode = .scaleAspectFit imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height) } var imageRect = CGRect.zero if let imageView = imageView { imageRect.origin.x = style.horizontalPadding imageRect.origin.y = style.verticalPadding imageRect.size.width = imageView.bounds.size.width imageRect.size.height = imageView.bounds.size.height } if let title = title { titleLabel = UILabel() titleLabel?.numberOfLines = style.titleNumberOfLines titleLabel?.font = style.titleFont titleLabel?.textAlignment = style.titleAlignment titleLabel?.lineBreakMode = .byTruncatingTail titleLabel?.textColor = style.titleColor titleLabel?.backgroundColor = UIColor.clear titleLabel?.text = title let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) let titleSize = titleLabel?.sizeThatFits(maxTitleSize) if let titleSize = titleSize { titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height) } } if let message = message { messageLabel = UILabel() messageLabel?.text = message messageLabel?.numberOfLines = style.messageNumberOfLines messageLabel?.font = style.messageFont messageLabel?.textAlignment = style.messageAlignment messageLabel?.lineBreakMode = .byTruncatingTail messageLabel?.textColor = style.messageColor messageLabel?.backgroundColor = UIColor.clear let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) let messageSize = messageLabel?.sizeThatFits(maxMessageSize) if let messageSize = messageSize { let actualWidth = min(messageSize.width, maxMessageSize.width) let actualHeight = min(messageSize.height, maxMessageSize.height) messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight) } } var titleRect = CGRect.zero if let titleLabel = titleLabel { titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding titleRect.origin.y = style.verticalPadding titleRect.size.width = titleLabel.bounds.size.width titleRect.size.height = titleLabel.bounds.size.height } var messageRect = CGRect.zero if let messageLabel = messageLabel { messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding messageRect.size.width = messageLabel.bounds.size.width messageRect.size.height = messageLabel.bounds.size.height } let longerWidth = max(titleRect.size.width, messageRect.size.width) let longerX = max(titleRect.origin.x, messageRect.origin.x) let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding)) let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0))) wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight) if let titleLabel = titleLabel { titleLabel.frame = titleRect wrapperView.addSubview(titleLabel) } if let messageLabel = messageLabel { messageLabel.frame = messageRect wrapperView.addSubview(messageLabel) } if let imageView = imageView { wrapperView.addSubview(imageView) } return wrapperView } // MARK: - Helpers fileprivate func centerPointForPosition(_ position: ToastPosition, toast: UIView) -> CGPoint { let padding: CGFloat = ToastManager.shared.style.verticalPadding switch(position) { case .top: return CGPoint(x: self.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + padding) case .center: return CGPoint(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0) case .bottom: return CGPoint(x: self.bounds.size.width / 2.0, y: (self.bounds.size.height - (toast.frame.size.height / 2.0)) - padding - 40) } } } // MARK: - Toast Style /** `ToastStyle` instances define the look and feel for toast views created via the `makeToast` methods as well for toast views created directly with `toastViewForMessage(message:title:image:style:)`. @warning `ToastStyle` offers relatively simple styling options for the default toast view. If you require a toast view with more complex UI, it probably makes more sense to create your own custom UIView subclass and present it with the `showToast` methods. */ public struct ToastStyle { public init() {} /** The background color. Default is `UIColor.blackColor()` at 80% opacity. */ public var backgroundColor = UIColor.black.withAlphaComponent(0.8) /** The title color. Default is `UIColor.whiteColor()`. */ public var titleColor = UIColor.white /** The message color. Default is `UIColor.whiteColor()`. */ public var messageColor = UIColor.white /** A percentage value from 0.0 to 1.0, representing the maximum width of the toast view relative to it's superview. Default is 0.8 (80% of the superview's width). */ public var maxWidthPercentage: CGFloat = 0.8 { didSet { maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0) } } /** A percentage value from 0.0 to 1.0, representing the maximum height of the toast view relative to it's superview. Default is 0.8 (80% of the superview's height). */ public var maxHeightPercentage: CGFloat = 0.8 { didSet { maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0) } } /** The spacing from the horizontal edge of the toast view to the content. When an image is present, this is also used as the padding between the image and the text. Default is 10.0. */ public var horizontalPadding: CGFloat = 10.0 /** The spacing from the vertical edge of the toast view to the content. When a title is present, this is also used as the padding between the title and the message. Default is 10.0. */ public var verticalPadding: CGFloat = 10.0 /** The corner radius. Default is 10.0. */ public var cornerRadius: CGFloat = 10.0 /** The title font. Default is `UIFont.boldSystemFontOfSize(16.0)`. */ public var titleFont = UIFont.boldSystemFont(ofSize: 16.0) /** The message font. Default is `UIFont.systemFontOfSize(16.0)`. */ public var messageFont = UIFont.systemFont(ofSize: 16.0) /** The title text alignment. Default is `NSTextAlignment.Left`. */ public var titleAlignment = NSTextAlignment.left /** The message text alignment. Default is `NSTextAlignment.Left`. */ public var messageAlignment = NSTextAlignment.left /** The maximum number of lines for the title. The default is 0 (no limit). */ public var titleNumberOfLines = 0 /** The maximum number of lines for the message. The default is 0 (no limit). */ public var messageNumberOfLines = 0 /** Enable or disable a shadow on the toast view. Default is `false`. */ public var displayShadow = false /** The shadow color. Default is `UIColor.blackColor()`. */ public var shadowColor = UIColor.black /** A value from 0.0 to 1.0, representing the opacity of the shadow. Default is 0.8 (80% opacity). */ public var shadowOpacity: Float = 0.8 { didSet { shadowOpacity = max(min(shadowOpacity, 1.0), 0.0) } } /** The shadow radius. Default is 6.0. */ public var shadowRadius: CGFloat = 6.0 /** The shadow offset. The default is 4 x 4. */ public var shadowOffset = CGSize(width: 4.0, height: 4.0) /** The image size. The default is 80 x 80. */ public var imageSize = CGSize(width: 80.0, height: 80.0) /** The size of the toast activity view when `makeToastActivity(position:)` is called. Default is 100 x 100. */ public var activitySize = CGSize(width: 100.0, height: 100.0) /** The fade in/out animation duration. Default is 0.2. */ public var fadeDuration: TimeInterval = 0.2 } // MARK: - Toast Manager /** `ToastManager` provides general configuration options for all toast notifications. Backed by a singleton instance. */ open class ToastManager { /** The `ToastManager` singleton instance. */ open static let shared = ToastManager() /** The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called with with a nil style. */ open var style = ToastStyle() /** Enables or disables tap to dismiss on toast views. Default is `true`. */ open var tapToDismissEnabled = true /** Enables or disables queueing behavior for toast views. When `true`, toast views will appear one after the other. When `false`, multiple toast views will appear at the same time (potentially overlapping depending on their positions). This has no effect on the toast activity view, which operates independently of normal toast views. Default is `true`. */ open var queueEnabled = true /** The default duration. Used for the `makeToast` and `showToast` methods that don't require an explicit duration. Default is 3.0. */ open var duration: TimeInterval = 3.0 /** Sets the default position. Used for the `makeToast` and `showToast` methods that don't require an explicit position. Default is `ToastPosition.Bottom`. */ open var position = ToastPosition.bottom }
bc48657638966cdbe305d111179afde2
39.1
237
0.651571
false
false
false
false
ArthurKK/SweetAlert-iOS
refs/heads/master
SweetAlert/ViewController.swift
mit
10
// // ViewController.swift // SweetAlert // // Created by Codester on 11/3/14. // Copyright (c) 2014 Codester. All rights reserved. // import UIKit class ViewController: UIViewController { var alert = SweetAlert() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor(red: 242.0/255.0, green: 244.0/255.0, blue: 246.0/255.0, alpha: 1.0) } override func viewDidAppear(animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func aBasicMessageAlert(sender: AnyObject) { SweetAlert().showAlert("Here's a message!") } @IBAction func subtitleAlert(sender: AnyObject) { SweetAlert().showAlert("Here's a message!", subTitle: "It's pretty, isn't it?", style: AlertStyle.None) } @IBAction func sucessAlert(sender: AnyObject) { SweetAlert().showAlert("Good job!", subTitle: "You clicked the button!", style: AlertStyle.Success) } @IBAction func warningAlert(sender: AnyObject) { SweetAlert().showAlert("Are you sure?", subTitle: "You file will permanently delete!", style: AlertStyle.Warning, buttonTitle:"Cancel", buttonColor:UIColor.colorFromRGB(0xD0D0D0) , otherButtonTitle: "Yes, delete it!", otherButtonColor: UIColor.colorFromRGB(0xDD6B55)) { (isOtherButton) -> Void in if isOtherButton == true { print("Cancel Button Pressed", appendNewline: false) } else { SweetAlert().showAlert("Deleted!", subTitle: "Your imaginary file has been deleted!", style: AlertStyle.Success) } } } @IBAction func cancelAndConfirm(sender: AnyObject) { SweetAlert().showAlert("Are you sure?", subTitle: "You file will permanently delete!", style: AlertStyle.Warning, buttonTitle:"No, cancel plx!", buttonColor:UIColor.colorFromRGB(0xD0D0D0) , otherButtonTitle: "Yes, delete it!", otherButtonColor: UIColor.colorFromRGB(0xDD6B55)) { (isOtherButton) -> Void in if isOtherButton == true { SweetAlert().showAlert("Cancelled!", subTitle: "Your imaginary file is safe", style: AlertStyle.Error) } else { SweetAlert().showAlert("Deleted!", subTitle: "Your imaginary file has been deleted!", style: AlertStyle.Success) } } } @IBAction func customIconAlert(sender: AnyObject) { SweetAlert().showAlert("Sweet!", subTitle: "Here's a custom image.", style: AlertStyle.CustomImag(imageFile: "thumb.jpg")) } }
97b1dda2c417fa934c0cffee8f704f87
36.44
314
0.637464
false
false
false
false
BobElDevil/ScriptWorker
refs/heads/master
ScriptWorker/ScriptWorker+Actions.swift
mit
1
// // ScriptWorker+Actions.swift // ScriptWorker // // Created by Steve Marquis on 8/20/16. // Copyright © 2016 Stephen Marquis. All rights reserved. // import Foundation /** All of the actions come in two variants. The standard method exits the program on any encountered errors, printing the received error. Actions suffixed with '_safe' throw any encountered errors, in case you want to handle the error without program failure. */ extension ScriptWorker { /// Remove the specified item. If item is nil, remove the path currently represented by the receiver. item defaults to nil. public func remove(item: String? = nil) { exitOnError { try remove_safe(item: item) } } public func remove_safe(item: String? = nil) throws { log(action: "Removing \(path(item: item))") try fileManager.removeItem(at: url(item: item)) } public static func remove(path: String) { applyScriptWorker(path: path) { $0.remove(item: $1) } } public static func remove_safe(path: String) throws { try applyScriptWorker(path: path) { try $0.remove_safe(item: $1) } } /// Create a directory. If item is nil, creates directory at the path currently represented by the reciever. item defaults to nil public func makeDirectory(at item: String? = nil, withIntermediates intermediates: Bool = false) { exitOnError { try makeDirectory_safe(at: item, withIntermediates: intermediates) } } public func makeDirectory_safe(at item: String? = nil, withIntermediates intermediates: Bool = false) throws { log(action: "Creating directory \(path(item: item))") try fileManager.createDirectory(at: url(item: item), withIntermediateDirectories: intermediates, attributes: nil) } public static func makeDirectory(path: String, withIntermediates intermediates: Bool = false) { applyScriptWorker(path: path) { $0.makeDirectory(at: $1, withIntermediates: intermediates) } } public static func makeDirectory_safe(path: String, withIntermediates intermediates: Bool = false) throws { try applyScriptWorker(path: path) { try $0.makeDirectory_safe(at: $1, withIntermediates: intermediates) } } /// Copy item at path to the location defined by 'toPath'. toPath can be absolute or relative /// If item is nil, copies the directory represented by the receiver. /// If 'toPath' alreday exists and is a directory, it will copy the item into that directory with the original name. /// Otherwise it copies to the destination with the destination name public func copy(item: String? = nil, to toPath: String) { exitOnError { try copy_safe(item: item, to: toPath) } } public func copy_safe(item: String? = nil, to toPath: String) throws { let destinationURL = destinationURLFor(item: item, path: toPath) log(action: "Copying \(path(item: item)) to \(destinationURL.path)") try fileManager.copyItem(at: url(item: item), to: destinationURL) } public static func copy(path: String, to toPath: String) { applyScriptWorker(path: path) { $0.copy(item: $1, to: toPath) } } public static func copy_safe(path: String, to toPath: String) throws { try applyScriptWorker(path: path) { try $0.copy_safe(item: $1, to: toPath) } } /// Move the item at path to the location defined by 'toPath'. toPath can be absolute or relative /// If item is nil, moves the directory represented by the receiver. /// If 'toPath' already exists and is a directory, it will move the item into that directory with the original name. /// Otherwise it moves to the destination with the destination name public func move(item: String? = nil, to toPath: String) { exitOnError { try move_safe(item: item, to: toPath) } } public func move_safe(item: String? = nil, to toPath: String) throws { let destinationURL = destinationURLFor(item: item, path: toPath) log(action: "Moving \(path(item: item)) to \(destinationURL.path)") try fileManager.moveItem(at: url(item: item), to: destinationURL) } public static func move(path: String, to toPath: String) { applyScriptWorker(path: path) { $0.move(item: $1, to: toPath) } } public static func move_safe(path: String, to toPath: String) throws { try applyScriptWorker(path: path) { try $0.move_safe(item: $1, to: toPath) } } /// Create a symlink at path to the location defined by 'toPath'. toPath can be absolute or relative public func symlink(item: String, to toPath: String) { exitOnError { try symlink_safe(item: item, to: toPath) } } public func symlink_safe(item: String, to toPath: String) throws { log(action: "Creating symlink from \(path(item: item)) to \(toPath)") if (toPath as NSString).isAbsolutePath { try fileManager.createSymbolicLink(at: url(item: item), withDestinationURL: URL(fileURLWithPath: toPath)) } else { // Use path based API to make sure it ends up relative try fileManager.createSymbolicLink(atPath: path(item: item), withDestinationPath: toPath) } } public static func symlink(path: String, to toPath: String) { applyScriptWorker(path: path) { $0.symlink(item: $1, to: toPath) } } public static func symlink_safe(path: String, to toPath: String) throws { try applyScriptWorker(path: path) { try $0.symlink_safe(item: $1, to: toPath) } } private func destinationURLFor(item: String?, path: String) -> URL { var destinationURL: URL if (path as NSString).isAbsolutePath { destinationURL = URL(fileURLWithPath: path) } else { destinationURL = url().appendingPathComponent(path) } let (exists, isDir) = fileStatus(for: destinationURL.path) if exists && isDir { destinationURL.appendPathComponent(item ?? url().lastPathComponent) } return destinationURL } }
1d37a50a135fb102982aa977ec2dcb46
41.923077
135
0.662594
false
false
false
false
urbn/URBNValidator
refs/heads/master
URBNValidator.playground/Pages/Length Rules.xcplaygroundpage/Contents.swift
mit
1
//: [Required Rule](@previous) [Overview](@overview) /*: # Length Requirements Here we've got a built in rule to handle length requirements. This will verify lengths of anything that conforms to our Lengthable protocol. Which by default handles strings, arrays and dictionaries. By default length rules are non-inclusive. Meaning the greater than matches '>' and less than '<'. If you'd like the rule to be inclusive '>=' or '<=', then you can include the optional `inclusive` param on init. Optionally you can set the .isInclusive property */ import URBNValidator var emptyVal: String? = nil /*: ### Max Length Our first length rule is a maxLength. This says that the value we're validating should nto be greater than 5 */ let maxLengthRule = URBNMaxLengthRule(maxLength: 5) // These are all valid maxLengthRule.validateValue([]) maxLengthRule.validateValue("") maxLengthRule.validateValue(["": 1]) maxLengthRule.validateValue("12345") // With inclusive maxLengthRule.isInclusive = true maxLengthRule.validateValue("12345") /*: For the anything that is `URBNRequirement` we specify an isRequired flag. The purpose of `isRequired` is to let the rule know whether or not it accepts nil. If required, then nil will not be valid */ maxLengthRule.isRequired = true maxLengthRule.validateValue(emptyVal) // Not Valid because isRequired=true maxLengthRule.isRequired = false maxLengthRule.validateValue(emptyVal) // Valid // These are invalid maxLengthRule.validateValue([1,2,3,4,5,6]) maxLengthRule.validateValue("123456") /*: ### Min Length Min Length is the same thing except at the bottom end. The given value should be > 5 */ let minLengthRule = URBNMinLengthRule(minLength: 2, inclusive: true) // These are valid minLengthRule.validateValue("12") minLengthRule.validateValue("1234") minLengthRule.validateValue([1,2]) minLengthRule.validateValue([1:1,2:2]) // These are invalid minLengthRule.validateValue("1") minLengthRule.validateValue([]) minLengthRule.validateValue(["1":1]) // Requirements minLengthRule.isRequired = true minLengthRule.validateValue(emptyVal) // Not Valid because isRequired=true minLengthRule.isRequired = false minLengthRule.validateValue(emptyVal) // Valid //: [Block Rules](@next)
6a592e226fe2b0fcce0b2214a791b122
26.925926
77
0.759505
false
false
false
false
hungdv136/rx.redux
refs/heads/master
Redux/Store.swift
mit
1
// // Store.swift // Redux // // Created by Chu Cuoi on 10/5/16. // Copyright © 2016 chucuoi.net. All rights reserved. // import Foundation import RxSwift import RxCocoa public protocol StoreType { associatedtype State: StateType var state: Driver<State> { get } func getState() -> State func dispatch(_ action: Action) -> Any } public class Store<T: StateType>: StoreType { public init(state: T, reducer: AnyReducer, middlewares: [Middleware] = []) { stateVar = Variable(state) self.reducer = reducer let dispatch: DispatchFunction = { [unowned self] in self.dispatch($0) } let getState: GetState = { [unowned self] in self.getState() } dispatchFunction = middlewares.reversed().reduce({ [unowned self] action in self.dispatchCore(action: action) }) { composed, middleware in return middleware.process(getState: getState, dispatch: dispatch)(composed) } } public func getState() -> T { return stateVar.value } @discardableResult public func dispatch(_ action: Action) -> Any { return dispatchFunction(action) } private func dispatchCore(action: Action) -> Any { guard !isDispatching else { fatalError("Redux:IllegalDispatchFromReducer - Reducers may not dispatch actions.") } isDispatching = true defer { isDispatching = false } stateVar.value = reducer._handleAction(state: stateVar.value, action: action) as! T return action } //MARK: Properties private let stateVar: Variable<T> public var state: Driver<T> { return stateVar.asDriver() } private let reducer: AnyReducer private var dispatchFunction: ((Action) -> Any)! private var isDispatching = false }
36b7aa31b551411eab27201e3f2d92ed
25.162162
95
0.604339
false
false
false
false
DaRkD0G/EasyHelper
refs/heads/master
EasyHelper/SequenceTypeExtensions.swift
mit
1
// // SequenceTypeExtensions.swift // EasyHelper // // Created by DaRk-_-D0G on 02/10/2015. // Copyright © 2015 DaRk-_-D0G. All rights reserved. // import Foundation public extension AnySequence { /** Returns each element of the sequence in an array :returns: Each element of the sequence in an array */ public func toArray () -> [Element] { var result: [Element] = [] for item in self { result.append(item) } return result } } public extension SequenceType { } // MARK: - String public extension SequenceType where Generator.Element == String { /** Count characters each cell of the array - returns: [Int] Array of count characters by cell in the array */ public func countByCharactersInArray() -> [Int] { return self.map{$0.characters.count} } /** Apprend all string after by after - returns: String */ public func appendAll() -> String { return String( self.map{$0.characters}.reduce(String.CharacterView(), combine: {$0 + $1})) } /** Array of String, find in array if has prefix String :param: ignoreCase True find lowercaseString :param: target String find :returns: Array of String find */ public func containsPrefix(ignoreCase:Bool,var target: String) -> [String] { let values = self.filter({ var val = $0 if ignoreCase { val = val.lowercaseString target = target.lowercaseString } return val.hasPrefix(target) ? true : false }) return values } /** Array of String, find in array if has suffix String :param: ignoreCase True find lowercaseString :param: target String find :returns: Array of String find */ public func containsSuffix(ignoreCase:Bool,var target: String) -> [String] { let values = self.filter({ var val = $0 if ignoreCase { val = val.lowercaseString target = target.lowercaseString } return val.hasSuffix(target) ? true : false }) return values } }
2b97933dfe0bead525e9b45c307652ae
24.053191
98
0.551827
false
false
false
false
ricealexanderb/forager
refs/heads/master
NewPatchViewController.swift
mit
1
// // NewPatchViewController.swift // Foragr // // Created by Alex on 8/13/14. // Copyright (c) 2014 Alex Rice. All rights reserved. // import UIKit class NewPatchViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate { @IBOutlet weak var nextHarvest: UIDatePicker! @IBOutlet weak var remindMe: UISwitch! @IBOutlet weak var plantTypeTextField: UITextField! @IBOutlet weak var suggestionLabel: UILabel! @IBOutlet weak var slidingView: UIView! @IBOutlet weak var topOfViewConstraint: NSLayoutConstraint! var plantTypes = ["Raspberries","Blackberries","Blueberries"] // TODO autocomplete should clear when there are no longer matching strings. // NOTE: look into "attributed strings" override func viewDidLoad() { super.viewDidLoad() self.nextHarvest.datePickerMode = UIDatePickerMode.Date let nextButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Bordered, target: self, action: "goNext") self.navigationItem.rightBarButtonItem = nextButton plantTypeTextField.delegate = self suggestionLabel.textColor = UIColor.lightGrayColor() var tapRecognizer = UITapGestureRecognizer(target: self, action: "completeSuggestion:") self.suggestionLabel.addGestureRecognizer(tapRecognizer) } func completeSuggestion(sender: UITapGestureRecognizer) { plantTypeTextField.text = suggestionLabel.text suggestionLabel.text = "" println("completed") } @IBAction func remindMeToggled(sender: AnyObject) { //UIUserNotificationSettings.aut } func goNext() { self.performSegueWithIdentifier("toPinMap", sender: self) } func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { println("replacement string: \(string)") if string == "" { println("backspace") } if countElements(plantTypeTextField.text) == 1 && string == "" { println("zero") suggestionLabel.text = "" return true } var currentText = textField.text + string currentText = currentText.lowercaseString // // UIColor* bgColor = [UIColor orangeColor]; // NSDictionary* style = @{ // NSBackgroundColorAttributeName: bgColor // }; // // NSAttributedString* myString = [[NSAttributedString alloc] initWithString:@"Touch Code Magazine" // attributes:style]; for suggestion in plantTypes { var normalizedSuggestion = suggestion.lowercaseString if (normalizedSuggestion.hasPrefix(currentText)) { var range = NSMakeRange(0, countElements(currentText)) // var bgColor = UIColor.blueColor() // var style = [ NSBackgroundColorAttributeName : bgColor ] //NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName]; var boldFontName = UIFont.boldSystemFontOfSize(17) //var suggestionString = NSAttributedString(string: suggestion, attributes: style) var suggestionWithBoldedSubstring = NSMutableAttributedString(string: suggestion) suggestionWithBoldedSubstring.addAttribute(NSFontAttributeName, value: boldFontName, range: range) suggestionLabel.attributedText = suggestionWithBoldedSubstring //[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange]; //suggestionLabel.attributedText = suggestionString //suggestionLabel.text = suggestion return true } } //suggestionLabel.text = string return true } override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { self.plantTypeTextField.resignFirstResponder() } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { var newPin = segue.destinationViewController as NewPinViewController newPin.plantName = plantTypeTextField.text println("Setting Pin's name to \(plantTypeTextField.text)") newPin.nextHarvest = nextHarvest.date if remindMe.on { println("pre segue Set reminder") } else { println("pre segue don't set reminder") } newPin.reminder = remindMe.on } //MARK: plant type picker func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int { return plantTypes.count } func pickerView(pickerView: UIPickerView!, titleForRow row: Int,forComponent component: Int) -> String! { return plantTypes[row] } func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int { return 1 } func textFieldDidBeginEditing(textField: UITextField!) { println("slide out") //self.view.layoutIfNeeded() topOfViewConstraint.constant += 30 UIView.animateWithDuration(0.4, animations: { () -> Void in self.view.layoutIfNeeded() }) } func textFieldDidEndEditing(textField: UITextField!) { println("slide in") topOfViewConstraint.constant -= 30 UIView.animateWithDuration(0.4, animations: { () -> Void in self.view.layoutIfNeeded() }) } }
fb71f1813d71f0ac09e144f9ccca550e
33.874251
134
0.625515
false
false
false
false
lcepy/STNetWork
refs/heads/master
STNetWork/STNetWorkResponse.swift
mit
2
// // STNetWorkResponse.swift // STNetWork // // Created by xiangwenwen on 15/6/12. // Copyright (c) 2015年 xiangwenwen. All rights reserved. // import UIKit class STNetworkResponse: NSObject { var httpResponse:NSHTTPURLResponse? var response:NSURLResponse? var responseHeader:Dictionary<NSObject,AnyObject>? var responseCookie:Dictionary<NSObject,AnyObject>! init(response:NSURLResponse?) { self.httpResponse = response as? NSHTTPURLResponse self.response = response self.responseHeader = self.httpResponse?.allHeaderFields super.init() self.responseCookie = self.getAllResponseCookie() } /** 获取 response所有的头信息 :returns: <#return value description#> */ func getAllResponseHeader()-> Dictionary<NSObject,AnyObject>?{ if let responseHeader = self.responseHeader{ return responseHeader } return nil } /** 获取 response的响应状态 :returns: <#return value description#> */ func getStatusCode()->Int?{ return self.httpResponse?.statusCode } /** 根据key返回一个header值 :param: headerKey <#headerKey description#> :returns: <#return value description#> */ func getResponseHeader(headerKey:NSObject?)->AnyObject?{ if let key = headerKey{ return self.responseHeader![headerKey!] } return nil } /** 获取所有的 cookie (注意,这个方法获取的是全局的) :returns: <#return value description#> */ func getAllStorageCookie()->Array<AnyObject>?{ var cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage() if let cookies:Array<AnyObject> = cookieStorage.cookies{ return cookies } return nil } /** 获取当前 response 的所有cookie :returns: <#return value description#> */ func getAllResponseCookie()->Dictionary<NSObject,AnyObject>?{ self.responseCookie = [:] if let cookiesString: NSString = self.responseHeader!["Set-Cookie" as NSObject] as? NSString{ var cookiesArray:Array<AnyObject> = cookiesString.componentsSeparatedByString(";") for cookiesOne in cookiesArray{ if let _cookiesOne = cookiesOne as? NSString{ var _cookiesArray:Array<AnyObject> = _cookiesOne.componentsSeparatedByString(",") for _cookiesString in _cookiesArray{ if var _value = _cookiesString as? NSString{ _value = _value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) var cookie:Array<AnyObject> = _value.componentsSeparatedByString("=") var cookieKey:String = String(cookie[0] as! String) self.responseCookie[cookieKey as NSObject] = cookie[1] } } }else{ if var value = cookiesOne as? NSString{ value = value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) var cookie:Array<AnyObject> = value.componentsSeparatedByString("=") var cookieKey:String = String(cookie[0] as! String) self.responseCookie[cookieKey as NSObject] = cookie[1] } } } return self.responseCookie } return nil } /** 根据key返回一个cookie值 :param: cookieKey <#cookieKey description#> :returns: <#return value description#> */ func getResponseCookie(cookieKey:NSObject?)->AnyObject?{ if let key:NSObject = cookieKey{ if let value:AnyObject = self.responseCookie?[key]{ return value } return nil } return nil } }
cfc2fea75dcbf3152f73a21012ca2e2c
31.131148
116
0.587395
false
false
false
false
crewshin/GasLog
refs/heads/master
My First IOS App/Pods/RealmSwift/RealmSwift/SortDescriptor.swift
apache-2.0
3
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm /** A `SortDescriptor` stores a property name and a sort order for use with `sorted(sortDescriptors:)`. It is similar to `NSSortDescriptor`, but supports only the subset of functionality which can be efficiently run by Realm's query engine. */ public struct SortDescriptor { // MARK: Properties /// The name of the property which this sort descriptor orders results by. public let property: String /// Whether this descriptor sorts in ascending or descending order. public let ascending: Bool /// Converts the receiver to an `RLMSortDescriptor` internal var rlmSortDescriptorValue: RLMSortDescriptor { return RLMSortDescriptor(property: property, ascending: ascending) } // MARK: Initializers /** Creates a `SortDescriptor` with the given property and ascending values. - parameter property: The name of the property which this sort descriptor orders results by. - parameter ascending: Whether this descriptor sorts in ascending or descending order. */ public init(property: String, ascending: Bool = true) { self.property = property self.ascending = ascending } // MARK: Functions /// Returns a copy of the `SortDescriptor` with the sort order reversed. public func reversed() -> SortDescriptor { return SortDescriptor(property: property, ascending: !ascending) } } // MARK: CustomStringConvertible extension SortDescriptor: CustomStringConvertible { /// Returns a human-readable description of the sort descriptor. public var description: String { let direction = ascending ? "ascending" : "descending" return "SortDescriptor (property: \(property), direction: \(direction))" } } // MARK: Equatable extension SortDescriptor: Equatable {} // swiftlint:disable valid_docs /// Returns whether the two sort descriptors are equal. public func == (lhs: SortDescriptor, rhs: SortDescriptor) -> Bool { return lhs.property == rhs.property && lhs.ascending == lhs.ascending } // swiftlint:enable valid_docs // MARK: StringLiteralConvertible extension SortDescriptor: StringLiteralConvertible { /// `StringLiteralType`. Required for `StringLiteralConvertible` conformance. public typealias UnicodeScalarLiteralType = StringLiteralType /// `StringLiteralType`. Required for `StringLiteralConvertible` conformance. public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType /** Creates a `SortDescriptor` from a `UnicodeScalarLiteralType`. - parameter unicodeScalarLiteral: Property name literal. */ public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(property: value) } /** Creates a `SortDescriptor` from an `ExtendedGraphemeClusterLiteralType`. - parameter extendedGraphemeClusterLiteral: Property name literal. */ public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(property: value) } /** Creates a `SortDescriptor` from a `StringLiteralType`. - parameter stringLiteral: Property name literal. */ public init(stringLiteral value: StringLiteralType) { self.init(property: value) } }
b01028a3128156d7d5f81ca5320f932b
31.475806
97
0.698038
false
false
false
false
Msr-B/FanFan-iOS
refs/heads/master
WeCenterMobile/View/Answer/AnswerCellWithQuestionTitle.swift
gpl-2.0
3
// // AnswerCellWithQuestionTitle.swift // WeCenterMobile // // Created by Darren Liu on 15/4/12. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class AnswerCellWithQuestionTitle: UITableViewCell { @IBOutlet weak var questionTitleLabel: UILabel! @IBOutlet weak var answerUserAvatarView: MSRRoundedImageView! @IBOutlet weak var answerUserNameLabel: UILabel! @IBOutlet weak var answerBodyLabel: UILabel! @IBOutlet weak var answerAgreementCountLabel: UILabel! @IBOutlet weak var questionButton: UIButton! @IBOutlet weak var answerButton: UIButton! @IBOutlet weak var userButton: UIButton! @IBOutlet weak var containerView: UIView! @IBOutlet weak var questionContainerView: UIView! @IBOutlet weak var userContainerView: UIView! @IBOutlet weak var answerContainerView: UIView! @IBOutlet weak var separatorA: UIView! @IBOutlet weak var separatorB: UIView! override func awakeFromNib() { super.awakeFromNib() let theme = SettingsManager.defaultManager.currentTheme msr_scrollView?.delaysContentTouches = false for v in [containerView, answerAgreementCountLabel] { v.msr_borderColor = theme.borderColorA } for v in [separatorA, separatorB] { v.backgroundColor = theme.borderColorA } for v in [questionContainerView, userContainerView] { v.backgroundColor = theme.backgroundColorB } for v in [answerContainerView, answerAgreementCountLabel] { v.backgroundColor = theme.backgroundColorA } for v in [questionButton, userButton, answerButton] { v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } for v in [answerBodyLabel, answerAgreementCountLabel] { v.textColor = theme.subtitleTextColor } questionTitleLabel.textColor = theme.titleTextColor } func update(answer answer: Answer) { questionTitleLabel.text = answer.question!.title answerUserAvatarView.wc_updateWithUser(answer.user) let theme = SettingsManager.defaultManager.currentTheme let text = NSMutableAttributedString(string: answer.user?.name ?? "匿名用户", attributes: [ NSFontAttributeName: UIFont.systemFontOfSize(14), NSForegroundColorAttributeName: theme.titleTextColor]) if let signature = answer.user?.signature?.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()) { text.appendAttributedString(NSAttributedString(string: "," + signature, attributes: [ NSFontAttributeName: UIFont.systemFontOfSize(14), NSForegroundColorAttributeName: theme.footnoteTextColor])) } answerUserNameLabel.attributedText = text answerBodyLabel.text = answer.body!.wc_plainString answerAgreementCountLabel.text = answer.agreementCount?.description ?? "0" questionButton.msr_userInfo = answer.question answerButton.msr_userInfo = answer userButton.msr_userInfo = answer.user setNeedsLayout() layoutIfNeeded() } }
83f2a932c48186a24419154a284c55f5
42.133333
122
0.700155
false
false
false
false
NextLevel/NextLevel
refs/heads/main
Project/NextLevel/FocusIndicatorView.swift
mit
1
// // CameraViewController.swift // NextLevel (http://github.com/NextLevel) // // Copyright (c) 2016-present patrick piemonte (http://patrickpiemonte.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Foundation public class FocusIndicatorView: UIView { // MARK: - ivars private lazy var _focusRingView: UIImageView = { let view = UIImageView(image: UIImage(named: "focus_indicator")) return view }() // MARK: - object lifecycle public override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear self.contentMode = .scaleToFill _focusRingView.alpha = 0 self.addSubview(_focusRingView) self.frame = self._focusRingView.frame self.prepareAnimation() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { self._focusRingView.layer.removeAllAnimations() } } // MARK: - animation extension FocusIndicatorView { private func prepareAnimation() { // prepare animation self._focusRingView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) self._focusRingView.alpha = 0 } public func startAnimation() { self._focusRingView.layer.removeAllAnimations() // animate UIView.animate(withDuration: 0.2) { self._focusRingView.alpha = 1 } UIView.animate(withDuration: 0.5) { self._focusRingView.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) } } public func stopAnimation() { self._focusRingView.layer.removeAllAnimations() UIView.animate(withDuration: 0.2) { self._focusRingView.alpha = 0 } UIView.animate(withDuration: 0.2) { self._focusRingView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) } completion: { (completed) in if completed { self.removeFromSuperview() } } } }
bdb36cb65fa99d084710f22d9196b647
30.642857
84
0.664947
false
false
false
false
julienbodet/wikipedia-ios
refs/heads/develop
Wikipedia/Code/WMFForgotPasswordViewController.swift
mit
1
import UIKit class WMFForgotPasswordViewController: WMFScrollViewController, Themeable { @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var subTitleLabel: UILabel! @IBOutlet fileprivate var usernameField: ThemeableTextField! @IBOutlet fileprivate var emailField: ThemeableTextField! @IBOutlet fileprivate var usernameTitleLabel: UILabel! @IBOutlet fileprivate var emailTitleLabel: UILabel! @IBOutlet fileprivate var orLabel: UILabel! @IBOutlet fileprivate var resetPasswordButton: WMFAuthButton! fileprivate var theme = Theme.standard let tokenFetcher = WMFAuthTokenFetcher() let passwordResetter = WMFPasswordResetter() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:))) navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel titleLabel.text = WMFLocalizedString("forgot-password-title", value:"Reset password", comment:"Title for reset password interface\n{{Identical|Reset password}}") subTitleLabel.text = WMFLocalizedString("forgot-password-instructions", value:"Fill in one of the fields below to receive password reset instructions via email", comment:"Instructions for resetting password") usernameField.placeholder = WMFLocalizedString("field-username-placeholder", value:"enter username", comment:"Placeholder text shown inside username field until user taps on it") emailField.placeholder = WMFLocalizedString("field-email-placeholder", value:"[email protected]", comment:"Placeholder text shown inside email address field until user taps on it") usernameTitleLabel.text = WMFLocalizedString("field-username-title", value:"Username", comment:"Title for username field\n{{Identical|Username}}") emailTitleLabel.text = WMFLocalizedString("field-email-title", value:"Email", comment:"Noun. Title for email address field.\n{{Identical|E-mail}}") resetPasswordButton.setTitle(WMFLocalizedString("forgot-password-button-title", value:"Reset", comment:"Title for reset password button\n{{Identical|Reset}}"), for: .normal) orLabel.text = WMFLocalizedString("forgot-password-username-or-email-title", value:"Or", comment:"Title shown between the username and email text fields. User only has to specify either username \"Or\" email address\n{{Identical|Or}}") view.wmf_configureSubviewsForDynamicType() apply(theme: theme) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) enableProgressiveButton(false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) usernameField.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) enableProgressiveButton(false) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { if (textField == usernameField) { emailField.becomeFirstResponder() } else if (textField == emailField) { save() } return true } @IBAction func textFieldDidChange(_ sender: UITextField) { guard let username = usernameField.text, let email = emailField.text else{ enableProgressiveButton(false) return } enableProgressiveButton((username.count > 0 || email.count > 0)) } func enableProgressiveButton(_ highlight: Bool) { resetPasswordButton.isEnabled = highlight } @IBAction fileprivate func resetPasswordButtonTapped(withSender sender: UIButton) { save() } fileprivate func save() { wmf_hideKeyboard() sendPasswordResetEmail(userName: usernameField.text, email: emailField.text) } @objc func closeButtonPushed(_ : UIBarButtonItem) { dismiss(animated: true, completion: nil) } func sendPasswordResetEmail(userName: String?, email: String?) { guard let siteURL = MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() else { WMFAlertManager.sharedInstance.showAlert("No site url", sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) return } let failure: WMFErrorHandler = {error in WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) } tokenFetcher.fetchToken(ofType: .csrf, siteURL: siteURL, success: { tokenBlock in self.passwordResetter.resetPassword( siteURL: siteURL, token: tokenBlock.token, userName: userName, email: email, success: { result in self.dismiss(animated: true, completion:nil) WMFAlertManager.sharedInstance.showSuccessAlert(WMFLocalizedString("forgot-password-email-sent", value:"An email with password reset instructions was sent", comment:"Alert text shown when password reset email is sent"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) }, failure:failure) }, failure:failure) } func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground view.tintColor = theme.colors.link titleLabel.textColor = theme.colors.primaryText let labels = [subTitleLabel, usernameTitleLabel, emailTitleLabel, orLabel] for label in labels { label?.textColor = theme.colors.secondaryText } usernameField.apply(theme: theme) emailField.apply(theme: theme) resetPasswordButton.apply(theme: theme) } }
ceddc0a7df840ccba9ee14801fac2a31
43.642336
300
0.680674
false
false
false
false
jboullianne/EndlessTunes
refs/heads/master
EndlessSoundFeed/SearchManager.swift
gpl-3.0
1
// // SearchManager.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 5/2/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import Foundation import Alamofire import AlamofireImage import AVFoundation import FirebaseDatabase class SearchManager{ static let sharedInstance = SearchManager() struct ETUser { var displayName:String var email:String var uid:String } var soundCloudResults:[Track] var spotifyResults:[Track] var allPartiesResults:[PartyManager.ETParty] var spPartiesResults:[PartyManager.ETParty] var collabPartiesResults:[PartyManager.ETParty] var userResults:[ETUser] var friendResults:[ETUser] var homeTracks:[Track] var player:AVPlayer? var lastTrackQuery:String = "" var lastPartyQuery:String = "" var lastUserQuery:String = "" private init() { self.spotifyResults = [] self.soundCloudResults = [] self.allPartiesResults = [] self.spPartiesResults = [] self.collabPartiesResults = [] self.friendResults = [] self.userResults = [] self.homeTracks = [] self.player = AVPlayer() } func attachImageToTrack(image:UIImage, url:String){ for track in spotifyResults{ if track.thumbnailURL == url{ track.thumbnailImage = image } } for track in soundCloudResults{ if track.thumbnailURL == url{ track.thumbnailImage = image } } } //Query SoundCloud / Spotify Tracks func queryTracks( q:String, callback: @escaping ()->()){ print("SearchManager: Query Tracks! q=\(q)") if lastTrackQuery != q { querySoundCloud(query: q) { callback() } querySpotify(query: q) { callback() } lastTrackQuery = q }else{ callback() } } //Query Users From Firebase func queryUsers( q:String, callback: @escaping ()->()){ print("SearchManager: Query Users! q=\(q)") if lastUserQuery != q { queryAllUsers(query: q) { callback() } queryFriends(query: q, owneruid: AccountManager.sharedInstance.currentUser!.uid) { callback() } lastUserQuery = q }else{ callback() } } //Query Parties From Firebase func queryParties( q:String, callback: @escaping ()->()){ print("SearchManager: Query Parties! q=\(q)") if lastPartyQuery != q { queryAllParties(query: q) { callback() } lastPartyQuery = q }else{ callback() } } func querySoundCloud(query:String, callback: @escaping ()->()){ print("Starting Query with SoundCloud!") let sq = query.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) //print("SQ: ", sq) soundCloudResults.removeAll() Alamofire.request("https://api.soundcloud.com/tracks?q=\(sq!)&client_id=acba82beee52b1215da96546eb0fabb6").responseJSON { response in //print(response.request) // original URL request //print(response.response) // HTTP URL response //print(response.data) // server data print(response.result) // result of response serialization //print(response.result.value) if let items = response.result.value as? NSArray{ for i in items { let item = i as! NSDictionary let streamable = item["streamable"] as! Bool if !streamable { continue } let thumbnailURL = item["artwork_url"] as? String let title = item["title"] as! String let author = (item["user"] as! NSDictionary)["username"] as! String let uri = (item["stream_url"] as! String) + "?client_id=acba82beee52b1215da96546eb0fabb6" //print("TITLE: ", title, author, thumbnailURL, uri) let track = Track(title: title, author: author, thumbnailURL: thumbnailURL, uri: uri, source: .SoundCloud) self.soundCloudResults.append(track) } callback() } } } func querySpotify(query: String, callback: @escaping ()->()){ let appDelegate = UIApplication.shared.delegate as! AppDelegate guard let session = appDelegate.spSession else{ return } spotifyResults.removeAll() SPTSearch.perform(withQuery: query, queryType: .queryTypeTrack, accessToken: session.accessToken, callback: { (error, data) in if let result = data as? SPTListPage{ guard (result.items) != nil else { return } for x in result.items { let item = x as! SPTPartialTrack let artist = (item.artists[0] as! SPTPartialArtist).name! let title = item.name! let smallThumbnail = item.album.smallestCover.imageURL.absoluteString let thumbnailURL = item.album.largestCover.imageURL.absoluteString let uri = item.uri.absoluteString let track = Track(title: title, author: artist, thumbnailURL: thumbnailURL, uri: uri, source: .Spotify) track.smallThumbnailURL = smallThumbnail self.spotifyResults.append(track) print("ARTIST: ", artist) } /* let track = result.items[0] as! SPTPartialTrack self.spotifyPlayer?.playSpotifyURI(track.uri.absoluteString, startingWith: 0, startingWithPosition: 0, callback: { (error) in if (error != nil) { print("playing!") } }) */ } }) } func queryAllUsers(query:String, callback: @escaping ()->()){ print("Starting Query Against User List!") let _ = AccountManager.sharedInstance.ref.child("p_users").queryOrdered(byChild: "displayname").queryStarting(atValue: query.lowercased(), childKey: "displayname").queryLimited(toFirst: 20).observeSingleEvent(of: .value, with: { (snap) in self.userResults.removeAll() for user in snap.children { let temp = user as! FIRDataSnapshot if let details = temp.value as? NSDictionary{ let displayName = details["displayname"] as! String let email = details["email"] as! String let uid = details["uid"] as! String let uResult = ETUser(displayName: displayName, email: email, uid: uid) self.userResults.append(uResult) } } print("Users Found: \(self.userResults)") callback() }) } func queryFriends(query:String, owneruid: String, callback: @escaping ()->()){ print("Starting Query Against User List!") let _ = AccountManager.sharedInstance.ref.child("/f_users/\(owneruid)/").queryOrdered(byChild: "displayname").queryStarting(atValue: query.lowercased(), childKey: "displayname").queryLimited(toFirst: 20).observeSingleEvent(of: .value, with: { (snap) in self.friendResults.removeAll() for user in snap.children { let temp = user as! FIRDataSnapshot if let details = temp.value as? NSDictionary{ let displayName = details["displayname"] as! String let email = details["email"] as! String let uid = details["uid"] as! String let uResult = ETUser(displayName: displayName, email: email, uid: uid) self.friendResults.append(uResult) } } callback() print("Users Found: \(self.friendResults)") }) } func queryAllParties(query: String, callback: @escaping ()->()) { let _ = AccountManager.sharedInstance.ref.child("/p_parties").queryOrdered(byChild: "name").queryStarting(atValue: query).queryLimited(toLast: 20).observeSingleEvent(of: .value, with: { (snap) in self.allPartiesResults.removeAll() for party in snap.children { let temp = party as! FIRDataSnapshot if let details = temp.value as? NSDictionary{ let partyID = temp.key let name = details["name"] as! String let ownerID = details["owneruid"] as! String let ownername = details["ownername"] as! String let isPublic = true let isSpotifyEnabled = details["sp_enabled"] as! Bool let isCollaborative = details["collab"] as! Bool let npThumbURL = details["np_thumb"] as? String let userCount = details["u_count"] as! Int let pResult = PartyManager.ETParty(partyID: partyID, name: name, ownerID: ownerID, ownername: ownername, isPublic: isPublic, isSpotifyEnabled: isSpotifyEnabled, isCollaborative: isCollaborative, npThumbURL: npThumbURL, image: nil, userCount: userCount) self.allPartiesResults.append(pResult) } } print("SORTED PARTIES: \(self.allPartiesResults)") //Sort The Parties Further self.buildSPParties() self.buildCollabParties() callback() }) } func buildSPParties() { self.spPartiesResults.removeAll() for party in self.allPartiesResults { if party.isSpotifyEnabled { self.spPartiesResults.append(party) } } } func buildCollabParties() { self.collabPartiesResults.removeAll() for party in self.allPartiesResults { if party.isCollaborative { self.collabPartiesResults.append(party) } } } func playTrack(atIndex index:Int, section:Int){ if section == 0 { let selectedTrack = soundCloudResults[index] MediaManager.sharedInstance.playTrack(track: selectedTrack) }else if section == 1{ let selectedTrack = spotifyResults[index] MediaManager.sharedInstance.playTrack(track: selectedTrack) } } }
b09d5d1c8e0f664221ea22c8d63713f5
34.589506
272
0.523632
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/ProfileInfoPresentationController.swift
apache-2.0
1
// // ProfileInfoPresentationController.swift // Slide for Reddit // // Created by Carlos Crane on 9/15/19. // Copyright © 2019 Haptic Apps. All rights reserved. // import Anchorage import Then import UIKit class ProfileInfoPresentationController: UIPresentationController { fileprivate var dimmingView: UIVisualEffectView! fileprivate var backgroundView: UIView! // Mirror Manager params here override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) setupDimmingView() } override func containerViewWillLayoutSubviews() { presentedView?.frame = frameOfPresentedViewInContainerView dimmingView.frame = frameOfPresentedViewInContainerView backgroundView.frame = frameOfPresentedViewInContainerView } override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize { return CGSize(width: parentSize.width, height: parentSize.height) } override func presentationTransitionWillBegin() { let accountView = presentedViewController as! ProfileInfoViewController if let containerView = containerView { containerView.insertSubview(dimmingView, at: 0) containerView.insertSubview(backgroundView, at: 0) // accountView.view.removeFromSuperview() // TODO: - Risky? containerView.addSubview(accountView.view) } if presentedViewController.transitionCoordinator != nil { UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: { self.dimmingView.effect = self.blurEffect }) } else { dimmingView.effect = blurEffect } } override func dismissalTransitionWillBegin() { if let coordinator = presentedViewController.transitionCoordinator { coordinator.animate(alongsideTransition: { _ in self.dimmingView.alpha = 0 self.backgroundView.alpha = 0 }, completion: { _ in self.dimmingView.alpha = 1 self.backgroundView.alpha = 0.7 }) } else { dimmingView.effect = nil } } lazy var blurEffect: UIBlurEffect = { return (NSClassFromString("_UICustomBlurEffect") as! UIBlurEffect.Type).init().then { $0.setValue(5, forKeyPath: "blurRadius") } }() } // MARK: - Private private extension ProfileInfoPresentationController { func setupDimmingView() { backgroundView = UIView(frame: UIScreen.main.bounds).then { $0.backgroundColor = .black $0.alpha = 0.7 } dimmingView = UIVisualEffectView(frame: UIScreen.main.bounds).then { $0.effect = nil } } }
67950abff45d36468ebca47342dbe3ec
32.01087
95
0.653606
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/OSX/AudioKit/AudioKit for OSX.playground/Pages/SelectorClock.xcplaygroundpage/Contents.swift
mit
1
import XCPlayground import AudioKit class SelectorClock { var sequencer = AKSequencer() var callbacker: AKCallbackInstrument? var bpm: Double var output:AKNode? init(tempo: Double = 120, division: Int = 4) { bpm = tempo callbacker = AKCallbackInstrument() { status, note, velocity in if note == 60 && status == .NoteOn { print("myClock -> Start Note 60 at \(myClock.sequencer.currentPositionInBeats)") } } output = callbacker let clickTrack = sequencer.newTrack() for i in 0 ..< division { clickTrack?.addNote(80, velocity: 100, position: Double(i) / Double(division) , duration: Double(0.1 / Double(division))) clickTrack?.addNote(60, velocity: 100, position: (Double(i) + 0.5) / Double(division) , duration: Double(0.1 / Double(division))) } clickTrack?.setMIDIOutput((callbacker?.midiIn)!) clickTrack?.setLoopInfo(1.0, numberOfLoops: 0) sequencer.setTempo(bpm) } func start() { sequencer.rewind() sequencer.play() } func pause() { sequencer.stop() } func stop() { sequencer.stop() sequencer.rewind() } func play() { sequencer.play() } var tempo: Double { get { return self.bpm } set { sequencer.setTempo(newValue) } } } // at Tempo 120, that will trigger every sixteenth note var myClock = SelectorClock(tempo: 120, division: 1) func myFunction(status: AKMIDIStatus, note: MIDINoteNumber, velocity: MIDIVelocity) { if note == 80 && status == .NoteOn { print("myClock -> Start Note 80 at \(myClock.sequencer.currentPositionInBeats)") } } myClock.callbacker?.callbacks.append(myFunction) // We must link the clock's output to AudioKit (even if we don't need the sound) AudioKit.output = myClock.output AudioKit.start() // Then We can start the clock ! myClock.start() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
0f09e96a7531c603dd6d83ad2a3ca095
24.795181
141
0.598319
false
false
false
false
adrfer/swift
refs/heads/master
stdlib/public/core/StringBridge.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) // Swift's String bridges NSString via this protocol and these // variables, allowing the core stdlib to remain decoupled from // Foundation. /// Effectively an untyped NSString that doesn't require foundation. public typealias _CocoaStringType = AnyObject public // @testable func _stdlib_binary_CFStringCreateCopy( source: _CocoaStringType ) -> _CocoaStringType { let result = _swift_stdlib_CFStringCreateCopy(nil, source) Builtin.release(result) return result } public // @testable func _stdlib_binary_CFStringGetLength( source: _CocoaStringType ) -> Int { return _swift_stdlib_CFStringGetLength(source) } public // @testable func _stdlib_binary_CFStringGetCharactersPtr( source: _CocoaStringType ) -> UnsafeMutablePointer<UTF16.CodeUnit> { return UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(source)) } /// Bridges `source` to `Swift.String`, assuming that `source` has non-ASCII /// characters (does not apply ASCII optimizations). @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency func _cocoaStringToSwiftString_NonASCII( source: _CocoaStringType ) -> String { let cfImmutableValue = _stdlib_binary_CFStringCreateCopy(source) let length = _stdlib_binary_CFStringGetLength(cfImmutableValue) let start = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue) return String(_StringCore( baseAddress: COpaquePointer(start), count: length, elementShift: 1, hasCocoaBuffer: true, owner: unsafeBitCast(cfImmutableValue, Optional<AnyObject>.self))) } /// Loading Foundation initializes these function variables /// with useful values /// Produces a `_StringBuffer` from a given subrange of a source /// `_CocoaStringType`, having the given minimum capacity. @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringToContiguous( source: _CocoaStringType, _ range: Range<Int>, minimumCapacity: Int ) -> _StringBuffer { _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(source) == nil, "Known contiguously-stored strings should already be converted to Swift") let startIndex = range.startIndex let count = range.endIndex - startIndex let buffer = _StringBuffer(capacity: max(count, minimumCapacity), initialSize: count, elementWidth: 2) _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange(location: startIndex, length: count), UnsafeMutablePointer<_swift_shims_UniChar>(buffer.start)) return buffer } /// Reads the entire contents of a _CocoaStringType into contiguous /// storage of sufficient capacity. @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringReadAll( source: _CocoaStringType, _ destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange( location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination) } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringSlice( target: _StringCore, _ subRange: Range<Int> ) -> _StringCore { _sanityCheck(target.hasCocoaBuffer) let cfSelf: _swift_shims_CFStringRef = unsafeUnwrap(target.cocoaBuffer) _sanityCheck( _swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil, "Known contiguously-stored strings should already be converted to Swift") let cfResult: AnyObject = _swift_stdlib_CFStringCreateWithSubstring( nil, cfSelf, _swift_shims_CFRange( location: subRange.startIndex, length: subRange.count)) return String(_cocoaString: cfResult)._core } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringSubscript( target: _StringCore, _ position: Int ) -> UTF16.CodeUnit { let cfSelf: _swift_shims_CFStringRef = unsafeUnwrap(target.cocoaBuffer) _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf)._isNull, "Known contiguously-stored strings should already be converted to Swift") return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position) } // // Conversion from NSString to Swift's native representation // internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding { return 0x0600 } extension String { @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency public // SPI(Foundation) init(_cocoaString: AnyObject) { if let wrapped = _cocoaString as? _NSContiguousString { self._core = wrapped._core return } // "copy" it into a value to be sure nobody will modify behind // our backs. In practice, when value is already immutable, this // just does a retain. let cfImmutableValue: _swift_shims_CFStringRef = _stdlib_binary_CFStringCreateCopy(_cocoaString) let length = _swift_stdlib_CFStringGetLength(cfImmutableValue) // Look first for null-terminated ASCII // Note: the code in clownfish appears to guarantee // nul-termination, but I'm waiting for an answer from Chris Kane // about whether we can count on it for all time or not. let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr( cfImmutableValue, kCFStringEncodingASCII) // start will hold the base pointer of contiguous storage, if it // is found. var start = UnsafeMutablePointer<RawByte>(nulTerminatedASCII) let isUTF16 = nulTerminatedASCII._isNull if (isUTF16) { start = UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue)) } self._core = _StringCore( baseAddress: COpaquePointer(start), count: length, elementShift: isUTF16 ? 1 : 0, hasCocoaBuffer: true, owner: unsafeBitCast(cfImmutableValue, Optional<AnyObject>.self)) } } // At runtime, this class is derived from `_SwiftNativeNSStringBase`, // which is derived from `NSString`. // // The @_swift_native_objc_runtime_base attribute // This allows us to subclass an Objective-C class and use the fast Swift // memory allocator. @objc @_swift_native_objc_runtime_base(_SwiftNativeNSStringBase) public class _SwiftNativeNSString {} @objc public protocol _NSStringCoreType : _NSCopyingType, _NSFastEnumerationType { // The following methods should be overridden when implementing an // NSString subclass. func length() -> Int func characterAtIndex(index: Int) -> UInt16 // We also override the following methods for efficiency. } /// An `NSString` built around a slice of contiguous Swift `String` storage. public final class _NSContiguousString : _SwiftNativeNSString { public init(_ _core: _StringCore) { _sanityCheck( _core.hasContiguousStorage, "_NSContiguousString requires contiguous storage") self._core = _core super.init() } init(coder aDecoder: AnyObject) { _sanityCheckFailure("init(coder:) not implemented for _NSContiguousString") } func length() -> Int { return _core.count } func characterAtIndex(index: Int) -> UInt16 { return _core[index] } func getCharacters( buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange) { _precondition(aRange.location + aRange.length <= Int(_core.count)) if _core.elementWidth == 2 { UTF16._copy( _core.startUTF16 + aRange.location, destination: UnsafeMutablePointer<UInt16>(buffer), count: aRange.length) } else { UTF16._copy( _core.startASCII + aRange.location, destination: UnsafeMutablePointer<UInt16>(buffer), count: aRange.length) } } @objc func _fastCharacterContents() -> UnsafeMutablePointer<UInt16> { return _core.elementWidth == 2 ? UnsafeMutablePointer(_core.startUTF16) : nil } // // Implement sub-slicing without adding layers of wrapping // func substringFromIndex(start: Int) -> _NSContiguousString { return _NSContiguousString(_core[Int(start)..<Int(_core.count)]) } func substringToIndex(end: Int) -> _NSContiguousString { return _NSContiguousString(_core[0..<Int(end)]) } func substringWithRange(aRange: _SwiftNSRange) -> _NSContiguousString { return _NSContiguousString( _core[Int(aRange.location)..<Int(aRange.location + aRange.length)]) } func copy() -> AnyObject { // Since this string is immutable we can just return ourselves. return self } public let _core: _StringCore } extension String { /// Same as `_bridgeToObjectiveC()`, but located inside the core standard /// library. public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject { if let ns = _core.cocoaBuffer where _swift_stdlib_CFStringGetLength(ns) == _core.count { return ns } _sanityCheck(_core.hasContiguousStorage) return _NSContiguousString(_core) } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency public func _bridgeToObjectiveCImpl() -> AnyObject { return _stdlib_binary_bridgeToObjectiveCImpl() } } #endif
105c2ecca74dd76ebc97592ba6d35751
31.773196
92
0.712488
false
false
false
false
xmartlabs/Bender
refs/heads/master
Sources/Adapters/Tensorflow/String+TFParsing.swift
mit
1
// // String+TFParsing.swift // Bender // // Created by Mathias Claassen on 5/18/17. // // extension Tensorflow_NodeDef { var isTFAddOp: Bool { return op == Constants.Ops.Add } var isTFVariableAssignOp: Bool { return op == Constants.Ops.Assign } var isTFFusedBatchNorm: Bool { return op == Constants.Ops.FusedBatchNorm } var isTFBatchNormGlobal: Bool { return op == Constants.Ops.BatchNormGlobal } var isTFBatchToSpace: Bool { return op == Constants.Ops.BatchToSpace } var isTFBiasAddOp: Bool { return op == Constants.Ops.BiasAdd } var isTFConvOp: Bool { return op == Constants.Ops.Conv } var isTFConstOp: Bool { return op == Constants.Ops.Const } var isTFDepthwiseConvOp: Bool { return op == Constants.Ops.DepthwiseConv } var isTFInstanceNormMulOp: Bool { return op == Constants.Ops.InstanceNormMul } var isTFMatMulOp: Bool { return op == Constants.Ops.MatMul } var isTFMeanOp: Bool { return op == Constants.Ops.Mean } var isTFMulOp: Bool { return op == Constants.Ops.Mul } var isTFPowOp: Bool { return op == Constants.Ops.Pow } var isTFQReshapeOp: Bool { return op == Constants.Ops.QuantizedReshape } var isTFRsqrtOp: Bool { return op == Constants.Ops.Rsqrt } var isTFRealDivOp: Bool { return op == Constants.Ops.RealDiv } var isTFReshapeOp: Bool { return op == Constants.Ops.Reshape } var isTFReLuOp: Bool { return op == Constants.Ops.Relu } var isTFShapeOp: Bool { return op == Constants.Ops.Shape } var isTFSigmoidOp: Bool { return op == Constants.Ops.Sigmoid } var isTFSpaceToBatch: Bool { return op == Constants.Ops.SpaceToBatch } var isTFSubOp: Bool { return op == Constants.Ops.Sub } var isTFSwitchOp: Bool { return op == Constants.Ops.Switch } var isTFTanhOp: Bool { return op == Constants.Ops.Tanh } var isTFVariableV2Op: Bool { return op == Constants.Ops.Variable } var isTFVariableOrConstOp: Bool { return isTFVariableV2Op || isTFConstOp } } // Node Names extension Tensorflow_NodeDef { var isTFMovMean: Bool { return name.hasSuffix("/moving_mean") } var isTFMovVariance: Bool { return name.hasSuffix("/moving_variance") } var isTFGamma: Bool { return name.hasSuffix("/gamma") } var isTFBeta: Bool { return name.hasSuffix("/beta") } }
36c455def23477b1484ce5033c4fad44
45.55102
82
0.701008
false
false
false
false
google/iosched-ios
refs/heads/master
Source/IOsched/Application/Application+Indexing.swift
apache-2.0
1
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import CoreSpotlight import MobileCoreServices extension Application { private enum DeepLinkingConstants { static let sessionID = "sessionId" } func navigateToDeepLink(uniqueIdPath: String) { let uniqueIdComponents = uniqueIdPath.components(separatedBy: "/") if uniqueIdComponents.count == 2 { let uniqueIdentifier = uniqueIdComponents[1] if let type = IndexConstants(rawValue: uniqueIdComponents[0]) { switch type { case .sessionDomainIdentifier: tabBarController.selectedViewController = scheduleNavigationController scheduleNavigator.navigateToSessionDetails(sessionID: uniqueIdentifier, popToRoot: true) case .speakerDomainIdentifier: tabBarController.selectedViewController = scheduleNavigationController // This won't work unless we can get a speaker object for the id. //scheduleNavigator.navigateToSpeakerDetails(speakerId: uniqueIdentifier, popToRoot: true) } } } } func navigateToImFeelingLucky(_ shortcutItem: UIApplicationShortcutItem) { guard let userInfo = shortcutItem.userInfo, let sessionID = userInfo[DeepLinkingConstants.sessionID] as? String else { return } // navigate to session detected in launch shortcut navigateToDeepLink(uniqueIdPath: sessionID) // ... and re-register launch shortcut with a new random session registerImFeelingLuckyShortcut() } @objc func registerImFeelingLuckyShortcut() { if let sessionID = serviceLocator.sessionsDataSource.randomSessionId() { let userInfo = [ DeepLinkingConstants.sessionID: IndexConstants.sessionDomainIdentifier.rawValue + "/" + sessionID ] let icon = UIApplicationShortcutIcon(type: .search) let item = UIApplicationShortcutItem( type: "com.google.iosched.imfeelinglucky", localizedTitle: NSLocalizedString("I'm feeling lucky", comment: "I'm feeling luck Siri shortcut name"), localizedSubtitle: NSLocalizedString("Show a random session", comment: "Describes the function of the I'm feeling lucky shortcut"), icon: icon, userInfo: userInfo as [String: NSSecureCoding] ) UIApplication.shared.shortcutItems = [item] } } } extension AppDelegate { func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if userActivity.activityType == CSSearchableItemActionType { if let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String { Application.sharedInstance.navigateToDeepLink(uniqueIdPath: uniqueIdentifier) } } return true } func handleShortcutItem(shortcutItem: UIApplicationShortcutItem) -> Bool { app.navigateToImFeelingLucky(shortcutItem) return true } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let handledShortCutItem = handleShortcutItem(shortcutItem: shortcutItem) completionHandler(handledShortCutItem) } }
d59ac68d3a25c7ac342d01e75d604672
37.117647
103
0.715021
false
false
false
false
hironytic/Kiretan0
refs/heads/master
Kiretan0Tests/Mock/Model/Utility/MockDataStore.swift
mit
1
// // MockDataStore.swift // Kiretan0Tests // // Copyright (c) 2018 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import XCTest import RxSwift @testable import Kiretan0 class MockDataStore: DataStore { class MockFunctionsForObserveDocument { var typeMap = [String: Any]() func install<E: Entity>(_ mockFunction: MockFunction<(DocumentPath) -> Observable<E?>>) { let typeString = String(describing: E.self) typeMap[typeString] = mockFunction } } class MockFunctionsForObserveCollection { var typeMap = [String: Any]() func install<E: Entity>(_ mockFunction: MockFunction<(DataStoreQuery) -> Observable<CollectionChange<E>>>) { let typeString = String(describing: E.self) typeMap[typeString] = mockFunction } } class Mock { var deletePlaceholder = MockFunction<() -> Any>("MockDataStore.deletePlaceholder") var serverTimestampPlaceholder = MockFunction<() -> Any>("MockDataStore.serverTimestampPlaceholder") var collection = MockFunction<(String) -> CollectionPath>("MockDataStore.collection") var observeDocument = MockFunctionsForObserveDocument() var observeCollection = MockFunctionsForObserveCollection() var write = MockFunction<(@escaping (DocumentWriter) throws -> Void) -> Completable>("MockDataStore.write") init() { deletePlaceholder.setup { return MockDataStorePlaceholder.deletePlaceholder } serverTimestampPlaceholder.setup { return MockDataStorePlaceholder.serverTimestampPlaceholder } collection.setup { return MockCollectionPath(path: "/\($0)")} } } let mock = Mock() var deletePlaceholder: Any { return mock.deletePlaceholder.call() } var serverTimestampPlaceholder: Any { return mock.serverTimestampPlaceholder.call() } func collection(_ collectionID: String) -> CollectionPath { return mock.collection.call(collectionID) } func observeDocument<E: Entity>(at documentPath: DocumentPath) -> Observable<E?> { let typeString = String(describing: E.self) guard let mockFunction = mock.observeDocument.typeMap[typeString] as? MockFunction<(DocumentPath) -> Observable<E?>> else { XCTFail("mock for observeDocument is not installed") fatalError() } return mockFunction.call(documentPath) } func observeCollection<E: Entity>(matches query: DataStoreQuery) -> Observable<CollectionChange<E>> { let typeString = String(describing: E.self) guard let mockFunction = mock.observeCollection.typeMap[typeString] as? MockFunction<(DataStoreQuery) -> Observable<CollectionChange<E>>> else { XCTFail("mock for observeCollection is not installed") fatalError() } return mockFunction.call(query) } func write(block: @escaping (DocumentWriter) throws -> Void) -> Completable { return mock.write.call(block) } } enum MockDataStorePlaceholder { case deletePlaceholder case serverTimestampPlaceholder } class MockDataStoreQuery: DataStoreQuery { class Mock { var whereFieldIsEqualTo = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsEqualTo") var whereFieldIsLessThan = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsLessThan") var whereFieldIsLessThanOrEqualTo = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsLessThanOrEqualTo") var whereFieldIsGreaterThan = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsGreaterThan") var whereFieldIsGreaterThanOrEqualTo = MockFunction<(String, Any) -> DataStoreQuery>("MockDataStoreQuery.whereFieldIsGreaterThanOrEqualTo") var orderBy = MockFunction<(String) -> DataStoreQuery>("MockDataStoreQuery.orderBy") var orderByDescending = MockFunction<(String, Bool) -> DataStoreQuery>("MockDataStoreQuery.orderByDescending") init(path: String) { whereFieldIsEqualTo.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)=={\(value)}") } whereFieldIsLessThan.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)<{\(value)}") } whereFieldIsLessThanOrEqualTo.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)<={\(value)}") } whereFieldIsGreaterThan.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)>{\(value)}") } whereFieldIsGreaterThanOrEqualTo.setup { (field, value) in return MockDataStoreQuery(path: path + "?\(field)>={\(value)}") } orderBy.setup { (field) in return MockDataStoreQuery(path: path + "@\(field):asc") } orderByDescending.setup { (field, isDescending) in let direction = isDescending ? "desc" : "asc" return MockDataStoreQuery(path: path + "@\(field):\(direction)") } } } let mock: Mock let path: String init(path: String = "") { mock = Mock(path: path) self.path = path } func whereField(_ field: String, isEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsEqualTo.call(field, value) } func whereField(_ field: String, isLessThan value: Any) -> DataStoreQuery { return mock.whereFieldIsLessThan.call(field, value) } func whereField(_ field: String, isLessThanOrEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsLessThanOrEqualTo.call(field, value) } func whereField(_ field: String, isGreaterThan value: Any) -> DataStoreQuery { return mock.whereFieldIsGreaterThan.call(field, value) } func whereField(_ field: String, isGreaterThanOrEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsGreaterThanOrEqualTo.call(field, value) } func order(by field: String) -> DataStoreQuery { return mock.orderBy.call(field) } func order(by field: String, descending: Bool) -> DataStoreQuery { return mock.orderByDescending.call(field, descending) } } class MockCollectionPath: CollectionPath { class Mock: MockDataStoreQuery.Mock { var collectionID = MockFunction<() -> String>("MockCollectionPath.collectionID") var document = MockFunction<() -> DocumentPath>("MockCollectionPath.document") var documentForID = MockFunction<(String) -> DocumentPath>("MockCollectionPath.documentForID") override init(path: String) { collectionID.setup { return String(path.split(separator: "/", omittingEmptySubsequences: false).last!) } document.setup { return MockDocumentPath(path: path + "/\(UUID().uuidString)") } documentForID.setup { return MockDocumentPath(path: path + "/\($0)") } super.init(path: path) } } let mock: Mock let path: String init(path: String) { mock = Mock(path: path) self.path = path } func whereField(_ field: String, isEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsEqualTo.call(field, value) } func whereField(_ field: String, isLessThan value: Any) -> DataStoreQuery { return mock.whereFieldIsLessThan.call(field, value) } func whereField(_ field: String, isLessThanOrEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsLessThanOrEqualTo.call(field, value) } func whereField(_ field: String, isGreaterThan value: Any) -> DataStoreQuery { return mock.whereFieldIsGreaterThan.call(field, value) } func whereField(_ field: String, isGreaterThanOrEqualTo value: Any) -> DataStoreQuery { return mock.whereFieldIsGreaterThanOrEqualTo.call(field, value) } func order(by field: String) -> DataStoreQuery { return mock.orderBy.call(field) } func order(by field: String, descending: Bool) -> DataStoreQuery { return mock.orderByDescending.call(field, descending) } var collectionID: String { return mock.collectionID.call() } func document() -> DocumentPath { return mock.document.call() } func document(_ documentID: String) -> DocumentPath { return mock.documentForID.call(documentID) } } class MockDocumentPath: DocumentPath { class Mock { var documentID = MockFunction<() -> String>("MockDocumentPath.documentID") var collection = MockFunction<(String) -> CollectionPath>("MockDocumentPath.collection") init(path: String) { documentID.setup { return String(path.split(separator: "/", omittingEmptySubsequences: false).last!) } collection.setup { return MockCollectionPath(path: path + "/\($0)") } } } let mock: Mock let path: String init(path: String) { mock = Mock(path: path) self.path = path } var documentID: String { return mock.documentID.call() } func collection(_ collectionID: String) -> CollectionPath { return mock.collection.call(collectionID) } } class MockDocumentWriter: DocumentWriter { class Mock { var setDocumentData = MockFunction<([String: Any], DocumentPath) -> Void>("MockDocumentWriter.setDocumentData") var updateDocumentData = MockFunction<([String: Any], DocumentPath) -> Void>("MockDocumentWriter.updateDocumentData") var mergeDocumentData = MockFunction<([String: Any], DocumentPath) -> Void>("MockDocumentWriter.mergeDocumentData") var deleteDocument = MockFunction<(DocumentPath) -> Void>("MockDocumentWriter.deleteDocument") } let mock = Mock() func setDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { mock.setDocumentData.call(documentData, documentPath) } func updateDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { mock.updateDocumentData.call(documentData, documentPath) } func mergeDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { mock.mergeDocumentData.call(documentData, documentPath) } func deleteDocument(at documentPath: DocumentPath) { mock.deleteDocument.call(documentPath) } }
b6b996ca66ff2d754ebefe7c0dce4d8e
43.593023
152
0.68292
false
false
false
false
skyPeat/DoYuLiveStreaming
refs/heads/master
DoYuLiveStreaming/DoYuLiveStreaming/Classes/Home/View/SP_NormalCell.swift
mit
1
// // SP_NormalCell.swift // DoYuLiveStreaming // // Created by tianfeng pan on 17/3/23. // Copyright © 2017年 tianfeng pan. All rights reserved. // import UIKit import Kingfisher class SP_NormalCell: UICollectionViewCell { // 设置属性 @IBOutlet weak var normalImageView: UIImageView! @IBOutlet weak var attentionCount: UIButton! @IBOutlet weak var name: UIButton! @IBOutlet weak var describeLabel: UILabel! var group : SP_AnchorModel?{ didSet{ // 在线人数 guard let group = group else{return} var onlineStr = "" if group.online >= 10000 { onlineStr = "\(Double(group.online) / 10000.0)万人在线" }else{ onlineStr = "\(group.online)人在线" } attentionCount.setTitle(onlineStr, for: .normal) name.setTitle(group.nickname, for: .normal) describeLabel.text = group.room_name guard let iconUrl = URL(string: group.vertical_src) else {return} normalImageView.kf.setImage(with: iconUrl) } } }
d9612a2b1c808ef6073169404a8c8994
29.083333
77
0.602955
false
false
false
false
cuappdev/eatery
refs/heads/master
Eatery/Controllers/Eateries/Campus/CampusEateriesViewController.swift
mit
1
// // CampusEateriesViewController.swift // Eatery // // Created by William Ma on 3/14/19. // Copyright © 2019 CUAppDev. All rights reserved. // import os.log import CoreLocation import UIKit class CampusEateriesViewController: EateriesViewController { private var allEateries: [CampusEatery]? private var preselectedEateryName: String? override func viewDidLoad() { super.viewDidLoad() dataSource = self delegate = self availableFilters = [ .nearest, .north, .west, .central, .swipes, .brb ] queryCampusEateries() } private func queryCampusEateries() { NetworkManager.shared.getCampusEateries { [weak self] (eateries, error) in guard let `self` = self else { return } guard let eateries = eateries else { if let error = error { self.updateState(.failedToLoad(error), animated: true) } return } os_log("Successfully loaded %d campus eateries", eateries.count) self.allEateries = eateries self.updateState(.presenting, animated: true) self.pushPreselectedEateryIfPossible() } } func preselectEatery(withName name: String) { preselectedEateryName = name pushPreselectedEateryIfPossible() } private func pushPreselectedEateryIfPossible() { guard let name = preselectedEateryName else { return } guard let eatery = allEateries?.first(where: { $0.name == name }) else { return } showMenu(of: eatery, animated: false) preselectedEateryName = nil } private func showMenu(of eatery: CampusEatery, animated: Bool) { let menuViewController = CampusMenuViewController(eatery: eatery, userLocation: userLocation) navigationController?.popToRootViewController(animated: animated) navigationController?.pushViewController(menuViewController, animated: animated) let payload: Payload if eatery.eateryType == .dining { payload = CampusDiningCellPressPayload(diningHallName: eatery.displayName) } else { payload = CampusCafeCellPressPayload(cafeName: eatery.displayName) } AppDevAnalytics.shared.logFirebase(payload) } override func filterBar(_ filterBar: FilterBar, filterWasSelected filter: Filter) { switch filter { case .nearest: AppDevAnalytics.shared.logFirebase(NearestFilterPressPayload()) case .north: AppDevAnalytics.shared.logFirebase(NorthFilterPressPayload()) case .west: AppDevAnalytics.shared.logFirebase(WestFilterPressPayload()) case .central: AppDevAnalytics.shared.logFirebase(CentralFilterPressPayload()) case .swipes: AppDevAnalytics.shared.logFirebase(SwipesFilterPressPayload()) case .brb: AppDevAnalytics.shared.logFirebase(BRBFilterPressPayload()) default: break } } } // MARK: - Eateries View Controller Data Source extension CampusEateriesViewController: EateriesViewControllerDataSource { func eateriesViewController(_ evc: EateriesViewController, eateriesToPresentWithSearchText searchText: String, filters: Set<Filter>) -> [Eatery] { guard let eateries = allEateries else { return [] } var filteredEateries = eateries if !searchText.isEmpty { filteredEateries = filter(eateries: filteredEateries, withSearchText: searchText) } filteredEateries = filter(eateries: filteredEateries, withFilters: filters) return filteredEateries } private func filter(eateries: [CampusEatery], withSearchText searchText: String) -> [CampusEatery] { return eateries.filter { eatery in if search(searchText, matches: eatery.name) || eatery.allNicknames.contains(where: { search(searchText, matches: $0) }) { return true } if let area = eatery.area, search(searchText, matches: area.rawValue) { return true } if eatery.diningItems(onDayOf: Date()).contains(where: { search(searchText, matches: $0.name) }) { return true } if let activeEvent = eatery.activeEvent(atExactly: Date()), activeEvent.menu.stringRepresentation.flatMap({ $0.1 }).contains(where: { search(searchText, matches: $0) }) { return true } return false } } private func filter(eateries: [CampusEatery], withFilters filters: Set<Filter>) -> [CampusEatery] { var filteredEateries = eateries filteredEateries = filteredEateries.filter { if filters.contains(.swipes) { return $0.paymentMethods.contains(.swipes) } if filters.contains(.brb) { return $0.paymentMethods.contains(.brb) } return true } if !filters.intersection(Filter.areaFilters).isEmpty { filteredEateries = filteredEateries.filter { guard let area = $0.area else { return false } switch area { case .north: return filters.contains(.north) case .west: return filters.contains(.west) case .central: return filters.contains(.central) } } } return filteredEateries } func eateriesViewController(_ evc: EateriesViewController, sortMethodWithSearchText searchText: String, filters: Set<Filter>) -> EateriesViewController.SortMethod { if filters.contains(.nearest), let userLocation = userLocation { return .nearest(userLocation) } else { return .alphabetical } } func eateriesViewController(_ evc: EateriesViewController, highlightedSearchDescriptionForEatery eatery: Eatery, searchText: String, filters: Set<Filter>) -> NSAttributedString? { guard !searchText.isEmpty, let eatery = eatery as? CampusEatery else { return nil } let string = NSMutableAttributedString() for itemText in eatery.diningItems(onDayOf: Date()).map({ $0.name }) { if let range = matchRange(of: searchText, in: itemText) { string.append(highlighted(text: itemText + "\n", range: range)) } } if let activeEvent = eatery.activeEvent(atExactly: Date()) { for itemText in activeEvent.menu.stringRepresentation.flatMap({ $0.1 }) { if let range = matchRange(of: searchText, in: itemText) { string.append(highlighted(text: itemText + "\n", range: range)) } } } return (string.length == 0) ? nil : string } private func matchRange(of searchText: String, in text: String) -> Range<String.Index>? { return text.range(of: searchText, options: [.caseInsensitive]) } private func search(_ searchText: String, matches text: String) -> Bool { return matchRange(of: searchText, in: text) != nil } private func highlighted(text: String, range: Range<String.Index>) -> NSAttributedString { let string = NSMutableAttributedString(string: text, attributes: [ .foregroundColor : UIColor.gray, .font : UIFont.systemFont(ofSize: 11) ]) string.addAttributes([ .foregroundColor: UIColor.darkGray, .font: UIFont.systemFont(ofSize: 11, weight: .bold) ], range: NSRange(range, in: text)) return string } } // MARK: - Eateries View Controller Delegate extension CampusEateriesViewController: EateriesViewControllerDelegate { func eateriesViewController(_ evc: EateriesViewController, didSelectEatery eatery: Eatery) { guard let campusEatery = eatery as? CampusEatery else { return } showMenu(of: campusEatery, animated: true) } func eateriesViewControllerDidPressRetryButton(_ evc: EateriesViewController) { updateState(.loading, animated: true) // Delay the reload to give the impression that the app is querying Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in self.queryCampusEateries() } } func eateriesViewControllerDidPushMapViewController(_ evc: EateriesViewController) { guard let eateries = allEateries else { return } let mapViewController = MapViewController(eateries: eateries) navigationController?.pushViewController(mapViewController, animated: true) } func eateriesViewControllerDidRefreshEateries(_ evc: EateriesViewController) { updateState(.loading, animated: true) Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in self.queryCampusEateries() } } }
2637012533d8d486490ff659f70e5e02
32.564748
126
0.61226
false
false
false
false
Reedyuk/Charts
refs/heads/Swift-3.0
Charts/Classes/Charts/PieChartView.swift
apache-2.0
6
// // PieChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// View that represents a pie chart. Draws cake like slices. open class PieChartView: PieRadarChartViewBase { /// rect object that represents the bounds of the piechart, needed for drawing the circle private var _circleBox = CGRect() private var _drawXLabelsEnabled = true /// array that holds the width of each pie-slice in degrees private var _drawAngles = [CGFloat]() /// array that holds the absolute angle in degrees of each slice private var _absoluteAngles = [CGFloat]() /// if true, the hole inside the chart will be drawn private var _drawHoleEnabled = true private var _holeColor: NSUIColor? = NSUIColor.white /// if true, the hole will see-through to the inner tips of the slices private var _drawSlicesUnderHoleEnabled = false /// if true, the values inside the piechart are drawn as percent values private var _usePercentValuesEnabled = false /// variable for the text that is drawn in the center of the pie-chart private var _centerAttributedText: NSAttributedString? /// indicates the size of the hole in the center of the piechart /// /// **default**: `0.5` private var _holeRadiusPercent = CGFloat(0.5) private var _transparentCircleColor: NSUIColor? = NSUIColor(white: 1.0, alpha: 105.0/255.0) /// the radius of the transparent circle next to the chart-hole in the center private var _transparentCircleRadiusPercent = CGFloat(0.55) /// if enabled, centertext is drawn private var _drawCenterTextEnabled = true private var _centerTextRadiusPercent: CGFloat = 1.0 /// maximum angle for this pie private var _maxAngle: CGFloat = 360.0 public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal override func initialize() { super.initialize() renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) _xAxis = nil } open override func draw(_ rect: CGRect) { super.draw(rect) if _data === nil { return } let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } renderer!.drawData(context: context) if (valuesToHighlight()) { renderer!.drawHighlighted(context: context, indices: _indicesToHighlight) } renderer!.drawExtras(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) drawDescription(context: context) drawMarkers(context: context) } internal override func calculateOffsets() { super.calculateOffsets() // prevent nullpointer when no data set if _data === nil { return } let radius = diameter / 2.0 let c = self.centerOffsets let shift = (data as? PieChartData)?.dataSet?.selectionShift ?? 0.0 // create the circle box that will contain the pie-chart (the bounds of the pie-chart) _circleBox.origin.x = (c.x - radius) + shift _circleBox.origin.y = (c.y - radius) + shift _circleBox.size.width = diameter - shift * 2.0 _circleBox.size.height = diameter - shift * 2.0 } internal override func calcMinMax() { calcAngles() } open override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { let center = self.centerCircleBox var r = self.radius var off = r / 10.0 * 3.6 if self.drawHoleEnabled { off = (r - (r * self.holeRadiusPercent)) / 2.0 } r -= off // offset to keep things inside the chart let rotationAngle = self.rotationAngle let i = e.xIndex // offset needed to center the drawn text in the slice let offset = drawAngles[i] / 2.0 // calculate the text position let x: CGFloat = (r * cos(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.x) let y: CGFloat = (r * sin(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.y) return CGPoint(x: x, y: y) } /// calculates the needed angles for the chart slices private func calcAngles() { _drawAngles = [CGFloat]() _absoluteAngles = [CGFloat]() guard let data = _data else { return } _drawAngles.reserveCapacity(data.yValCount) _absoluteAngles.reserveCapacity(data.yValCount) let yValueSum = (_data as! PieChartData).yValueSum var dataSets = data.dataSets var cnt = 0 for i in 0 ..< data.dataSetCount { let set = dataSets[i] let entryCount = set.entryCount for j in 0 ..< entryCount { guard let e = set.entryForIndex(j) else { continue } _drawAngles.append(calcAngle(abs(e.value), yValueSum: yValueSum)) if (cnt == 0) { _absoluteAngles.append(_drawAngles[cnt]) } else { _absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt]) } cnt += 1 } } } /// checks if the given index in the given DataSet is set for highlighting or not open func needsHighlight(xIndex: Int, dataSetIndex: Int) -> Bool { // no highlight if (!valuesToHighlight() || dataSetIndex < 0) { return false } for i in 0 ..< _indicesToHighlight.count { // check if the xvalue for the given dataset needs highlight if (_indicesToHighlight[i].xIndex == xIndex && _indicesToHighlight[i].dataSetIndex == dataSetIndex) { return true } } return false } /// calculates the needed angle for a given value private func calcAngle(_ value: Double) -> CGFloat { return calcAngle(value, yValueSum: (_data as! PieChartData).yValueSum) } /// calculates the needed angle for a given value private func calcAngle(_ value: Double, yValueSum: Double) -> CGFloat { return CGFloat(value) / CGFloat(yValueSum) * _maxAngle } /// This will throw an exception, PieChart has no XAxis object. open override var xAxis: ChartXAxis { fatalError("PieChart has no XAxis") } open override func indexForAngle(_ angle: CGFloat) -> Int { // take the current angle of the chart into consideration let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle) for i in 0 ..< _absoluteAngles.count { if (_absoluteAngles[i] > a) { return i } } return -1; // return -1 if no index found } /// - returns: the index of the DataSet this x-index belongs to. open func dataSetIndexForIndex(_ xIndex: Int) -> Int { var dataSets = _data?.dataSets ?? [] for i in 0 ..< dataSets.count { if (dataSets[i].entryForXIndex(xIndex) !== nil) { return i } } return -1 } /// - returns: an integer array of all the different angles the chart slices /// have the angles in the returned array determine how much space (of 360°) /// each slice takes open var drawAngles: [CGFloat] { return _drawAngles } /// - returns: the absolute angles of the different chart slices (where the /// slices end) open var absoluteAngles: [CGFloat] { return _absoluteAngles } /// The color for the hole that is drawn in the center of the PieChart (if enabled). /// /// *Note: Use holeTransparent with holeColor = nil to make the hole transparent.* open var holeColor: NSUIColor? { get { return _holeColor } set { _holeColor = newValue setNeedsDisplay() } } /// if true, the hole will see-through to the inner tips of the slices /// /// **default**: `false` open var drawSlicesUnderHoleEnabled: Bool { get { return _drawSlicesUnderHoleEnabled } set { _drawSlicesUnderHoleEnabled = newValue setNeedsDisplay() } } /// true if the hole in the center of the pie-chart is set to be visible, false if not open var drawHoleEnabled: Bool { get { return _drawHoleEnabled } set { _drawHoleEnabled = newValue setNeedsDisplay() } } /// the text that is displayed in the center of the pie-chart open var centerText: String? { get { return self.centerAttributedText?.string } set { var attrString: NSMutableAttributedString? if newValue == nil { attrString = nil } else { let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.lineBreakMode = NSLineBreakMode.byTruncatingTail paragraphStyle.alignment = .center attrString = NSMutableAttributedString(string: newValue!) attrString?.setAttributes([ NSForegroundColorAttributeName: NSUIColor.black, NSFontAttributeName: NSUIFont.systemFont(ofSize: 12.0), NSParagraphStyleAttributeName: paragraphStyle ], range: NSMakeRange(0, attrString!.length)) } self.centerAttributedText = attrString } } /// the text that is displayed in the center of the pie-chart open var centerAttributedText: NSAttributedString? { get { return _centerAttributedText } set { _centerAttributedText = newValue setNeedsDisplay() } } /// true if drawing the center text is enabled open var drawCenterTextEnabled: Bool { get { return _drawCenterTextEnabled } set { _drawCenterTextEnabled = newValue setNeedsDisplay() } } internal override var requiredLegendOffset: CGFloat { return _legend.font.pointSize * 2.0 } internal override var requiredBaseOffset: CGFloat { return 0.0 } open override var radius: CGFloat { return _circleBox.width / 2.0 } /// - returns: the circlebox, the boundingbox of the pie-chart slices open var circleBox: CGRect { return _circleBox } /// - returns: the center of the circlebox open var centerCircleBox: CGPoint { return CGPoint(x: _circleBox.midX, y: _circleBox.midY) } /// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart) /// /// **default**: 0.5 (50%) (half the pie) open var holeRadiusPercent: CGFloat { get { return _holeRadiusPercent } set { _holeRadiusPercent = newValue setNeedsDisplay() } } /// The color that the transparent-circle should have. /// /// **default**: `nil` open var transparentCircleColor: NSUIColor? { get { return _transparentCircleColor } set { _transparentCircleColor = newValue setNeedsDisplay() } } /// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart) /// /// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default open var transparentCircleRadiusPercent: CGFloat { get { return _transparentCircleRadiusPercent } set { _transparentCircleRadiusPercent = newValue setNeedsDisplay() } } /// set this to true to draw the x-value text into the pie slices open var drawSliceTextEnabled: Bool { get { return _drawXLabelsEnabled } set { _drawXLabelsEnabled = newValue setNeedsDisplay() } } /// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent. open var usePercentValuesEnabled: Bool { get { return _usePercentValuesEnabled } set { _usePercentValuesEnabled = newValue setNeedsDisplay() } } /// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole open var centerTextRadiusPercent: CGFloat { get { return _centerTextRadiusPercent } set { _centerTextRadiusPercent = newValue setNeedsDisplay() } } /// The max angle that is used for calculating the pie-circle. /// 360 means it's a full pie-chart, 180 results in a half-pie-chart. /// **default**: 360.0 open var maxAngle: CGFloat { get { return _maxAngle } set { _maxAngle = newValue if _maxAngle > 360.0 { _maxAngle = 360.0 } if _maxAngle < 90.0 { _maxAngle = 90.0 } } } }
108e03892dfe1a684b08e5ffcdce16f2
26.649541
189
0.555047
false
false
false
false
ThumbWorks/i-meditated
refs/heads/master
Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift
mit
6
// // TakeLast.swift // Rx // // Created by Tomi Koskinen on 25/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class TakeLastSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = TakeLast<ElementType> typealias E = ElementType private let _parent: Parent private var _elements: Queue<ElementType> init(parent: Parent, observer: O) { _parent = parent _elements = Queue<ElementType>(capacity: parent._count + 1) super.init(observer: observer) } func on(_ event: Event<E>) { switch event { case .next(let value): _elements.enqueue(value) if _elements.count > self._parent._count { let _ = _elements.dequeue() } case .error: forwardOn(event) dispose() case .completed: for e in _elements { forwardOn(.next(e)) } forwardOn(.completed) dispose() } } } class TakeLast<Element>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _count: Int init(source: Observable<Element>, count: Int) { if count < 0 { rxFatalError("count can't be negative") } _source = source _count = count } override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { let sink = TakeLastSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } }
c7f7b7c2ce4ee39caba1be3e677d2da0
25.396825
99
0.567649
false
false
false
false
DivineDominion/mac-multiproc-code
refs/heads/master
RelocationManager/AppDelegate.swift
mit
1
// // AppDelegate.swift // RelocationManager // // Created by Christian Tietze on 19/01/15. // Copyright (c) 2015 Christian Tietze. All rights reserved. // import Cocoa import ServiceManagement func createXPCConnection(loginItemName: NSString, error: NSErrorPointer) -> NSXPCConnection? { let mainBundleURL = NSBundle.mainBundle().bundleURL let loginItemDirURL = mainBundleURL.URLByAppendingPathComponent("Contents/Library/LoginItems", isDirectory: true) let loginItemURL = loginItemDirURL.URLByAppendingPathComponent(loginItemName) return createXPCConnection(loginItemURL, error) } /// Constant for 1 as a true Boolean let TRUE: Boolean = 1 as Boolean /// Constant for 0 as a true Boolean let FALSE: Boolean = 0 as Boolean func createXPCConnection(loginItemURL: NSURL, error: NSErrorPointer) -> NSXPCConnection? { let loginItemBundle = NSBundle(URL: loginItemURL) if loginItemBundle == nil { if error != nil { error.memory = NSError(domain:NSPOSIXErrorDomain, code:Int(EINVAL), userInfo: [ NSLocalizedFailureReasonErrorKey: "failed to load bundle", NSURLErrorKey: loginItemURL ]) } return nil } // Lookup the bundle identifier for the login item. // LaunchServices implicitly registers a mach service for the login // item whose name is the name as the login item's bundle identifier. if loginItemBundle!.bundleIdentifier? == nil { if error != nil { error.memory = NSError(domain:NSPOSIXErrorDomain, code:Int(EINVAL), userInfo:[ NSLocalizedFailureReasonErrorKey: "bundle has no identifier", NSURLErrorKey: loginItemURL ]) } return nil } let loginItemBundleId = loginItemBundle!.bundleIdentifier! // The login item's file name must match its bundle Id. let loginItemBaseName = loginItemURL.lastPathComponent!.stringByDeletingPathExtension if loginItemBundleId != loginItemBaseName { if error != nil { let message = NSString(format: "expected bundle identifier \"%@\" for login item \"%@\", got \"%@\"", loginItemBaseName, loginItemURL, loginItemBundleId) error.memory = NSError(domain:NSPOSIXErrorDomain, code:Int(EINVAL), userInfo:[ NSLocalizedFailureReasonErrorKey: "bundle identifier does not match file name", NSLocalizedDescriptionKey: message, NSURLErrorKey: loginItemURL ]) } return nil } // Enable the login item. // This will start it running if it wasn't already running. if SMLoginItemSetEnabled(loginItemBundleId as CFString, TRUE) != TRUE { if error != nil { error.memory = NSError(domain:NSPOSIXErrorDomain, code:Int(EINVAL), userInfo:[ NSLocalizedFailureReasonErrorKey: "SMLoginItemSetEnabled() failed" ]) } return nil } return NSXPCConnection(machServiceName: loginItemBundleId, options: NSXPCConnectionOptions(0)) } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var connection: NSXPCConnection? var helper: ManagesBoxesAndItems? func applicationDidFinishLaunching(aNotification: NSNotification) { var error: NSError? connect(&error) if (connection == nil) { NSLog("conn failed %@", error!.description) return } connection!.remoteObjectInterface = NSXPCInterface(`protocol`: ManagesBoxesAndItems.self) // connection!.exportedInterface = NSXPCInterface(`protocol`: UsesBoxesAndItems.self) // connection!.exportedObject = self connection!.invalidationHandler = { NSLog("invalidated") } connection!.interruptionHandler = { NSLog("interrupted") } connection!.resume() // Get a proxy DecisionAgent object for the connection. helper = connection!.remoteObjectProxyWithErrorHandler() { err in // This block is run when an error occurs communicating with // the launch item service. This will not be invoked on the // main queue, so re-schedule a block on the main queue to // update the U.I. dispatch_async(dispatch_get_main_queue()) { NSLog("Failed to query oracle: %@\n\n", err.description) } } as? ManagesBoxesAndItems if helper == nil { NSLog("No helper") } } func connect(error: NSErrorPointer) { connection = createXPCConnection("FRMDA3XRGC.de.christiantietze.relocman.Service.app", error) } func windowWillClose(notification: NSNotification) { NSApplication.sharedApplication().terminate(self) } func updateTicker(tick: Int) { NSLog("Tick #\(tick)") } func applicationWillTerminate(aNotification: NSNotification) { //helper = nil connection?.invalidate() } func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { return .TerminateNow } }
2ab635d67b328937ce4b20ef9a284444
35.248276
165
0.651446
false
false
false
false
openHPI/xikolo-ios
refs/heads/dev
Common/Data/Model/PlatformEvent.swift
gpl-3.0
1
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import CoreData import Stockpile final class PlatformEvent: NSManagedObject { @NSManaged var id: String @NSManaged var createdAt: Date? @NSManaged var preview: String? @NSManaged var title: String? @NSManaged var type: String? @NSManaged var course: Course? @nonobjc public class func fetchRequest() -> NSFetchRequest<PlatformEvent> { return NSFetchRequest<PlatformEvent>(entityName: "PlatformEvent") } } extension PlatformEvent: JSONAPIPullable { static var type: String { return "platform-events" } public func update(from object: ResourceData, with context: SynchronizationContext) throws { let attributes = try object.value(for: "attributes") as JSON self.title = try attributes.value(for: "title") self.createdAt = try attributes.value(for: "created_at") self.preview = try attributes.value(for: "preview") self.type = try attributes.value(for: "type") let relationships = try object.value(for: "relationships") as JSON try self.updateRelationship(forKeyPath: \Self.course, forKey: "course", fromObject: relationships, with: context) } }
e75ef44c7cd20222552af6b28a3f68f4
30
121
0.692368
false
false
false
false
Erin-Mounts/BridgeAppSDK
refs/heads/master
BridgeAppSDK/Localization.swift
bsd-3-clause
1
// // Localization.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit class Localization: NSObject { static var localeBundle = { return NSBundle.init(forClass: Localization.classForCoder()) }() static func localizedString(key: String) -> String { var str = NSLocalizedString(key, tableName: nil, bundle: localeBundle, value: key, comment: "") if (str == key) { if let defaultStr = listOfAllLocalizedStrings[key] { str = defaultStr } } return str } // List of the strings used in this module. This func is never called but is included to allow running // the localization macro static var listOfAllLocalizedStrings: [String : String] = { return [ "SBA_CONSENT_TITLE" : NSLocalizedString("SBA_CONSENT_TITLE", tableName: nil, bundle: localeBundle, value: "Consent", comment: "Consent title"), "SBA_CONSENT_SIGNATURE_CONTENT" : NSLocalizedString("SBA_CONSENT_SIGNATURE_CONTENT", tableName: nil, bundle: localeBundle, value:"By agreeing you confirm that you read the consent and that you wish to take part in this research study.", comment:"Consent signature page content"), "SBA_CONSENT_PERSON_TITLE" : NSLocalizedString("SBA_CONSENT_PERSON_TITLE", tableName: nil, bundle: localeBundle, value: "Participant", comment: "Title for the person participating in the study"), ] }() }
b70f9b19acd995e24799699a670a99b2
49.112903
283
0.728677
false
false
false
false
KrishMunot/swift
refs/heads/master
test/Prototypes/TextFormatting.swift
apache-2.0
5
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // Text Formatting Prototype // // This file demonstrates the concepts proposed in TextFormatting.rst // FIXME: Workaround for <rdar://problem/14011860> SubTLF: Default // implementations in protocols. infix operator ~> { precedence 255 } /// \brief A thing into which we can stream text protocol XOutputStream { mutating func append(_ text: String) } /// \brief Strings are XOutputStreams extension String: XOutputStream { mutating func append(_ text: String) { self += text } } /// \brief A thing that can be written to an XOutputStream protocol XStreamable { func writeTo<Target: XOutputStream>(_ target: inout Target) } /// \brief A thing that can be printed in the REPL and the Debugger /// /// Everything compiler-magically conforms to this protocol. To /// change the debug representation for a type, you don't need to /// declare conformance: simply give the type a debugFormat(). protocol XDebugPrintable { associatedtype DebugRepresentation : XStreamable // = String /// \brief Produce a textual representation for the REPL and /// Debugger. /// /// Because String is a XStreamable, your implementation of /// debugRepresentation can just return a String. If you want to write /// directly to the XOutputStream for efficiency reasons, /// (e.g. if your representation is huge), you can return a custom /// DebugRepresentation type. /// /// NOTE: producing a representation that can be consumed by the /// REPL to produce an equivalent object is strongly encouraged /// where possible! For example, String.debugFormat() produces a /// representation containing quotes, where special characters are /// escaped, etc. A struct Point { var x, y: Int } might be /// represented as "Point(x: 3, y: 5)". func debugFormat() -> DebugRepresentation } /// \brief Strings are XStreamable extension String : XStreamable { func writeTo<Target: XOutputStream>(_ target: inout Target) { target.append(self) } } // FIXME: Should be a method of XDebugPrintable once // <rdar://problem/14692224> (Default Implementations in Protocols) is // handled func toDebugString <T:XDebugPrintable> (_ x: T) -> String { var result = "" x.debugFormat().writeTo(&result) return result } // FIXME: The following should be a method of XPrintable once // <rdar://problem/14692224> (Default Implementations in Protocols) is // handled struct __PrintedFormat {} func format() -> __PrintedFormat { return __PrintedFormat() } func ~> <T:XDebugPrintable> (x: T, _: __PrintedFormat) -> T.DebugRepresentation { return x.debugFormat() } /// \brief A thing that can be xprint()ed and toString()ed. /// /// Conformance to XPrintable is explicit, but if you want to use the /// debugFormat() results for your type's format(), all you need /// to do is declare conformance to XPrintable, and there's nothing to /// implement. protocol XPrintable: XDebugPrintable { associatedtype PrintRepresentation: XStreamable = DebugRepresentation /// \brief produce a "pretty" textual representation that can be /// distinct from the debug format. For example, /// String.printRepresentation returns the string itself, without quoting. /// /// In general you can return a String here, but if you need more /// control, we strongly recommend returning a custom Representation /// type, e.g. a nested struct of your type. If you're lazy, you /// can conform to XStreamable directly and just implement its /// write() func. func ~> (x: Self, _: __PrintedFormat) -> PrintRepresentation } // FIXME: The following should be a method of XPrintable once // <rdar://problem/14692224> (Default Implementations in Protocols) is // handled /// \brief Simply convert to String /// /// Don't reimplement this: the default implementation always works. /// If you must reimplement toString(), make sure its results are /// consistent with those of format() (i.e. you shouldn't /// change the behavior). func toString<T: XPrintable>(_ x: T) -> String { var result = "" (x~>format()).writeTo(&result) return result } // \brief Streamer for the debug representation of String. When an // EscapedStringFormat is written to a XOutputStream, it adds // surrounding quotes and escapes special characters. struct EscapedStringFormat : XStreamable { init(_ s: String) { self._value = s } func writeTo<Target: XOutputStream>(_ target: inout Target) { target.append("\"") for c in _value.unicodeScalars { target.append(c.escaped(asASCII: true)) } target.append("\"") } var _value: String } // FIXME: In theory, this shouldn't be needed extension String: XDebugPrintable {} extension String : XPrintable { func debugFormat() -> EscapedStringFormat { return EscapedStringFormat(self) } func format() -> String { return self } } /// \brief An integral type that can be printed protocol XPrintableInteger : IntegerLiteralConvertible, Comparable, SignedNumber, XPrintable { func %(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self // FIXME: Stand-in for constructor pending <rdar://problem/13695680> // (Constructor requirements in protocols) static func fromInt(_ x: Int) -> Self func toInt() -> Int } extension Int : XDebugPrintable { func debugFormat() -> String { return String(self) } } extension Int : XPrintableInteger { static func fromInt(_ x: Int) -> Int { return x } func toInt() -> Int { return self } func getValue() -> Int { return self } } struct _formatArgs { var radix: Int, fill: String, width: Int } func format(radix radix: Int = 10, fill: String = " ", width: Int = 0) -> _formatArgs { return _formatArgs(radix: radix, fill: fill, width: width) } // FIXME: this function was a member of RadixFormat, but // <rdar://problem/15525229> (SIL verification failed: operand of // 'apply' doesn't match function input type) changed all that. func _writePositive<T:XPrintableInteger, S: XOutputStream>( _ value: T, _ stream: inout S, _ args: _formatArgs) -> Int { if value == 0 { return 0 } var radix: T = T.fromInt(args.radix) var rest: T = value / radix var nDigits = _writePositive(rest, &stream, args) var digit = UInt32((value % radix).toInt()) var baseCharOrd : UInt32 = digit <= 9 ? UnicodeScalar("0").value : UnicodeScalar("A").value - 10 stream.append(String(UnicodeScalar(baseCharOrd + digit))) return nDigits + 1 } // FIXME: this function was a member of RadixFormat, but // <rdar://problem/15525229> (SIL verification failed: operand of // 'apply' doesn't match function input type) changed all that. func _writeSigned<T:XPrintableInteger, S: XOutputStream>( _ value: T, _ target: inout S, _ args: _formatArgs ) { var width = 0 var result = "" if value == 0 { result = "0" width += 1 } else { var absVal = abs(value) if (value < 0) { target.append("-") width += 1 } width += _writePositive(absVal, &result, args) } while width < args.width { width += 1 target.append(args.fill) } target.append(result) } struct RadixFormat<T: XPrintableInteger> : XStreamable { init(value: T, args: _formatArgs) { self.value = value self.args = args } func writeTo<S: XOutputStream>(_ target: inout S) { _writeSigned(value, &target, args) } typealias DebugRepresentation = String func debugFormat() -> String { return "RadixFormat(" + toDebugString(value) + ", " + toDebugString(args.radix) + ")" } var value: T var args: _formatArgs } func ~> <T:XPrintableInteger> (x: T, _: __PrintedFormat) -> RadixFormat<T> { return RadixFormat(value: x, args: format()) } func ~> <T:XPrintableInteger> (x: T, args: _formatArgs) -> RadixFormat<T> { return RadixFormat(value: x, args: args) } // ========== // // xprint and xprintln // struct StdoutStream : XOutputStream { func append(_ text: String) { Swift.print(text, terminator: "") } // debugging only func dump() -> String { return "<StdoutStream>" } } func xprint<Target: XOutputStream, T: XStreamable>(_ target: inout Target, _ x: T) { x.writeTo(&target) } func xprint<Target: XOutputStream, T: XPrintable>(_ target: inout Target, _ x: T) { xprint(&target, x~>format()) } func xprint<T: XPrintable>(_ x: T) { var target = StdoutStream() xprint(&target, x) } func xprint<T: XStreamable>(_ x: T) { var target = StdoutStream() xprint(&target, x) } func xprintln<Target: XOutputStream, T: XPrintable>(_ target: inout Target, _ x: T) { xprint(&target, x) target.append("\n") } func xprintln<Target: XOutputStream, T: XStreamable>(_ target: inout Target, _ x: T) { xprint(&target, x) target.append("\n") } func xprintln<T: XPrintable>(_ x: T) { var target = StdoutStream() xprintln(&target, x) } func xprintln<T: XStreamable>(_ x: T) { var target = StdoutStream() xprintln(&target, x) } func xprintln(_ x: String) { var target = StdoutStream() x.writeTo(&target) "\n".writeTo(&target) } extension String { init <T: XStreamable>(_ x: T) { self = "" xprint(&self, x) } } func toPrettyString<T: XStreamable>(_ x: T) -> String { var result = "|" xprint(&result, x) result += "|" return result } // =========== var x = "fubar\n\tbaz" xprintln(x) // CHECK: fubar // CHECK-NEXT: baz xprintln(toDebugString(x)) // CHECK-NEXT: "fubar\n\tbaz" xprintln(toPrettyString(424242~>format(radix:16, width:8))) // CHECK-NEXT: | 67932| var zero = "0" xprintln(toPrettyString(-434343~>format(width:8, fill:zero))) // CHECK-NEXT: |-0434343| xprintln(toPrettyString(-42~>format(radix:13, width:8))) // CHECK-NEXT: |- 33| xprintln(0x1EADBEEF~>format(radix:16)) // CHECK-NEXT: 1EADBEEF // FIXME: rdar://16168414 this doesn't work in 32-bit // xprintln(0xDEADBEEF~>format(radix:16)) // CHECK-NEXT-not: DEADBEEF
06f015b1bccf9feed0aee22af4d9dbfb
26.366391
94
0.677773
false
false
false
false
tominated/Quake-3-BSP-Renderer
refs/heads/master
Quake 3 BSP Renderer/ShaderGenerator.swift
mit
1
// // ShaderGenerator.swift // Quake 3 BSP Renderer // // Created by Thomas Brunoli on 04/04/2018. // Copyright © 2018 Thomas Brunoli. All rights reserved. // import Foundation import Metal class ShaderGenerator { let shader: Q3Shader let stage: Q3ShaderStage static private let vertexInDef = """ struct VertexIn { float4 position [[attribute(0)]]; float4 normal [[attribute(1)]]; float4 color [[attribute(2)]]; float2 textureCoord [[attribute(3)]]; float2 lightmapCoord [[attribute(4)]]; }; """ static private let vertexOutDef = """ struct VertexOut { float4 position [[position]]; float4 normal; float4 color; float2 textureCoord; }; """ static private let uniformsDef = """ struct Uniforms { float time; float4x4 viewMatrix; float4x4 projectionMatrix; }; """ static private let vertexFunctionDef = """ vertex VertexOut renderVert(VertexIn in [[stage_in]], constant Uniforms &uniforms [[buffer(1)]], uint vid [[vertex_id]]) """ static private let fragmentFunctionDef = """ fragment half4 renderFrag(VertexOut in [[stage_in]], constant Uniforms &uniforms [[buffer(0)]], texture2d<half> tex [[texture(0)]], sampler smp [[sampler(0)]]) """ init(shader: Q3Shader, stage: Q3ShaderStage) { self.shader = shader self.stage = stage } public func buildShader() -> String { return """ #include <metal_stdlib> using namespace metal; \(ShaderGenerator.vertexInDef) \(ShaderGenerator.vertexOutDef) \(ShaderGenerator.uniformsDef) \(buildVertexFunction()) \(buildFragmentFunction()) """ } private func buildVertexFunction() -> String { return """ \(ShaderGenerator.vertexFunctionDef) { VertexOut out; float3 position = in.position.xyz; \(buildVertexDeforms()) float4 worldPosition = uniforms.viewMatrix * float4(position, 1.0); float2 textureCoord = \(buildTextureCoordinateGenerator()); \(buildTextureCoordinateMods()) out.position = uniforms.projectionMatrix * worldPosition; out.normal = float4(in.normal); out.color = float4(in.color); out.textureCoord = textureCoord; return out; } """ } private func buildFragmentFunction() -> String { return """ \(ShaderGenerator.fragmentFunctionDef) { half4 diffuse = tex.sample(smp, in.textureCoord); \(buildRGBGenerator()) \(buildAlphaGenerator()) \(buildAlphaFunction()) return half4(color.rgb, alpha); } """ } private func buildTextureCoordinateGenerator() -> String { switch stage.textureCoordinateGenerator { case .lightmap: return "in.lightmapCoord" default: return "in.textureCoord" } } private func buildRGBGenerator() -> String { switch stage.rgbGenerator { case .vertex: return "half3 color = half3(diffuse.rgb * half3(in.color.rgb));" case .wave(let waveform): return """ \(buildWaveform(waveform, name: "rgbWave")) half3 color = diffuse.rgb * rgbWave; """ default: return "half3 color = half3(diffuse.rgb);" } } private func buildAlphaGenerator() -> String { switch stage.alphaGenerator { case .constant(let a): return "float alpha = \(a)F;" case .wave(let waveform): return buildWaveform(waveform, name: "alpha") default: return "float alpha = diffuse.a;" } } private func buildAlphaFunction() -> String { guard let alphaFunction = stage.alphaFunction else { return "" } var condition = "" switch alphaFunction { case .gt0: condition = "<= 0F" case .lt128: condition = ">= 0.5F" case .ge128: condition = "< 0.5F" } return "if (alpha \(condition)) discard_fragment();" } private func buildWaveform(_ waveform: Waveform, name: String) -> String { switch waveform.function { case .sawtooth: return """ float \(name) = \(waveform.base)F + fract(\(waveform.phase)F + uniforms.time * \(waveform.frequency)F) * \(waveform.amplitude)F; """ case .sin: return """ float \(name) = \(waveform.base)F + sin((\(waveform.phase)F + uniforms.time * \(waveform.frequency)F) * M_PI_F * 2) * \(waveform.amplitude)F; """ case .square: return """ float \(name) = \(waveform.base)F + ((((int(floor((\(waveform.phase)F + uniforms.time * \(waveform.frequency)F) * 2.0) + 1.0)) % 2) * 2.0) - 1.0) * \(waveform.amplitude)F; """ case .triangle: return """ float \(name) = \(waveform.base)F + abs(2.0 * fract((\(waveform.phase)F + uniforms.time * \(waveform.frequency)F)) - 1.0) * \(waveform.amplitude)F; """ default: return "float \(name) = \(waveform.base)F;" } } private func buildVertexDeforms() -> String { var deforms = "" for vertexDeform in shader.vertexDeforms { switch vertexDeform { case .wave(let spread, let waveform): deforms.append(""" { \(buildWaveform(waveform, name: "deformWave")) float offset = (in.position.x + in.position.y + in.position.z) * \(spread)F; position *= in.normal.xyz * deformWave; } """) default: continue } } return deforms } private func buildTextureCoordinateMods() -> String { var texCoordMods = "" for texCoordMod in stage.textureCoordinateMods { switch texCoordMod { case .rotate(let degrees): texCoordMods.append(""" { float r = \(degrees)F * uniforms.time; textureCoord -= float2(0.5, 0.5); textureCoord = float2( textureCoord[0] * cos(r) - textureCoord[1] * sin(r), textureCoord[1] * cos(r) + textureCoord[0] * sin(r) ); textureCoord += float2(0.5, 0.5); } """) case .scale(let x, let y): texCoordMods.append(""" { textureCoord *= float2(\(x)F, \(y)F); } """) case .scroll(let x, let y): texCoordMods.append(""" { textureCoord += float2(\(x)F * uniforms.time, \(y)F * uniforms.time); } """) case .stretch(let waveform): texCoordMods.append(""" { \(buildWaveform(waveform, name: "stretchWave")) stretchWave = 1.0F / stretchWave; textureCoord *= stretchWave; textureCoord += float2(0.5F - (0.5F * stretchWave), 0.5F - (0.5F * stretchWave)); } """) default: continue } } return texCoordMods } }
908e57165017ff7363d240c0bb067873
27.858182
127
0.496094
false
false
false
false
nakau1/NerobluCore
refs/heads/master
NerobluCore/NBCoreGraphic.swift
apache-2.0
1
// ============================================================================= // NerobluCore // Copyright (C) NeroBlu. All rights reserved. // ============================================================================= import UIKit /// CGRectZeroの省略形 public let cr0 = CGRectZero /// CGPointZeroの省略形 public let cp0 = CGPointZero /// CGSizeZeroの省略形 public let cs0 = CGSizeZero /// CGRectMakeのラッパ関数 /// - parameter x: X座標 /// - parameter y: Y座標 /// - parameter w: 幅 /// - parameter h: 高さ /// - returns: CGRect構造体 public func cr(x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) -> CGRect { return CGRectMake(x, y, w, h) } /// サイズのみを指定したCGRect構造体を取得(originはCGPointZero) /// - parameter w: 幅 /// - parameter h: 高さ /// - returns: CGRect構造体 public func cr(w: CGFloat, _ h: CGFloat) -> CGRect { return cr(0, 0, w, h) } /// CGPointMakeのラッパ関数 /// - parameter x: X座標 /// - parameter y: Y座標 /// - returns: CGPoint構造体 public func cp(x: CGFloat, _ y: CGFloat) -> CGPoint { return CGPointMake(x, y) } /// CGSizeMakeのラッパ関数 /// - parameter w: 幅 /// - parameter h: 高さ /// - returns: CGSize構造体 public func cs(w: CGFloat, _ h: CGFloat) -> CGSize { return CGSizeMake(w, h) } /// CGRectGetWidthのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: 幅 public func crW(r: CGRect) -> CGFloat { return CGRectGetWidth(r) } /// CGRectGetHeightのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: 高さ public func crH(r: CGRect) -> CGFloat { return CGRectGetHeight(r) } /// CGRectGetMinXのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: X座標 public func crX(r: CGRect) -> CGFloat { return CGRectGetMinX(r) } /// CGRectGetMinYのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: Y座標 public func crY(r: CGRect) -> CGFloat { return CGRectGetMinY(r) } /// CGRectGetMinYのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: 上端のY座標 public func crT(r: CGRect) -> CGFloat { return CGRectGetMinY(r) } /// CGRectGetMinXのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: 左端のX座標 public func crL(r: CGRect) -> CGFloat { return CGRectGetMinX(r) } /// CGRectGetMaxXのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: 右端のX座標 public func crR(r: CGRect) -> CGFloat { return CGRectGetMaxX(r) } /// CGRectGetMaxXのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: 下端のY座標 public func crB(r: CGRect) -> CGFloat { return CGRectGetMaxY(r) } /// CGRectGetMidXのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: 水平方向の中央X座標 public func crMX(r: CGRect) -> CGFloat { return CGRectGetMidX(r) } /// CGRectGetMidYのラッパ関数 /// - parameter r: CGRect構造体 /// - returns: 垂直方向の中央Y座標 public func crMY(r: CGRect) -> CGFloat { return CGRectGetMidY(r) } /// CGRectZeroを取得する /// - returns: CGRect構造体 public func crZ() -> CGRect { return CGRectZero } /// CGPointZeroを取得する /// - returns: CGPoint構造体 public func cpZ() -> CGPoint { return CGPointZero } /// CGSizeZeroを取得する /// - returns: CGSize構造体 public func csZ() -> CGSize { return CGSizeZero } /// サイズのみを指定したCGRect構造体を取得(originはCGPointZero) /// - parameter s: CGSize構造体 /// - returns: CGRect構造体 public func crS(s: CGSize) -> CGRect { return cr(0, 0, s.width, s.height); } /// 座標のみを指定したCGRect構造体を取得(sizeはCGSizeZero) /// - parameter p: CGPoint構造体 /// - returns: CGRect構造体 public func crP(p: CGPoint) -> CGRect { return cr(p.x, p.y, 0, 0); } /// CGRect構造体のセンター位置を取得 /// - parameter r: CGRect構造体 /// - returns: CGPoint構造体 public func crC(r: CGRect) -> CGPoint { let x: CGFloat = crL(r) + (crW(r) / 2.0) let y: CGFloat = crT(r) + (crH(r) / 2.0) return cp(x, y); } /// CGPoint構造体のY座標とY座標を入れ替えた座標を取得 /// - parameter p: CGPoint構造体 /// - returns: CGPoint構造体 public func cpYX(p: CGPoint) -> CGPoint { return cp(p.y, p.x); } /// CGSize構造体の幅と高さを入れ替えたサイズを取得 /// - parameter s: CGSize構造体 /// - returns: CGSize構造体 public func csHW(s: CGSize) -> CGSize { return cs(s.height, s.width); }
33f7d50832596814149679146026b45b
26.28777
112
0.641445
false
false
false
false
yankodimitrov/SignalKit
refs/heads/master
SignalKitTests/Fakes/MockCollectionView.swift
mit
1
// // MockCollectionView.swift // SignalKit // // Created by Yanko Dimitrov on 3/7/16. // Copyright © 2016 Yanko Dimitrov. All rights reserved. // import UIKit class MockCollectionView: UICollectionView { var isReloadDataCalled = false var isInsertSectionsCalled = false var isReloadSectionsCalled = false var isDeleteSectionsCalled = false var isInsertItemsCalled = false var isReloadItemsCalled = false var isDeleteItemsCalled = false var isPerformBarchUpdatesCalled = false convenience init() { let layout = UICollectionViewFlowLayout() self.init(frame: CGRectZero, collectionViewLayout: layout) } override func reloadData() { isReloadDataCalled = true } override func insertSections(sections: NSIndexSet) { isInsertSectionsCalled = true } override func reloadSections(sections: NSIndexSet) { isReloadSectionsCalled = true } override func deleteSections(sections: NSIndexSet) { isDeleteSectionsCalled = true } override func insertItemsAtIndexPaths(indexPaths: [NSIndexPath]) { isInsertItemsCalled = true } override func reloadItemsAtIndexPaths(indexPaths: [NSIndexPath]) { isReloadItemsCalled = true } override func deleteItemsAtIndexPaths(indexPaths: [NSIndexPath]) { isDeleteItemsCalled = true } override func performBatchUpdates(updates: (() -> Void)?, completion: ((Bool) -> Void)?) { updates?() isPerformBarchUpdatesCalled = true } }
30d7a1dd9ca65f1149e2a23c3ab2392f
23.347826
94
0.63869
false
false
false
false
Dwarven/ShadowsocksX-NG
refs/heads/develop
Example/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift
apache-2.0
3
// // UICollectionView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import RxSwift import UIKit // Items extension Reactive where Base: UICollectionView { /** Binds sequences of elements to collection view items. - parameter source: Observable sequence of items. - parameter cellFactory: Transform between sequence elements and view cells. - returns: Disposable object that can be used to unbind. Example let items = Observable.just([ 1, 2, 3 ]) items .bind(to: collectionView.rx.items) { (collectionView, row, element) in let indexPath = IndexPath(row: row, section: 0) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell cell.value?.text = "\(element) @ \(row)" return cell } .disposed(by: disposeBag) */ public func items<S: Sequence, O: ObservableType> (_ source: O) -> (_ cellFactory: @escaping (UICollectionView, Int, S.Iterator.Element) -> UICollectionViewCell) -> Disposable where O.E == S { return { cellFactory in let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory) return self.items(dataSource: dataSource)(source) } } /** Binds sequences of elements to collection view items. - parameter cellIdentifier: Identifier used to dequeue cells. - parameter source: Observable sequence of items. - parameter configureCell: Transform between sequence elements and view cells. - parameter cellType: Type of table view cell. - returns: Disposable object that can be used to unbind. Example let items = Observable.just([ 1, 2, 3 ]) items .bind(to: collectionView.rx.items(cellIdentifier: "Cell", cellType: NumberCell.self)) { (row, element, cell) in cell.value?.text = "\(element) @ \(row)" } .disposed(by: disposeBag) */ public func items<S: Sequence, Cell: UICollectionViewCell, O : ObservableType> (cellIdentifier: String, cellType: Cell.Type = Cell.self) -> (_ source: O) -> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void) -> Disposable where O.E == S { return { source in return { configureCell in let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S> { cv, i, item in let indexPath = IndexPath(item: i, section: 0) let cell = cv.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! Cell configureCell(i, item, cell) return cell } return self.items(dataSource: dataSource)(source) } } } /** Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation. - parameter dataSource: Data source used to transform elements to view cells. - parameter source: Observable sequence of items. - returns: Disposable object that can be used to unbind. Example let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, Double>>() let items = Observable.just([ SectionModel(model: "First section", items: [ 1.0, 2.0, 3.0 ]), SectionModel(model: "Second section", items: [ 1.0, 2.0, 3.0 ]), SectionModel(model: "Third section", items: [ 1.0, 2.0, 3.0 ]) ]) dataSource.configureCell = { (dataSource, cv, indexPath, element) in let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell cell.value?.text = "\(element) @ row \(indexPath.row)" return cell } items .bind(to: collectionView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) */ public func items< DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, O: ObservableType> (dataSource: DataSource) -> (_ source: O) -> Disposable where DataSource.Element == O.E { return { source in // This is called for sideeffects only, and to make sure delegate proxy is in place when // data source is being bound. // This is needed because theoretically the data source subscription itself might // call `self.rx.delegate`. If that happens, it might cause weird side effects since // setting data source will set delegate, and UICollectionView might get into a weird state. // Therefore it's better to set delegate proxy first, just to be sure. _ = self.delegate // Strong reference is needed because data source is in use until result subscription is disposed return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak collectionView = self.base] (_: RxCollectionViewDataSourceProxy, event) -> Void in guard let collectionView = collectionView else { return } dataSource.collectionView(collectionView, observedEvent: event) } } } } extension Reactive where Base: UICollectionView { public typealias DisplayCollectionViewCellEvent = (cell: UICollectionViewCell, at: IndexPath) public typealias DisplayCollectionViewSupplementaryViewEvent = (supplementaryView: UICollectionReusableView, elementKind: String, at: IndexPath) /// Reactive wrapper for `dataSource`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var dataSource: DelegateProxy<UICollectionView, UICollectionViewDataSource> { return RxCollectionViewDataSourceProxy.proxy(for: base) } /// Installs data source as forwarding delegate on `rx.dataSource`. /// Data source won't be retained. /// /// It enables using normal delegate mechanism with reactive delegate mechanism. /// /// - parameter dataSource: Data source object. /// - returns: Disposable object that can be used to unbind the data source. public func setDataSource(_ dataSource: UICollectionViewDataSource) -> Disposable { return RxCollectionViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) } /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. public var itemSelected: ControlEvent<IndexPath> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didSelectItemAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didDeselectItemAtIndexPath:)`. public var itemDeselected: ControlEvent<IndexPath> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didDeselectItemAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didHighlightItemAt:)`. public var itemHighlighted: ControlEvent<IndexPath> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didHighlightItemAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didUnhighlightItemAt:)`. public var itemUnhighlighted: ControlEvent<IndexPath> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUnhighlightItemAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView:willDisplay:forItemAt:`. public var willDisplayCell: ControlEvent<DisplayCollectionViewCellEvent> { let source: Observable<DisplayCollectionViewCellEvent> = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplay:forItemAt:))) .map { a in return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:willDisplaySupplementaryView:forElementKind:at:)`. public var willDisplaySupplementaryView: ControlEvent<DisplayCollectionViewSupplementaryViewEvent> { let source: Observable<DisplayCollectionViewSupplementaryViewEvent> = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplaySupplementaryView:forElementKind:at:))) .map { a in return (try castOrThrow(UICollectionReusableView.self, a[1]), try castOrThrow(String.self, a[2]), try castOrThrow(IndexPath.self, a[3])) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView:didEndDisplaying:forItemAt:`. public var didEndDisplayingCell: ControlEvent<DisplayCollectionViewCellEvent> { let source: Observable<DisplayCollectionViewCellEvent> = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplaying:forItemAt:))) .map { a in return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:)`. public var didEndDisplayingSupplementaryView: ControlEvent<DisplayCollectionViewSupplementaryViewEvent> { let source: Observable<DisplayCollectionViewSupplementaryViewEvent> = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:))) .map { a in return (try castOrThrow(UICollectionReusableView.self, a[1]), try castOrThrow(String.self, a[2]), try castOrThrow(IndexPath.self, a[3])) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. /// /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, /// or any other data source conforming to `SectionedViewDataSourceType` protocol. /// /// ``` /// collectionView.rx.modelSelected(MyModel.self) /// .map { ... /// ``` public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = itemSelected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable<T> in guard let view = view else { return Observable.empty() } return Observable.just(try view.rx.model(at: indexPath)) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. /// /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, /// or any other data source conforming to `SectionedViewDataSourceType` protocol. /// /// ``` /// collectionView.rx.modelDeselected(MyModel.self) /// .map { ... /// ``` public func modelDeselected<T>(_ modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = itemDeselected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable<T> in guard let view = view else { return Observable.empty() } return Observable.just(try view.rx.model(at: indexPath)) } return ControlEvent(events: source) } /// Synchronous helper method for retrieving a model at indexPath through a reactive data source public func model<T>(at indexPath: IndexPath) throws -> T { let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemsWith*` methods was used.") let element = try dataSource.model(at: indexPath) return try castOrThrow(T.self, element) } } @available(iOS 10.0, tvOS 10.0, *) extension Reactive where Base: UICollectionView { /// Reactive wrapper for `prefetchDataSource`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var prefetchDataSource: DelegateProxy<UICollectionView, UICollectionViewDataSourcePrefetching> { return RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base) } /** Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`. Prefetch data source won't be retained. It enables using normal delegate mechanism with reactive delegate mechanism. - parameter prefetchDataSource: Prefetch data source object. - returns: Disposable object that can be used to unbind the data source. */ public func setPrefetchDataSource(_ prefetchDataSource: UICollectionViewDataSourcePrefetching) -> Disposable { return RxCollectionViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base) } /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:prefetchItemsAt:)`. public var prefetchItems: ControlEvent<[IndexPath]> { let source = RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base).prefetchItemsPublishSubject return ControlEvent(events: source) } /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:cancelPrefetchingForItemsAt:)`. public var cancelPrefetchingForItems: ControlEvent<[IndexPath]> { let source = prefetchDataSource.methodInvoked(#selector(UICollectionViewDataSourcePrefetching.collectionView(_:cancelPrefetchingForItemsAt:))) .map { a in return try castOrThrow(Array<IndexPath>.self, a[1]) } return ControlEvent(events: source) } } #endif #if os(tvOS) extension Reactive where Base: UICollectionView { /// Reactive wrapper for `delegate` message `collectionView(_:didUpdateFocusInContext:withAnimationCoordinator:)`. public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUpdateFocusIn:with:))) .map { a -> (context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in let context = try castOrThrow(UICollectionViewFocusUpdateContext.self, a[1]) let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) return (context: context, animationCoordinator: animationCoordinator) } return ControlEvent(events: source) } } #endif
371af5dab9c92994d04cbaa43c5a20f5
42.189474
215
0.655374
false
false
false
false
finder39/Swimgur
refs/heads/master
Swimgur/Controllers/GalleryItemView/GalleryItemTableView.swift
mit
1
// // GalleryItemTableView.swift // Swimgur // // Created by Joseph Neuman on 11/9/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import Foundation import UIKit import SWNetworking private enum GalleryItemTableSection: Int { case Images = 0 case GalleryItemInfo = 1 case Comments = 2 } class GalleryItemTableView: UITableView, UITableViewDelegate, UITableViewDataSource { var galleryIndex:Int = -1 { didSet { if DataManager.sharedInstance.galleryItems.count > galleryIndex && galleryIndex >= 0 { self.loadImage() } } } private var currentGalleryItem:GalleryItem? { if DataManager.sharedInstance.galleryItems.count > galleryIndex && galleryIndex >= 0 { return DataManager.sharedInstance.galleryItems[galleryIndex] } else { return nil } } var textCell:ImgurTextCell! var commentCell:CommentCell! // lifecyle override init() { super.init() setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) setup() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { // hacky hack hack //self.registerClass(ImgurTextCell.self, forCellReuseIdentifier: "ImgurTextCellReuseIdentifier") //self.registerClass(CommentCell.self, forCellReuseIdentifier: "CommentCellReuseIdentifier") //self.registerClass(ImgurImageCell.self, forCellReuseIdentifier: "ImgurImageCellReuseIdentifier") self.registerNib(UINib(nibName: "ImgurImageCell", bundle: nil), forCellReuseIdentifier: Constants.ReuseIdentifier.ImgurImageCellReuseIdentifier) self.registerNib(UINib(nibName: "ImgurTextCell", bundle: nil), forCellReuseIdentifier: Constants.ReuseIdentifier.ImgurTextCellReuseIdentifier) self.registerNib(UINib(nibName: "CommentCell", bundle: nil), forCellReuseIdentifier: Constants.ReuseIdentifier.CommentCellReuseIdentifier) self.registerNib(UINib(nibName: "GalleryItemInfoCell", bundle: nil), forCellReuseIdentifier: Constants.ReuseIdentifier.GalleryItemInfoCellReuseIdentifier) textCell = self.dequeueReusableCellWithIdentifier(Constants.ReuseIdentifier.ImgurTextCellReuseIdentifier) as ImgurTextCell commentCell = self.dequeueReusableCellWithIdentifier(Constants.ReuseIdentifier.CommentCellReuseIdentifier) as CommentCell self.delegate = self self.dataSource = self } // galleryitem functions func loadImage() { dispatch_async(dispatch_get_main_queue()) { self.scrollRectToVisible(CGRectMake(0, 0, 1, 1), animated: false) } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { if let item = self.currentGalleryItem { item.getComments({ (success) -> () in dispatch_async(dispatch_get_main_queue()) { self.reloadData() } }) //self.title = item.title //self.colorFromVote(item) // http://stackoverflow.com/questions/19896447/ios-7-navigation-bar-height /*UIView.animateWithDuration(0.25, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in self.navigationController!.navigationBar.bounds = CGRectMake(0, 0, self.navigationController!.navigationBar.frame.size.width, 100) }, completion: { (done) -> Void in })*/ if let galleryImage = item as? GalleryImage { dispatch_async(dispatch_get_main_queue()) { self.reloadData() } } else if let galleryAlbum = item as? GalleryAlbum { if galleryAlbum.images.count == 0 { galleryAlbum.getAlbum(onCompletion: { (album) -> () in DataManager.sharedInstance.galleryItems[self.galleryIndex] = album self.loadImage() }) } else { dispatch_async(dispatch_get_main_queue()) { self.reloadData() } } } } } } // MARK: UITableViewDelegate func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == GalleryItemTableSection.Images.rawValue { if let item = currentGalleryItem { if item.tableViewDataSourceArray[indexPath.row].type == .Image { if let image = item.tableViewDataSourceArray[indexPath.row].associatedGalleryImage { let height:CGFloat = tableView.frame.width/CGFloat(image.width)*CGFloat(image.height) return height } else if let image = item.tableViewDataSourceArray[indexPath.row].associatedAlbumImage { let height:CGFloat = tableView.frame.width/CGFloat(image.width)*CGFloat(image.height) return height } } else if item.tableViewDataSourceArray[indexPath.row].type == .Title || item.tableViewDataSourceArray[indexPath.row].type == .Description { textCell.imgurText.text = item.tableViewDataSourceArray[indexPath.row].text let size = textCell.imgurText.sizeThatFits(CGSizeMake(tableView.frame.size.width, CGFloat.max)) return size.height } } } else if indexPath.section == GalleryItemTableSection.Comments.rawValue { if let item = currentGalleryItem { let comment = item.tableViewDataSourceCommentsArray[indexPath.row].associatedComment! commentCell.imgurText.text = comment.comment let size = commentCell.imgurText.sizeThatFits(CGSizeMake(tableView.frame.size.width, CGFloat.max)) return size.height+24 } } return 40 } func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int { if indexPath.section == GalleryItemTableSection.Images.rawValue { } else if indexPath.section == GalleryItemTableSection.Comments.rawValue { let item = currentGalleryItem! let comment = item.tableViewDataSourceCommentsArray[indexPath.row].associatedComment! return comment.depth } return 0 } // MARK: UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let item = currentGalleryItem { if section == GalleryItemTableSection.Images.rawValue { return item.tableViewDataSourceArray.count } else if section == GalleryItemTableSection.Comments.rawValue { return item.tableViewDataSourceCommentsArray.count } else if section == GalleryItemTableSection.GalleryItemInfo.rawValue { return 1 } } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == GalleryItemTableSection.Images.rawValue { let item = currentGalleryItem! if item.tableViewDataSourceArray[indexPath.row].type == .Image { var cell = tableView.dequeueReusableCellWithIdentifier(Constants.ReuseIdentifier.ImgurImageCellReuseIdentifier, forIndexPath: indexPath) as ImgurImageCell SWNetworking.sharedInstance.setImageView(cell.imgurImage, withURL: item.tableViewDataSourceArray[indexPath.row].text) return cell } else if item.tableViewDataSourceArray[indexPath.row].type == .Title || item.tableViewDataSourceArray[indexPath.row].type == .Description { var cell = tableView.dequeueReusableCellWithIdentifier(Constants.ReuseIdentifier.ImgurTextCellReuseIdentifier, forIndexPath: indexPath) as ImgurTextCell cell.imgurText.text = item.tableViewDataSourceArray[indexPath.row].text return cell } } else if indexPath.section == GalleryItemTableSection.Comments.rawValue { let item = currentGalleryItem! let comment = item.tableViewDataSourceCommentsArray[indexPath.row].associatedComment! var cell = tableView.dequeueReusableCellWithIdentifier(Constants.ReuseIdentifier.CommentCellReuseIdentifier, forIndexPath: indexPath) as CommentCell cell.authorButton.setTitle(comment.author, forState: .Normal) let authorSize = cell.authorButton.sizeThatFits(CGSizeMake(CGFloat.max, cell.authorButton.frame.size.height)) cell.authorWidth.constant = authorSize.width if let points = comment.points { cell.pointsLabel.text = "\(points) points" } else { cell.pointsLabel.text = "0 points" } let pointsSize = cell.pointsLabel.sizeThatFits(CGSizeMake(CGFloat.max, cell.pointsLabel.frame.size.height)) cell.pointsWidth.constant = pointsSize.width cell.imgurText.text = comment.comment if comment.children.count > 0 { cell.expandButton.hidden = false } if comment.expanded { cell.expandButton.setTitle("Collapse", forState: .Normal) } cell.associatedComment = comment cell.associatedGalleryItem = item cell.parentTableView = tableView return cell } else if indexPath.section == GalleryItemTableSection.GalleryItemInfo.rawValue { let item = currentGalleryItem! var cell = tableView.dequeueReusableCellWithIdentifier(Constants.ReuseIdentifier.GalleryItemInfoCellReuseIdentifier, forIndexPath: indexPath) as GalleryItemInfoCell if item.loadingComments == true { cell.commentsInfoLabel.text = "Loading comments..." } else { var levelZeroComments = 0 for theComment in item.comments { if theComment.depth == 0 { levelZeroComments++ } } cell.commentsInfoLabel.text = "\(levelZeroComments) comments by Popularity" } return cell } return UITableViewCell() } }
4f62b442760c0ff4e34011ecfdaa94fb
39.401639
170
0.699706
false
false
false
false
Binur/SubscriptionPrompt
refs/heads/master
SubscriptionPrompt/OptionStyle.swift
mit
1
// // OptionStyle.swift // SubscriptionPrompt // // Created by Binur Konarbayev on 7/16/16. // // import UIKit @objc public final class OptionStyle: NSObject { let backgroundColor: UIColor? let textFont: UIFont? let textColor: UIColor? let accessoryType: UITableViewCellAccessoryType? public init(backgroundColor: UIColor? = nil, textFont: UIFont? = nil, textColor: UIColor? = nil, accessoryType: UITableViewCellAccessoryType? = nil) { self.backgroundColor = backgroundColor self.textFont = textFont self.textColor = textColor self.accessoryType = accessoryType } }
a72a6b827d27247c28a2713fc3c2bed3
26
96
0.680556
false
false
false
false
andrewloyola/siesta
refs/heads/master
Source/Entity.swift
mit
2
// // Entity.swift // Siesta // // Created by Paul on 2015/6/26. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation /** An [HTTP entity](http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html). Consists of data content plus metadata about the content’s type and freshness. Typically extracted from an HTTP message body. */ public struct Entity { /** The data itself. When constructed from an HTTP response, it begins its life as `NSData`, but may become any type of object after running though the service’s `ResponseTransformer` chain. When using `content`, because you do not know what the server actually returned, write your code to handle it being of an unexpected type. Siesta provides `TypedContentAccessors` to help deal with this. - Note: Why is the type of this property `Any` instead of a generic `T`? Because an `Entity<T>` declaration would mean “Siesta guarantees the data is of type `T`” — that’s what strong static types do — but there is no way to tell Swift at _compile time_ what content type a server will actually send at _runtime_. The best client code can do is to say, “I expect the server to have returned data of type `T`; did it?” That is exactly what Swift’s `as?` operator does — and any scheme within the current system involving a generic `Entity<T>` ends up being an obfuscated equivalent to `as?` — or, far worse, an obfuscated `as!`, a.k.a. “The Amazing Server-Triggered Client Crash-o-Matic.” Siesta’s future direction is to let users declare their expected type at the resource level by asking for a `Resource<T>`, and have that resource report an unexpected content type from the server as a request failure. However, limitations of Swift’s type system currently make this unworkable. Given what the core Swift team is saying, we’re cautiously optimistic that Swift 3 will be able to support this. - SeeAlso: `TypedContentAccessors` */ public var content: Any /** The type of data contained in the content. If the content was parsed into a data structure, this property typically contains the type of the original raw data. For example, the type might be `application/json` even though `content` is a `Dictionary` and no longer the original JSON text data. This property may include MIME parameters, so beware of using exact string matches. For a plain text response, for example, you might see “`text/plain`”, “`text/plain; charset=utf-8`”, or even “`text/foo+plain`”. */ public var contentType: String { return headers["content-type"] ?? "application/octet-stream" } /** The charset given with the content type, if any. */ public var charset: String? /** The etag of this data. If non-nil, Siesta will send an `If-None-Match` header with subsequent loads. */ public var etag: String? { return headers["etag"] } internal var headers: [String:String] /// The time at which this data was last known to be valid. public var timestamp: NSTimeInterval /** Extracts data from a network response. */ public init(response: NSHTTPURLResponse?, content: Any) { let headers = (response?.allHeaderFields ?? [:]) .flatMapDict { ($0 as? String, $1 as? String) } self.init( content: content, charset: response?.textEncodingName, headers: headers) } /** For creating ad hoc data locally. - SeeAlso: `Resource.overrideLocalData(_:)` */ public init( content: Any, contentType: String, charset: String? = nil, headers: [String:String] = [:]) { var headers = headers headers["Content-Type"] = contentType self.init(content:content, charset:charset, headers:headers) } /** Full-width initializer, typically used only for reinflating cached data. */ public init( content: Any, charset: String? = nil, headers rawHeaders: [String:String], timestamp: NSTimeInterval? = nil) { self.content = content self.headers = rawHeaders.mapDict { ($0.lowercaseString, $1) } self.charset = charset if let timestamp = timestamp { self.timestamp = timestamp } else { self.timestamp = 0 self.touch() } } /** Returns the value of the HTTP header with the given key. Entity does not support multi-valued headers (i.e. headers which occur more than once in the response). - Parameter key: The case-insensitive header name. */ @warn_unused_result public func header(key: String) -> String? { return headers[key.lowercaseString] } /// Updates `timestamp` to the current time. public mutating func touch() { timestamp = now() } } /** Mixin that provides convenience accessors for the content of an optional contained entity. Allows you to replace the following: resource.latestData?.content as? String (resource.latestError?.entity?.content as? [String:AnyObject])?["error.detail"] …with: resource.text resource.latestError?.jsonDict["error.detail"] You can extend this protocol to provide your own convenience accessors. For example: extension TypedContentAccessors { var doorknob: UIDoorknob { return typedContent(ifNone: placeholderKnob)) } } Note that the sample code above is _only_ a convenience accessor. It checks whether the entity already has a `UIDoorknob`, but does not do any parsing to put a `UIDoorknob` there in the first place. You’d need to pair this with a custom `ResponseTransformer` that converts raw doorknob responses to `UIDoorknob`s. */ public protocol TypedContentAccessors { /// The entity to which the convenience accessors will apply. var entityForTypedContentAccessors: Entity? { get } } public extension TypedContentAccessors { /** A convenience for retrieving the content in this container when you expect it to be of a specific type. For example, if you expect the content to be a UIImage: let image = typedContent(ifNone: UIImage(named: "placeholder.png")) - Returns: The content if it is present _and_ can be downcast to a type matching both the `ifNone` parameter and the inferred return type; otherwise returns `ifNone`. - SeeAlso: `typedContent()` - SeeAlso: `ResponseTransformer` */ @warn_unused_result public func typedContent<T>(@autoclosure ifNone defaultContent: () -> T) -> T { return (entityForTypedContentAccessors?.content as? T) ?? defaultContent() } /// Variant of `typedContent(ifNone:)` with optional input & output. @warn_unused_result public func typedContent<T>(@autoclosure ifNone defaultContent: () -> T?) -> T? { return (entityForTypedContentAccessors?.content as? T) ?? defaultContent() } /** A variant of `typedContent(ifNone:)` that infers the desired type entirely from context, and returns nil if the content is either not present or cannot be cast to that type. For example: func showUser(user: User?) { ... } showUser(resource.typedContent()) // Infers that desired type is User */ @warn_unused_result public func typedContent<T>() -> T? { return typedContent(ifNone: nil) } /// Returns content if it is a dictionary with string keys; otherwise returns an empty dictionary. public var jsonDict: [String:AnyObject] { return typedContent(ifNone: [:]) } /// Returns content if it is an array; otherwise returns an empty array. public var jsonArray: [AnyObject] { return typedContent(ifNone: []) } /// Returns content if it is a string; otherwise returns an empty string. public var text: String { return typedContent(ifNone: "") } } extension Entity: TypedContentAccessors { /// Typed content accessors such as `.text` and `.jsonDict` apply to this entity’s content. public var entityForTypedContentAccessors: Entity? { return self } } extension Resource: TypedContentAccessors { /// Typed content accessors such as `.text` and `.jsonDict` apply to `latestData?.content`. public var entityForTypedContentAccessors: Entity? { return latestData } } extension Error: TypedContentAccessors { /// Typed content accessors such as `.text` and `.jsonDict` apply to `entity?.content`. public var entityForTypedContentAccessors: Entity? { return entity } }
a1d91e7ba5779dc460623513680a272d
35.639344
120
0.655481
false
false
false
false
fastred/IBAnalyzer
refs/heads/master
Pods/SourceKittenFramework/Source/SourceKittenFramework/String+SourceKitten.swift
mit
1
// // String+SourceKitten.swift // SourceKitten // // Created by JP Simard on 2015-01-05. // Copyright (c) 2015 SourceKitten. All rights reserved. // import Foundation // swiftlint:disable file_length // This file could easily be split up /// Representation of line in String public struct Line { /// origin = 0 public let index: Int /// Content public let content: String /// UTF16 based range in entire String. Equivalent to Range<UTF16Index> public let range: NSRange /// Byte based range in entire String. Equivalent to Range<UTF8Index> public let byteRange: NSRange } /** * For "wall of asterisk" comment blocks, such as this one. */ private let commentLinePrefixCharacterSet: CharacterSet = { var characterSet = CharacterSet.whitespacesAndNewlines characterSet.insert(charactersIn: "*") return characterSet }() extension NSString { /** CacheContainer caches: - UTF16-based NSRange - UTF8-based NSRange - Line */ private class CacheContainer { let lines: [Line] let utf8View: String.UTF8View init(_ string: NSString) { // Make a copy of the string to avoid holding a circular reference, which would leak // memory. // // If the string is a `Swift.String`, strongly referencing that in `CacheContainer` does // not cause a circular reference, because casting `String` to `NSString` makes a new // `NSString` instance. // // If the string is a native `NSString` instance, a circular reference is created when // assigning `self.utf8View = (string as String).utf8`. // // A reference to `NSString` is held by every cast `String` along with their views and // indices. let string = (string.mutableCopy() as! NSMutableString).bridge() utf8View = string.utf8 var utf16CountSoFar = 0 var bytesSoFar = 0 var lines = [Line]() let lineContents = string.components(separatedBy: .newlines) // Be compatible with `NSString.getLineStart(_:end:contentsEnd:forRange:)` let endsWithNewLineCharacter: Bool if let lastChar = string.utf16.last, let lastCharScalar = UnicodeScalar(lastChar) { endsWithNewLineCharacter = CharacterSet.newlines.contains(lastCharScalar) } else { endsWithNewLineCharacter = false } // if string ends with new line character, no empty line is generated after that. let enumerator = endsWithNewLineCharacter ? AnySequence(lineContents.dropLast().enumerated()) : AnySequence(lineContents.enumerated()) for (index, content) in enumerator { let index = index + 1 let rangeStart = utf16CountSoFar let utf16Count = content.utf16.count utf16CountSoFar += utf16Count let byteRangeStart = bytesSoFar let byteCount = content.lengthOfBytes(using: .utf8) bytesSoFar += byteCount let newlineLength = index != lineContents.count ? 1 : 0 // FIXME: assumes \n let line = Line( index: index, content: content, range: NSRange(location: rangeStart, length: utf16Count + newlineLength), byteRange: NSRange(location: byteRangeStart, length: byteCount + newlineLength) ) lines.append(line) utf16CountSoFar += newlineLength bytesSoFar += newlineLength } self.lines = lines } /** Returns UTF16 offset from UTF8 offset. - parameter byteOffset: UTF8-based offset of string. - returns: UTF16 based offset of string. */ func location(fromByteOffset byteOffset: Int) -> Int { if lines.isEmpty { return 0 } let index = lines.index(where: { NSLocationInRange(byteOffset, $0.byteRange) }) // byteOffset may be out of bounds when sourcekitd points end of string. guard let line = (index.map { lines[$0] } ?? lines.last) else { fatalError() } let diff = byteOffset - line.byteRange.location if diff == 0 { return line.range.location } else if line.byteRange.length == diff { return NSMaxRange(line.range) } let utf8View = line.content.utf8 let endUTF16index = utf8View.index(utf8View.startIndex, offsetBy: diff, limitedBy: utf8View.endIndex)! .samePosition(in: line.content.utf16)! let utf16Diff = line.content.utf16.distance(from: line.content.utf16.startIndex, to: endUTF16index) return line.range.location + utf16Diff } /** Returns UTF8 offset from UTF16 offset. - parameter location: UTF16-based offset of string. - returns: UTF8 based offset of string. */ func byteOffset(fromLocation location: Int) -> Int { if lines.isEmpty { return 0 } let index = lines.index(where: { NSLocationInRange(location, $0.range) }) // location may be out of bounds when NSRegularExpression points end of string. guard let line = (index.map { lines[$0] } ?? lines.last) else { fatalError() } let diff = location - line.range.location if diff == 0 { return line.byteRange.location } else if line.range.length == diff { return NSMaxRange(line.byteRange) } let utf16View = line.content.utf16 let endUTF8index = utf16View.index(utf16View.startIndex, offsetBy: diff, limitedBy: utf16View.endIndex)! .samePosition(in: line.content.utf8)! let byteDiff = line.content.utf8.distance(from: line.content.utf8.startIndex, to: endUTF8index) return line.byteRange.location + byteDiff } func lineAndCharacter(forCharacterOffset offset: Int, expandingTabsToWidth tabWidth: Int) -> (line: Int, character: Int)? { assert(tabWidth > 0) let index = lines.index(where: { NSLocationInRange(offset, $0.range) }) return index.map { let line = lines[$0] let prefixLength = offset - line.range.location let character: Int if tabWidth == 1 { character = prefixLength } else { character = line.content.prefix(prefixLength).reduce(0) { sum, character in if character == "\t" { return sum - (sum % tabWidth) + tabWidth } else { return sum + 1 } } } return (line: line.index, character: character + 1) } } func lineAndCharacter(forByteOffset offset: Int, expandingTabsToWidth tabWidth: Int) -> (line: Int, character: Int)? { let characterOffset = location(fromByteOffset: offset) return lineAndCharacter(forCharacterOffset: characterOffset, expandingTabsToWidth: tabWidth) } } static private var stringCache = [NSString: CacheContainer]() static private var stringCacheLock = NSLock() /** CacheContainer instance is stored to instance of NSString as associated object. */ private var cacheContainer: CacheContainer { NSString.stringCacheLock.lock() defer { NSString.stringCacheLock.unlock() } if let cache = NSString.stringCache[self] { return cache } let cache = CacheContainer(self) NSString.stringCache[self] = cache return cache } /** Returns line number and character for utf16 based offset. - parameter offset: utf16 based index. - parameter tabWidth: the width in spaces to expand tabs to. */ public func lineAndCharacter(forCharacterOffset offset: Int, expandingTabsToWidth tabWidth: Int = 1) -> (line: Int, character: Int)? { return cacheContainer.lineAndCharacter(forCharacterOffset: offset, expandingTabsToWidth: tabWidth) } /** Returns line number and character for byte offset. - parameter offset: byte offset. - parameter tabWidth: the width in spaces to expand tabs to. */ public func lineAndCharacter(forByteOffset offset: Int, expandingTabsToWidth tabWidth: Int = 1) -> (line: Int, character: Int)? { return cacheContainer.lineAndCharacter(forByteOffset: offset, expandingTabsToWidth: tabWidth) } /** Returns a copy of `self` with the trailing contiguous characters belonging to `characterSet` removed. - parameter characterSet: Character set to check for membership. */ public func trimmingTrailingCharacters(in characterSet: CharacterSet) -> String { guard length > 0 else { return "" } var unicodeScalars = self.bridge().unicodeScalars while let scalar = unicodeScalars.last { if !characterSet.contains(scalar) { return String(unicodeScalars) } unicodeScalars.removeLast() } return "" } /** Returns self represented as an absolute path. - parameter rootDirectory: Absolute parent path if not already an absolute path. */ public func absolutePathRepresentation(rootDirectory: String = FileManager.default.currentDirectoryPath) -> String { if isAbsolutePath { return bridge() } #if os(Linux) return NSURL(fileURLWithPath: NSURL.fileURL(withPathComponents: [rootDirectory, bridge()])!.path).standardizingPath!.path #else return NSString.path(withComponents: [rootDirectory, bridge()]).bridge().standardizingPath #endif } /** Converts a range of byte offsets in `self` to an `NSRange` suitable for filtering `self` as an `NSString`. - parameter start: Starting byte offset. - parameter length: Length of bytes to include in range. - returns: An equivalent `NSRange`. */ public func byteRangeToNSRange(start: Int, length: Int) -> NSRange? { if self.length == 0 { return nil } let utf16Start = cacheContainer.location(fromByteOffset: start) if length == 0 { return NSRange(location: utf16Start, length: 0) } let utf16End = cacheContainer.location(fromByteOffset: start + length) return NSRange(location: utf16Start, length: utf16End - utf16Start) } /** Converts an `NSRange` suitable for filtering `self` as an `NSString` to a range of byte offsets in `self`. - parameter start: Starting character index in the string. - parameter length: Number of characters to include in range. - returns: An equivalent `NSRange`. */ public func NSRangeToByteRange(start: Int, length: Int) -> NSRange? { let string = bridge() let utf16View = string.utf16 let startUTF16Index = utf16View.index(utf16View.startIndex, offsetBy: start) let endUTF16Index = utf16View.index(startUTF16Index, offsetBy: length) let utf8View = string.utf8 guard let startUTF8Index = startUTF16Index.samePosition(in: utf8View), let endUTF8Index = endUTF16Index.samePosition(in: utf8View) else { return nil } // Don't using `CacheContainer` if string is short. // There are two reasons for: // 1. Avoid using associatedObject on NSTaggedPointerString (< 7 bytes) because that does // not free associatedObject. // 2. Using cache is overkill for short string. let byteOffset: Int if utf16View.count > 50 { byteOffset = cacheContainer.byteOffset(fromLocation: start) } else { byteOffset = utf8View.distance(from: utf8View.startIndex, to: startUTF8Index) } // `cacheContainer` will hit for below, but that will be calculated from startUTF8Index // in most case. let length = utf8View.distance(from: startUTF8Index, to: endUTF8Index) return NSRange(location: byteOffset, length: length) } /** Returns a substring with the provided byte range. - parameter start: Starting byte offset. - parameter length: Length of bytes to include in range. */ public func substringWithByteRange(start: Int, length: Int) -> String? { return byteRangeToNSRange(start: start, length: length).map(substring) } /** Returns a substring starting at the beginning of `start`'s line and ending at the end of `end`'s line. Returns `start`'s entire line if `end` is nil. - parameter start: Starting byte offset. - parameter length: Length of bytes to include in range. */ public func substringLinesWithByteRange(start: Int, length: Int) -> String? { return byteRangeToNSRange(start: start, length: length).map { range in var lineStart = 0, lineEnd = 0 getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: range) return substring(with: NSRange(location: lineStart, length: lineEnd - lineStart)) } } public func substringStartingLinesWithByteRange(start: Int, length: Int) -> String? { return byteRangeToNSRange(start: start, length: length).map { range in var lineStart = 0, lineEnd = 0 getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: range) return substring(with: NSRange(location: lineStart, length: NSMaxRange(range) - lineStart)) } } /** Returns line numbers containing starting and ending byte offsets. - parameter start: Starting byte offset. - parameter length: Length of bytes to include in range. */ public func lineRangeWithByteRange(start: Int, length: Int) -> (start: Int, end: Int)? { return byteRangeToNSRange(start: start, length: length).flatMap { range in var numberOfLines = 0, index = 0, lineRangeStart = 0 while index < self.length { numberOfLines += 1 if index <= range.location { lineRangeStart = numberOfLines } index = NSMaxRange(lineRange(for: NSRange(location: index, length: 1))) if index > NSMaxRange(range) { return (lineRangeStart, numberOfLines) } } return nil } } /** Returns an array of Lines for each line in the file. */ public func lines() -> [Line] { return cacheContainer.lines } /** Returns true if self is an Objective-C header file. */ public func isObjectiveCHeaderFile() -> Bool { return ["h", "hpp", "hh"].contains(pathExtension) } /** Returns true if self is a Swift file. */ public func isSwiftFile() -> Bool { return pathExtension == "swift" } #if !os(Linux) /** Returns a substring from a start and end SourceLocation. */ public func substringWithSourceRange(start: SourceLocation, end: SourceLocation) -> String? { return substringWithByteRange(start: Int(start.offset), length: Int(end.offset - start.offset)) } #endif } extension String { internal var isFile: Bool { return FileManager.default.fileExists(atPath: self) } internal func capitalizingFirstLetter() -> String { return String(prefix(1)).capitalized + String(dropFirst()) } #if !os(Linux) /// Returns the `#pragma mark`s in the string. /// Just the content; no leading dashes or leading `#pragma mark`. public func pragmaMarks(filename: String, excludeRanges: [NSRange], limit: NSRange?) -> [SourceDeclaration] { let regex = try! NSRegularExpression(pattern: "(#pragma\\smark|@name)[ -]*([^\\n]+)", options: []) // Safe to force try let range: NSRange if let limit = limit { range = NSRange(location: limit.location, length: min(utf16.count - limit.location, limit.length)) } else { range = NSRange(location: 0, length: utf16.count) } let matches = regex.matches(in: self, options: [], range: range) return matches.flatMap { match in let markRange = match.range(at: 2) for excludedRange in excludeRanges { if NSIntersectionRange(excludedRange, markRange).length > 0 { return nil } } let markString = (self as NSString).substring(with: markRange).trimmingCharacters(in: .whitespaces) if markString.isEmpty { return nil } guard let markByteRange = self.NSRangeToByteRange(start: markRange.location, length: markRange.length) else { return nil } let location = SourceLocation(file: filename, line: UInt32((self as NSString).lineRangeWithByteRange(start: markByteRange.location, length: 0)!.start), column: 1, offset: UInt32(markByteRange.location)) return SourceDeclaration(type: .mark, location: location, extent: (location, location), name: markString, usr: nil, declaration: nil, documentation: nil, commentBody: nil, children: [], swiftDeclaration: nil, swiftName: nil, availability: nil) } } #endif /** Returns whether or not the `token` can be documented. Either because it is a `SyntaxKind.Identifier` or because it is a function treated as a `SyntaxKind.Keyword`: - `subscript` - `init` - `deinit` - parameter token: Token to process. */ public func isTokenDocumentable(token: SyntaxToken) -> Bool { if token.type == SyntaxKind.keyword.rawValue { let keywordFunctions = ["subscript", "init", "deinit"] return bridge().substringWithByteRange(start: token.offset, length: token.length) .map(keywordFunctions.contains) ?? false } return token.type == SyntaxKind.identifier.rawValue } /** Find integer offsets of documented Swift tokens in self. - parameter syntaxMap: Syntax Map returned from SourceKit editor.open request. - returns: Array of documented token offsets. */ public func documentedTokenOffsets(syntaxMap: SyntaxMap) -> [Int] { let documentableOffsets = syntaxMap.tokens.filter(isTokenDocumentable).map { $0.offset } let regex = try! NSRegularExpression(pattern: "(///.*\\n|\\*/\\n)", options: []) // Safe to force try let range = NSRange(location: 0, length: utf16.count) let matches = regex.matches(in: self, options: [], range: range) return matches.flatMap { match in documentableOffsets.first { $0 >= match.range.location } } } /** Returns the body of the comment if the string is a comment. - parameter range: Range to restrict the search for a comment body. */ public func commentBody(range: NSRange? = nil) -> String? { let nsString = bridge() let patterns: [(pattern: String, options: NSRegularExpression.Options)] = [ ("^\\s*\\/\\*\\*\\s*(.*?)\\*\\/", [.anchorsMatchLines, .dotMatchesLineSeparators]), // multi: ^\s*\/\*\*\s*(.*?)\*\/ ("^\\s*\\/\\/\\/(.+)?", .anchorsMatchLines) // single: ^\s*\/\/\/(.+)? // swiftlint:disable:previous comma ] let range = range ?? NSRange(location: 0, length: nsString.length) for pattern in patterns { let regex = try! NSRegularExpression(pattern: pattern.pattern, options: pattern.options) // Safe to force try let matches = regex.matches(in: self, options: [], range: range) let bodyParts = matches.flatMap { match -> [String] in let numberOfRanges = match.numberOfRanges if numberOfRanges < 1 { return [] } return (1..<numberOfRanges).map { rangeIndex in let range = match.range(at: rangeIndex) if range.location == NSNotFound { return "" // empty capture group, return empty string } var lineStart = 0 var lineEnd = nsString.length let indexRange = NSRange(location: range.location, length: 0) nsString.getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: indexRange) let leadingWhitespaceCountToAdd = nsString.substring(with: NSRange(location: lineStart, length: lineEnd - lineStart)) .countOfLeadingCharacters(in: .whitespacesAndNewlines) let leadingWhitespaceToAdd = String(repeating: " ", count: leadingWhitespaceCountToAdd) let bodySubstring = nsString.substring(with: range) if bodySubstring.contains("@name") { return "" // appledoc directive, return empty string } return leadingWhitespaceToAdd + bodySubstring } } if !bodyParts.isEmpty { return bodyParts.joined(separator: "\n").bridge() .trimmingTrailingCharacters(in: .whitespacesAndNewlines) .removingCommonLeadingWhitespaceFromLines() } } return nil } /// Returns a copy of `self` with the leading whitespace common in each line removed. public func removingCommonLeadingWhitespaceFromLines() -> String { var minLeadingCharacters = Int.max let lineComponents = components(separatedBy: .newlines) for line in lineComponents { let lineLeadingWhitespace = line.countOfLeadingCharacters(in: .whitespacesAndNewlines) let lineLeadingCharacters = line.countOfLeadingCharacters(in: commentLinePrefixCharacterSet) // Is this prefix smaller than our last and not entirely whitespace? if lineLeadingCharacters < minLeadingCharacters && lineLeadingWhitespace != line.count { minLeadingCharacters = lineLeadingCharacters } } return lineComponents.map { line in if line.count >= minLeadingCharacters { return String(line[line.index(line.startIndex, offsetBy: minLeadingCharacters)...]) } return line }.joined(separator: "\n") } /** Returns the number of contiguous characters at the start of `self` belonging to `characterSet`. - parameter characterSet: Character set to check for membership. */ public func countOfLeadingCharacters(in characterSet: CharacterSet) -> Int { let characterSet = characterSet.bridge() var count = 0 for char in utf16 { if !characterSet.characterIsMember(char) { break } count += 1 } return count } /// Returns a copy of the string by trimming whitespace and the opening curly brace (`{`). internal func trimmingWhitespaceAndOpeningCurlyBrace() -> String? { var unwantedSet = CharacterSet.whitespacesAndNewlines unwantedSet.insert(charactersIn: "{") return trimmingCharacters(in: unwantedSet) } /// Returns the byte offset of the section of the string following the last dot ".", or 0 if no dots. internal func byteOffsetOfInnerTypeName() -> Int64 { guard let range = range(of: ".", options: .backwards) else { return 0 } #if swift(>=4.0) let utf8pos = index(after: range.lowerBound).samePosition(in: utf8)! #else let utf8pos = index(after: range.lowerBound).samePosition(in: utf8) #endif return Int64(utf8.distance(from: utf8.startIndex, to: utf8pos)) } }
0d9763a6190180dfda6035434b92fc8a
39.341021
138
0.605178
false
false
false
false
alltheflow/copypasta
refs/heads/master
Carthage/Checkouts/VinceRP/vincerpTests/Common/AdvancedSpec.swift
mit
1
// // Created by Viktor Belenyesi on 18/04/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // @testable import VinceRP import Quick import Nimble func myRandom() -> Int { return Int(arc4random()) } let fakeError = NSError(domain: "domain.com", code: 1, userInfo: nil) class AdvancedSpec: QuickSpec { override func spec() { describe("advanced") { /* context("performance") { it("init") { // given let start = CACurrentMediaTime() var n = 0 // when while CACurrentMediaTime() < start + 1.0 { let (_, _, _, _, _, _) = testGraph() n += 1 } // then expect(n) > 30000 } it("propagation") { // given let (a, b, c, d, e, f) = testGraph() let start = CACurrentMediaTime() var n = 0 // when while CACurrentMediaTime() < start + 1.0 { a <- n n += 1 } // then expect(n) > 9500.0 } } */ context("nesting") { it("works with nested reactives") { // given let a = reactive(1) let b = definedAs { (definedAs{ a* }, definedAs{ myRandom() }) } let r = b*.1* // when a <- 2 // then expect(b*.1*) =~ r } it("works with recalcs") { // given var source = 0 let a = definedAs{source} var i = 0 _ = onChangeDo(a){ _ in i += 1 } // then expect(i) =~ 1 expect(a*) =~ 0 // when source = 1 // then expect(a*) =~ 0 // when a.recalc() // then expect(a*) =~ 1 expect(i) =~ 2 } it("can update multiple variables in a batch") { // given let a = reactive(1) let b = reactive(1) let c = reactive(1) let d = definedAs { a* + b* + c* } var i = 0 // when _ = onChangeDo(d) { _ in i += 1 } // then expect(i) =~ 1 a <- 2 expect(i) =~ 2 b <- 2 expect(i) =~ 3 c <- 2 expect(i) =~ 4 BatchUpdate(a, withValue:3).and(b, withValue:3).and(c, withValue:3).now() expect(i) =~ 5 BatchUpdate(a, withValue:4).and(b, withValue:5).and(c, withValue:6).now() expect(i) =~ 6 expect(a*) =~ 4 expect(b*) =~ 5 expect(c*) =~ 6 } } } describe("combinators") { it("blocks observers") { // given let a = reactive(10) let b = a.filter { $0 > 5 } var sideeffect = 0 onChangeDo(b) { _ in sideeffect = sideeffect + 1 } // when a <- 1 // then expect(b*) =~ 10 expect(sideeffect) =~ 1 // when a <- 2 // then expect(b*) =~ 10 expect(sideeffect) =~ 1 // when a <- 6 // then expect(b*) =~ 6 expect(sideeffect) =~ 2 } } context("kill") { it("kills observer") { // given let a = reactive(1) let b = definedAs { 2 * a* } var target = 0 let o = onChangeDo(b) { _ in target = b* } // then expect(a.children) =~ toSet(b) expect(b.children) =~ toSet(o) expect(target) =~ 2 // when a <- 2 // then expect(target) =~ 4 // when o.kill() // then expect(a.children) =~ toSet(b) expect(b.children) =~ Set() // when a <- 3 // then expect(target) =~ 4 } it("kills reactive") { // given let (a, b, c, d, e, f) = testGraph() // then expect(c*) =~ 2 expect(e*) =~ 1 expect(f*) =~ 10 // when a <- 3 // then expect(c*) =~ 6 expect(e*) =~ 3 expect(f*) =~ 12 // when d.kill() a <- 1 // then expect(f*) =~ 14 expect(e.children) =~ toSet(f) // when f.kill() // then expect(e.children) =~ Set() // when a <- 3 // then expect(c*) =~ 6 expect(e*) =~ 3 expect(f*) =~ 14 expect(a.children) =~ toSet(c) expect(b.children) =~ toSet(c) // when c.kill() // then expect(a.children) =~ Set() expect(b.children) =~ Set() // when a <- 1 // then expect(c*) =~ 6 expect(e*) =~ 3 expect(f*) =~ 14 } it("kills all Hub") { // given let (a, _, c, d, e, f) = testGraph() // when // killAll-ing d makes f die too d.killAll() // then a <- 3 expect(c*) =~ 6 expect(e*) =~ 3 expect(f*) =~ 10 } } } }
e0f97e93076e83937c615ca4a9baa2e2
23.5
93
0.279424
false
false
false
false
beltex/dshb
refs/heads/master
dshb/main.swift
mit
1
// // main.swift // dshb // // The MIT License // // Copyright (C) 2014-2017 beltex <https://beltex.github.io> // // 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 IOKit import Darwin.ncurses //------------------------------------------------------------------------------ // MARK: GLOBAL PROPERTIES //------------------------------------------------------------------------------ /// Application version let dshbVersion = "0.2.0" /// Statistic update frequency in seconds. Default is 1 let updateFrequency: UInt64 /// Does this machine have a battery? let hasBattery: Bool /// Does this machine have a SMC (System Management Controller)? let hasSMC: Bool /// Statistic widgets that are on (displayed) var widgets: [WidgetType] = [WidgetCPU(), WidgetMemory(), WidgetSystem()] //------------------------------------------------------------------------------ // MARK: COMMAND LINE INTERFACE //------------------------------------------------------------------------------ let CLIExperimentalOption = BoolOption(shortFlag: "e", longFlag: "experimental", helpMessage: "Turn on experimental features") let CLIFrequencyOption = IntOption(shortFlag: "f", longFlag: "frequency", helpMessage: "Statistic update frequency in seconds. Default is 1") let CLIHelpOption = BoolOption(shortFlag: "h", longFlag: "help", helpMessage: "Print the list of options") let CLIUnknownTemperatureSensorsOption = BoolOption(shortFlag: "u", longFlag: "unknown-temperature-sensors", helpMessage: "Show temperature sensors whose hardware mapping is unknown") let CLIVersionOption = BoolOption(shortFlag: "v", longFlag: "version", helpMessage: "Print dshb version") let CLI = CommandLine() CLI.addOptions(CLIExperimentalOption, CLIFrequencyOption, CLIHelpOption, CLIUnknownTemperatureSensorsOption, CLIVersionOption) do { try CLI.parse(strict: true) } catch { CLI.printUsage(error) exit(EX_USAGE) } // Give precedence to help flag if CLIHelpOption.wasSet { CLI.printUsage() exit(EX_OK) } else if CLIVersionOption.wasSet { print(dshbVersion) exit(EX_OK) } if let customFrequency = CLIFrequencyOption.value { if customFrequency < 1 { print("Usage: Statistic update frequency must be >= 1") exit(EX_USAGE) } updateFrequency = UInt64(customFrequency) } else { updateFrequency = 1 } if CLIExperimentalOption.wasSet { widgets.append(WidgetProcess()) } //------------------------------------------------------------------------------ // MARK: NCURSES SETTINGS //------------------------------------------------------------------------------ setlocale(LC_ALL, "") initscr() // Init window. Must be first cbreak() noecho() // Don't echo user input nonl() // Disable newline mode intrflush(stdscr, true) // Prevent flush keypad(stdscr, true) // Enable function and arrow keys curs_set(0) // Set cursor to invisible // Init terminal colours // TODO: Do has_color() check when we have a way to log the error, print() // won't work start_color() init_pair(Int16(WidgetUIColor.background.rawValue), Int16(COLOR_WHITE), Int16(use_default_colors())) init_pair(Int16(WidgetUIColor.title.rawValue), Int16(COLOR_WHITE), Int16(COLOR_CYAN)) init_pair(Int16(WidgetUIColor.warningLevelCool.rawValue), Int16(COLOR_BLACK), Int16(COLOR_BLUE)) init_pair(Int16(WidgetUIColor.warningLevelNominal.rawValue), Int16(COLOR_BLACK), Int16(COLOR_GREEN)) init_pair(Int16(WidgetUIColor.warningLevelDanger.rawValue), Int16(COLOR_BLACK), Int16(COLOR_YELLOW)) init_pair(Int16(WidgetUIColor.warningLevelCrisis.rawValue), Int16(COLOR_BLACK), Int16(COLOR_RED)) bkgd(UInt32(COLOR_PAIR(WidgetUIColor.background.rawValue))) //------------------------------------------------------------------------------ // MARK: WIDGET SETUP //------------------------------------------------------------------------------ // Do this before SMC, since temperature widget needs to know about battery var battery = Battery() if battery.open() == kIOReturnSuccess { // TODO: Could this change during use? Old MacBook with removeable battery? hasBattery = true widgets.append(WidgetBattery()) } else { hasBattery = false } do { try SMCKit.open() hasSMC = true widgets.append(WidgetTemperature()) // Due to the new fanless MacBook8,1 if let fanCount = try? SMCKit.fanCount(), fanCount > 0 { widgets.append(WidgetFan()) } } catch { hasSMC = false } widgets.sort { $0.displayOrder < $1.displayOrder } drawAllWidgets() //------------------------------------------------------------------------------ // MARK: GCD TIMER SETUP //------------------------------------------------------------------------------ // See comment for background for reference. // https://github.com/beltex/dshb/issues/16#issuecomment-70699890 let qAttr = DispatchQueue.Attributes() let qLabel = "com.beltex.dshb" let queue: DispatchQueue if #available(OSX 10.10, *) { let qos = DispatchQoS(qosClass: DispatchQoS.QoSClass.userInteractive, relativePriority: 0) queue = DispatchQueue(label: qLabel, qos: qos, attributes: qAttr) } else { queue = DispatchQueue(label: qLabel, attributes: qAttr) } let source = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: queue) source.scheduleRepeating(deadline: .now(), interval: Double(updateFrequency), leeway: .seconds(0)) source.setEventHandler { // TODO: If we call clear() here, can help address display "race condition" // mentioned in issue #16 (see URL above). Though we'd have to redraw // titles too for index in 0..<widgets.count { widgets[index].draw() } refresh() } // We have to resume the dispatch source as it is paused by default source.resume() //------------------------------------------------------------------------------ // MARK: MAIN (EVENT) LOOP //------------------------------------------------------------------------------ while true { switch getch() { // TODO: has_key() check for KEY_RESIZE? case KEY_RESIZE: // This could be done through GCD signal handler as well source.suspend() // If this takes too long, queue will build up. Also, there is the // issue of mutiple resize calls. drawAllWidgets() source.resume() case Int32(UnicodeScalar("q").value): // Quit source.cancel() endwin() // ncurses cleanup if hasSMC { SMCKit.close() } if hasBattery { _ = battery.close() } exit(EX_OK) default: break } }
ceab2a590dea7f4797312c62de6e2e46
35.471616
90
0.566451
false
false
false
false
alexaubry/BulletinBoard
refs/heads/develop
Sources/Support/Animations/BulletinPresentationAnimationController.swift
mit
1
/** * BulletinBoard * Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license. */ import UIKit /** * The animation controller for bulletin presentation. * * It moves the card on screen, creates and fades in the background view. */ class BulletinPresentationAnimationController: NSObject, UIViewControllerAnimatedTransitioning { let style: BLTNBackgroundViewStyle init(style: BLTNBackgroundViewStyle) { self.style = style } // MARK: - Transition func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toVC = transitionContext.viewController(forKey: .to) as? BulletinViewController else { return } let containerView = transitionContext.containerView // Fix the frame (Needed for iPad app running in split view) // (Convert the "from" view's frame coordinates to the container view's coordinate system) if let fromView = transitionContext.viewController(forKey: .from)?.view { let fromFrame = containerView.convert(fromView.frame, from: fromView) toVC.view.frame = fromFrame } let rootView = toVC.view! let contentView = toVC.contentView let backgroundView = toVC.backgroundView! // Add root view containerView.addSubview(rootView) // Prepare background view rootView.insertSubview(backgroundView, at: 0) backgroundView.leadingAnchor.constraint(equalTo: rootView.leadingAnchor).isActive = true backgroundView.trailingAnchor.constraint(equalTo: rootView.trailingAnchor).isActive = true backgroundView.topAnchor.constraint(equalTo: rootView.topAnchor).isActive = true backgroundView.bottomAnchor.constraint(equalTo: rootView.bottomAnchor).isActive = true rootView.setNeedsLayout() contentView.setNeedsLayout() rootView.layoutIfNeeded() contentView.layoutIfNeeded() backgroundView.layoutIfNeeded() // Animate presentation let duration = transitionDuration(using: transitionContext) let options = UIView.AnimationOptions(rawValue: 7 << 16) let animations = { toVC.moveIntoPlace() backgroundView.show() } UIView.animate(withDuration: duration, delay: 0, options: options, animations: animations) { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
1f9adb08800702c8983ca1dbcb9bd8e9
31.365854
109
0.69367
false
false
false
false
cuappdev/podcast-ios
refs/heads/master
Recast/Utilities/NavigationController.swift
mit
1
// // NavigationController.swift // Recast // // Created by Jack Thompson on 11/17/18. // Copyright © 2018 Cornell AppDev. All rights reserved. // import UIKit class NavigationController: UINavigationController { override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) navigationBar.prefersLargeTitles = true navigationBar.barTintColor = .black navigationBar.tintColor = .white navigationBar.isOpaque = true navigationBar.isTranslucent = false let textAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] navigationBar.titleTextAttributes = textAttributes navigationBar.largeTitleTextAttributes = textAttributes } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
67a57210be3cfe423e3b8afcf386fb63
29.558824
84
0.717036
false
false
false
false
BiteCoda/icebreaker-app
refs/heads/master
IceBreaker-iOS/IceBreaker/ScanViewController/ScanViewController.swift
gpl-3.0
1
// // ScanViewController.swift // IceBreaker // // Created by Jacob Chen on 2/21/15. // Copyright (c) 2015 floridapoly.IceMakers. All rights reserved. // import UIKit /* This View controller will be responsible for sniffing beacons in the region. */ class ScanViewController: UIViewController { @IBOutlet var searchButton: UIButton! @IBOutlet var messageLabelView: UILabel! var beaconInQuestion: ESTBeacon? let beaconManager: BeaconManager = BeaconManager.sharedBeaconManager var answerNotification: Bool = false var searchMode: Bool = true override func viewDidLoad() { super.viewDidLoad() // Add notification listener NSNotificationCenter.defaultCenter().addObserver(self, selector: "foundBeacon:", name: NOTIF_BEACON_FOUND, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "beaconPaired:", name: NOTIF_BEACON_PAIRED, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "failedPairingSource:", name: NOTIF_ERROR_PAIR_EXISTS_SOURCE, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "failedPairingTarget:", name: NOTIF_ERROR_PAIR_EXISTS_TARGET, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "failedPairingInvalidRequest:", name: NOTIF_ERROR_INVALID_REQUEST, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "failedPairingTargetNotSubscribed:", name: NOTIF_ERROR_TARGET_NOT_SUBSCRIBED, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "displayAnswer:", name: NOTIF_ANSWER_RECEIVED, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Notification Center methods func foundBeacon(notification: NSNotification) { beaconInQuestion = notification.userInfo![NOTIF_BEACON_KEY] as? ESTBeacon println("found beacon major id = \(beaconInQuestion!.major), minor = \(beaconInQuestion!.minor)") RESTManager.sharedRESTManager.request( beaconInQuestion!.major!, targetMinorID: beaconInQuestion!.minor! ) SVProgressHUD.show() } func beaconPaired(notification: NSNotification) { println("beacon paired") if !answerNotification { SVProgressHUD.dismiss() // Beacon paired, add to known beacons, display the question, change button text println ("Beacon has been paired ") Beacon.sharedBeacon.beaconsConnected.append( Beacon(majID: beaconInQuestion!.major!, minID: beaconInQuestion!.minor!) ) let content: String = notification.userInfo![NOTIF_CONTENT_KEY] as String println(content) self.messageLabelView.text = content self.searchButton.setTitle("Found!", forState: UIControlState.Normal) searchMode = false } } func failedPairingSource(notification: NSNotification) { println("failed pairing source") if !answerNotification { SVProgressHUD.dismiss() println("Failed pairing source") RESTManager.sharedRESTManager.unpair() var alert: UIAlertController = UIAlertController(title: "Device Can't Pair", message: "Huh, weird...", preferredStyle: UIAlertControllerStyle.Alert) var dismissAction: UIAlertAction = UIAlertAction(title: "Okay, fine", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in alert.dismissViewControllerAnimated(true, completion: nil) } alert.addAction(dismissAction) self.presentViewController(alert, animated: true, completion: nil) println("Failed pairing target") } } func failedPairingTarget(notification: NSNotification) { println("failed pairing target") if !answerNotification { SVProgressHUD.dismiss() var alert: UIAlertController = UIAlertController(title: "Device Can't Pair", message: "Target is taken already", preferredStyle: UIAlertControllerStyle.Alert) var dismissAction: UIAlertAction = UIAlertAction(title: "Okay, fine", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in alert.dismissViewControllerAnimated(true, completion: nil) } alert.addAction(dismissAction) self.presentViewController(alert, animated: true, completion: nil) println("Failed pairing target") } } func failedPairingInvalidRequest(notification: NSNotification) { if !answerNotification { SVProgressHUD.dismiss() println("Invalid Request") } } func failedPairingTargetNotSubscribed(notification: NSNotification) { if !answerNotification { SVProgressHUD.dismiss() var alert: UIAlertController = UIAlertController(title: "Device Can't Pair", message: "Target isn't subscribed to server", preferredStyle: UIAlertControllerStyle.Alert) var dismissAction: UIAlertAction = UIAlertAction(title: "Okay, fine", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in alert.dismissViewControllerAnimated(true, completion: nil) } alert.addAction(dismissAction) self.presentViewController(alert, animated: true, completion: nil) Beacon.sharedBeacon.beaconsTried.push( Beacon(majID: beaconInQuestion!.major, minID: beaconInQuestion!.minor) ) println(Beacon.sharedBeacon.beaconsTried.myQueue) var queue: [Beacon] = Beacon.sharedBeacon.beaconsTried.myQueue as [Beacon] for beacon in queue { println("beacon maj: \(beacon.majorID!) min: \(beacon.minorID!)") } println("Target not subscribed") } } func displayAnswer(notification: NSNotification) { var userInfo: NSDictionary = notification.userInfo! as NSDictionary var answer: String = userInfo[ANSWER_KEY] as String answerNotification = true SVProgressHUD.dismiss() self.messageLabelView.text = "Answer: \(answer)" self.searchButton.setTitle("Search", forState: UIControlState.Normal) } // MARK: Button Pressed methods @IBAction func didTouchUpInsideSearchButton(sender: AnyObject) { // check if this device has been registered if (searchMode) { // Search if RESTManager.sharedRESTManager.hasRegistered { // Begin searching beaconManager.listenToRegion(mode:beaconManagerMode.discoveryAnyMode, majID: nil, minID: nil) SVProgressHUD.show() } else { // Alert that the register hasn't happened yet var alert: UIAlertController = UIAlertController(title: "Device hasn't regiestered", message: "Please wait a little bit until you're registered", preferredStyle: UIAlertControllerStyle.Alert) var dismissAction: UIAlertAction = UIAlertAction(title: "Okay, fine", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in alert.dismissViewControllerAnimated(true, completion: nil) } alert.addAction(dismissAction) self.presentViewController(alert, animated: true, completion: nil) } } else { // Back to search searchMode = true searchButton.setTitle("Search", forState: UIControlState.Normal) self.messageLabelView.text = "" answerNotification = false RESTManager.sharedRESTManager.unpair() } } }
553ce7bce407f99ad41c5c69679af4ce
34.922764
207
0.590991
false
false
false
false
zmeriksen/Layers
refs/heads/master
Layers/ViewController.swift
mit
1
// // ViewController.swift // Layers // // Created by Zach Eriksen on 6/24/15. // Copyright (c) 2015 Leif. All rights reserved. // import UIKit class ViewController: UIViewController { var handler = LayerHandler() override func viewDidLoad() { super.viewDidLoad() createLayers() view.addSubview(handler) } func delete(){ if handler.layers.count > 0 { let layerName = handler.layers[0].label!.text handler.removeLayerWithTitle(layerName!) } } func add() -> Layer?{ func randomColor() -> UIColor{ let red = arc4random_uniform(255) let blue = arc4random_uniform(255) let green = arc4random_uniform(255) return UIColor(red: CGFloat(red)/255, green: CGFloat(green)/255, blue: CGFloat(blue)/255, alpha: 1) } return handler.addLayer(randomColor(), title: "\(arc4random_uniform(100))") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(navigationController?.isNavigationBarHidden == false, animated: false) } func createLayers(){ handler.addLayer(purple, title: "Title") handler.addLayer(blue, title: "Plan") handler.addLayer(lightGreen, title: "Budget")?.addToInnerView({ let buttonSegue = UIButton(frame: CGRect(x: 30, y: 50, width: self.handler.layerWithTitle("Budget")!.frame.width-60, height: 50)) buttonSegue.setTitle("Next", for: UIControlState()) buttonSegue.addTarget(self, action: #selector(ViewController.segue(_:)), for: .touchUpInside) buttonSegue.titleLabel?.textAlignment = .center buttonSegue.titleLabel?.textColor = .black return buttonSegue }) handler.addLayer(darkGreen, title: "Vehicles") handler.addLayer(UIColor(red: 200/255, green: 100/255, blue: 100/255, alpha: 1), title: "Definitions") } func segue(_ sender : AnyObject){ performSegue(withIdentifier: "nextView", sender: nil) navigationController?.setNavigationBarHidden(false, animated: true) } }
92ea8720b7d6ec77e0230212e31da807
34.935484
141
0.629264
false
false
false
false
Schatzjason/cs212
refs/heads/master
Networking/MovieList1/MovieList/MovieListViewController.swift
mit
1
// // MovieListViewController.swift // MovieList // // Created by ccsfcomputers on 10/29/15. // Copyright (c) 2015 Jason Schatz. All rights reserved. // import UIKit class MovieListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var movies: [Movie] = [Movie]() override func viewDidLoad() { setUIToDownloading(true) let url = TMDBURLs.URLForResource(TMDB.Resources.MovieTopRated) print(url) let task = URLSession.shared.dataTask(with: url) { data, response, error in // Simple error handling if let error = error { print(error) return } // Update the view controller's state self.movies = self.moviesFromData(data) // Send the UI Updating work back to the main thread DispatchQueue.main.async { self.tableView.reloadData() self.setUIToDownloading(false) } } task.resume() } // MARK: - Toggle UI while downloading func setUIToDownloading(_ isDownloading: Bool) { if isDownloading { self.activityIndicator.startAnimating() } else { self.activityIndicator.stopAnimating() } self.activityIndicator.isHidden = isDownloading self.tableView.alpha = isDownloading ? 0.2 : 1.0 } // MARK: - Table View func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } var cellNumber = 0 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! // Get the movie associated with this row out of the array let movie = movies[indexPath.row] // Set the movie title cell.textLabel!.text = movie.title // Set the movie poster if movie.posterPath == nil { // api node has no imagepath cell.imageView!.image = UIImage(named: "noImage") } else { // Set a placeholder before we start the download cell.imageView!.image = UIImage(named: "placeHolder") // get url, let url = TMDBURLs.URLForPosterWithPath(movie.posterPath!) // create task let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in if let error = error { print(error) } if data == nil { return } let image = UIImage(data: data!)! movie.posterImage = image DispatchQueue.main.async { cell.imageView!.image = image } }) // resume task task.resume() } return cell } // MARK: - Parser func moviesFromData(_ data: Data?) -> [Movie] { // No data, return an empty array guard let data = data else { return [] } // Parse the Data into a JSON Object let JSONObject = try! JSONSerialization.jsonObject(with: data) // Insist that this object must be a dictionary guard let dictionary = JSONObject as? [String : Any] else { assertionFailure("Failed to parse data. data.length: \(data.count)") return [Movie]() } // These are the dictionaries that we want to make into movies let movieDictionaries = dictionary[TMDB.Keys.Results] as! [[String : AnyObject]] // This is where we will put the movies. We will return this array. var movies = [Movie]() // For each dictionary... for d in movieDictionaries { // Make a movie... let m = Movie(dictionary: d)! // Put it into the array that we will return movies.append(m) } return movies } }
19ce15a3f921d048c41af309ff6019ce
28.254777
100
0.527977
false
false
false
false
marc-medley/004.45macOS_CotEditorSwiftScripting
refs/heads/master
scripts/02)Tidy/24)Tidy XML (xmllint, 4-space).swift
mit
1
#!/usr/bin/swift // %%%{CotEditorXInput=AllText}%%% // %%%{CotEditorXOutput=ReplaceAllText}%%% import Foundation func setEnvironmentVar(key: String, value: String, overwrite: Bool = false) { setenv(key, value, overwrite ? 1 : 0) } var xmlString: String = "" var i = 0 while true { let line = readLine(strippingNewline: true) if line == nil { break } if line == "" { continue } // `break` or `continue` if let s = line { xmlString.append(s) // uncomment to view input // print("line[\(i)] \(s)") i = i + 1 } } let xmlData = xmlString.data(using: String.Encoding.utf8)! // XMLLINT_INDENT=$' ' xmllint --format --encode utf-8 - // Use `which -a xmllint` to find install location // e.g. /usr/bin/xmllint or /opt/local/bin/xmllint /// full command path required let commandPath = "/usr/bin/xmllint" /// comment/uncomment arguments as needed var args = [String]() args.append("--format") args.append(contentsOf: ["--encode", "utf-8"]) args.append("-") // four spaces setEnvironmentVar(key: "XMLLINT_INDENT", value: " ") let process = Process() process.launchPath = commandPath process.arguments = args let stdinPipe = Pipe() process.standardInput = stdinPipe let stdoutPipe = Pipe() process.standardOutput = stdoutPipe let stderrPipe = Pipe() process.standardError = stderrPipe process.launch() let stdin = stdinPipe.fileHandleForWriting stdin.write(xmlData) stdin.closeFile() let data = stdoutPipe.fileHandleForReading.readDataToEndOfFile() if let output = String(data: data, encoding: String.Encoding.utf8) { // print("STANDARD OUTPUT\n" + output) print(output) } /** Uncomment to include errors in stdout output */ // let dataError = stderrPipe.fileHandleForReading.readDataToEndOfFile() // if let outputError = String(data: dataError, encoding: String.Encoding.utf8) { // print("STANDARD ERROR \n" + outputError) // } process.waitUntilExit() /** Uncomment to include status in stdout output */ // let status = process.terminationStatus // print("STATUS: \(status)")
3d3110de4c7add678e1e65165eb9e6a0
26.648649
81
0.691593
false
false
false
false
KoCMoHaBTa/MHAppKit
refs/heads/master
MHAppKit/Extensions/Foundation/Dictionary+KeysSubscript.swift
mit
1
// // Dictionary+KeysSubscript.swift // MHAppKit // // Created by Milen Halachev on 17.11.20. // Copyright © 2020 Milen Halachev. All rights reserved. // import Foundation extension Dictionary { public subscript<T>(_ keys: T) -> [Value?] where T: Collection, T.Element == Key { return keys.map({ self[$0] }) } public subscript<T>(_ keys: T?) -> [Value?] where T: Collection, T.Element == Key { guard let keys = keys else { return [] } return self[keys] } }
9ba6e20b417ed091168b11172c443f4d
20.222222
87
0.537522
false
false
false
false
bingoogolapple/SwiftNote-PartOne
refs/heads/master
九宫格新/九宫格新/ProductCell.swift
apache-2.0
1
// // ProductCell.swift // 九宫格新 // // Created by bingoogol on 14/9/30. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit protocol ProductCellDelegate : NSObjectProtocol { func productCell(productCell: ProductCell, didSelectedAtIndex index: Int) } class ProductCell: UITableViewCell { let START_INDEX = 100 var delegate:ProductCellDelegate! var cellRow:Int! override init?(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) var w = UIScreen.mainScreen().bounds.width / CGFloat(COL_COUNT) var productBtn:ProductButton for i in 0 ..< COL_COUNT { productBtn = ProductButton.buttonWithType(UIButtonType.Custom) as ProductButton productBtn.frame = CGRectMake(CGFloat(i) * w, 0, w, ROW_HEIGHT) productBtn.tag = START_INDEX + i productBtn.addTarget(self, action: Selector("clickBtn:"), forControlEvents: UIControlEvents.TouchUpInside) self.contentView.addSubview(productBtn) } } func resetButtonWithArray(array:NSArray) { var productBtn:ProductButton var product:Product for i in 0 ..< COL_COUNT { productBtn = self.viewWithTag(START_INDEX + i) as ProductButton if i < array.count { productBtn.hidden = false product = array[i] as Product // UIButton优先显示图片,如果空间不够则只显示图片 productBtn.setImage(product.image, forState: UIControlState.Normal) productBtn.setTitle(product.name, forState: UIControlState.Normal) } else { productBtn.hidden = true } } } func clickBtn(button:UIButton) { if delegate != nil { var index = cellRow * COL_COUNT + button.tag - START_INDEX delegate.productCell(self, didSelectedAtIndex: index) } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
55dd09a41958a80019c1aa1086038442
31.686567
118
0.620091
false
false
false
false
alessiobrozzi/firefox-ios
refs/heads/master
Sync/BatchingClient.swift
mpl-2.0
2
/* 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 Alamofire import Shared import XCGLogger import Deferred open class SerializeRecordFailure<T: CleartextPayloadJSON>: MaybeErrorType { open let record: Record<T> open var description: String { return "Failed to serialize record: \(record)" } public init(record: Record<T>) { self.record = record } } private let log = Logger.syncLogger private typealias UploadRecord = (guid: GUID, payload: String, sizeBytes: Int) private typealias DeferredResponse = Deferred<Maybe<StorageResponse<POSTResult>>> typealias BatchUploadFunction = (_ lines: [String], _ ifUnmodifiedSince: Timestamp?, _ queryParams: [URLQueryItem]?) -> Deferred<Maybe<StorageResponse<POSTResult>>> private let commitParam = URLQueryItem(name: "commit", value: "true") private enum AccumulateRecordError: MaybeErrorType { var description: String { switch self { case .full: return "Batch or payload is full." case .unknown: return "Unknown errored while trying to accumulate records in batch" } } case full(uploadOp: DeferredResponse) case unknown } open class Sync15BatchClient<T: CleartextPayloadJSON> { fileprivate(set) var ifUnmodifiedSince: Timestamp? fileprivate let config: InfoConfiguration fileprivate let uploader: BatchUploadFunction fileprivate let serializeRecord: (Record<T>) -> String? fileprivate var batchToken: BatchToken? // Keep track of the limits of a single batch fileprivate var totalBytes: ByteCount = 0 fileprivate var totalRecords: Int = 0 // Keep track of the limits of a single POST fileprivate var postBytes: ByteCount = 0 fileprivate var postRecords: Int = 0 fileprivate var records = [UploadRecord]() fileprivate var onCollectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp fileprivate func batchQueryParamWithValue(_ value: String) -> URLQueryItem { return URLQueryItem(name: "batch", value: value) } init(config: InfoConfiguration, ifUnmodifiedSince: Timestamp? = nil, serializeRecord: @escaping (Record<T>) -> String?, uploader: @escaping BatchUploadFunction, onCollectionUploaded: @escaping (POSTResult, Timestamp?) -> DeferredTimestamp) { self.config = config self.ifUnmodifiedSince = ifUnmodifiedSince self.uploader = uploader self.serializeRecord = serializeRecord self.onCollectionUploaded = onCollectionUploaded } open func endBatch() -> Success { guard !records.isEmpty else { return succeed() } if let token = self.batchToken { return commitBatch(token) >>> succeed } let lines = self.freezePost() return self.uploader(lines, self.ifUnmodifiedSince, nil) >>== effect(moveForward) >>> succeed } open func addRecords(_ records: [Record<T>]) -> Success { guard !records.isEmpty else { return succeed() } do { // Eagerly serializer the record prior to processing them so we can catch any issues // with record sizes before we start uploading to the server. let serialized = try records.map { try serialize($0) } return addRecords(serialized.makeIterator()) } catch let e { return deferMaybe(e as! MaybeErrorType) } } fileprivate func addRecords(_ generator: IndexingIterator<[UploadRecord]>) -> Success { var mutGenerator = generator while let record = mutGenerator.next() { return accumulateOrUpload(record) >>> { self.addRecords(mutGenerator) } } return succeed() } fileprivate func accumulateOrUpload(_ record: UploadRecord) -> Success { do { // Try to add the record to our buffer try accumulateRecord(record) } catch AccumulateRecordError.full(let uploadOp) { // When we're full, run the upload and try to add the record // after uploading since we've made room for it. return uploadOp >>> { self.accumulateOrUpload(record) } } catch let e { // Should never happen. return deferMaybe(e as! MaybeErrorType) } return succeed() } fileprivate func accumulateRecord(_ record: UploadRecord) throws { guard let token = self.batchToken else { guard addToPost(record) else { throw AccumulateRecordError.full(uploadOp: self.start()) } return } guard fitsInBatch(record) else { throw AccumulateRecordError.full(uploadOp: self.commitBatch(token)) } guard addToPost(record) else { throw AccumulateRecordError.full(uploadOp: self.postInBatch(token)) } addToBatch(record) } fileprivate func serialize(_ record: Record<T>) throws -> UploadRecord { guard let line = self.serializeRecord(record) else { throw SerializeRecordFailure(record: record) } let lineSize = line.utf8.count guard lineSize < Sync15StorageClient.maxRecordSizeBytes else { throw RecordTooLargeError(size: lineSize, guid: record.id) } return (record.id, line, lineSize) } fileprivate func addToPost(_ record: UploadRecord) -> Bool { guard postRecords + 1 <= config.maxPostRecords && postBytes + record.sizeBytes <= config.maxPostBytes else { return false } postRecords += 1 postBytes += record.sizeBytes records.append(record) return true } fileprivate func fitsInBatch(_ record: UploadRecord) -> Bool { return totalRecords + 1 <= config.maxTotalRecords && totalBytes + record.sizeBytes <= config.maxTotalBytes } fileprivate func addToBatch(_ record: UploadRecord) { totalRecords += 1 totalBytes += record.sizeBytes } fileprivate func postInBatch(_ token: BatchToken) -> DeferredResponse { // Push up the current payload to the server and reset let lines = self.freezePost() return uploader(lines, self.ifUnmodifiedSince, [batchQueryParamWithValue(token)]) } fileprivate func commitBatch(_ token: BatchToken) -> DeferredResponse { resetBatch() let lines = self.freezePost() let queryParams = [batchQueryParamWithValue(token), commitParam] return uploader(lines, self.ifUnmodifiedSince, queryParams) >>== effect(moveForward) } fileprivate func start() -> DeferredResponse { let postRecordCount = self.postRecords let postBytesCount = self.postBytes let lines = freezePost() return self.uploader(lines, self.ifUnmodifiedSince, [batchQueryParamWithValue("true")]) >>== effect(moveForward) >>== { response in if let token = response.value.batchToken { self.batchToken = token // Now that we've started a batch, make sure to set the counters for the batch to include // the records we just sent as part of the start call. self.totalRecords = postRecordCount self.totalBytes = postBytesCount } return deferMaybe(response) } } fileprivate func moveForward(_ response: StorageResponse<POSTResult>) { let lastModified = response.metadata.lastModifiedMilliseconds self.ifUnmodifiedSince = lastModified let _ = self.onCollectionUploaded(response.value, lastModified) } fileprivate func resetBatch() { totalBytes = 0 totalRecords = 0 self.batchToken = nil } fileprivate func freezePost() -> [String] { let lines = records.map { $0.payload } self.records = [] self.postBytes = 0 self.postRecords = 0 return lines } }
1d046f2a00d462c21e4ae3d0ed149f13
33.617647
164
0.641219
false
false
false
false
nicksweet/Clink
refs/heads/master
Clink/Classes/PropertyDescriptor.swift
mit
1
// // PropertyDescriptor.swift // Clink // // Created by Nick Sweet on 7/27/17. // import Foundation internal class PropertyDescriptor: NSObject, NSCoding { let name: Clink.PeerPropertyKey let value: Any let characteristicId: String override var description: String { return "name: \(name), value: \(value), characteristicId: \(characteristicId)" } init(name: Clink.PeerPropertyKey, value: Any, characteristicId: String) { self.name = name self.value = value self.characteristicId = characteristicId super.init() } required init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObject(forKey: "name") as? String, let value = aDecoder.decodeObject(forKey: "value"), let characteristicId = aDecoder.decodeObject(forKey: "characteristicId") as? String else { return nil } self.name = name self.value = value self.characteristicId = characteristicId } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") aCoder.encode(value, forKey: "value") aCoder.encode(characteristicId, forKey: "characteristicId") } }
686a3c3c7b2e4f5557e21ea9ba80ae64
26.255319
95
0.615144
false
false
false
false