hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
20e9dff69ab2ca958cf31d1e1f64aa1d36fb089d
179
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing &Range.T{
29.833333
87
0.765363
e5667db5ecdce7872e56358684b8ac3bd2805409
307
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: OS=tvos import MapKit let rect = MKMapRectMake(1.0, 2.0, 3.0, 4.0) // CHECK: {{^}}1.0 2.0 3.0 4.0{{$}} print("\(rect.origin.x) \(rect.origin.y) \(rect.size.width) \(rect.size.height)")
25.583333
81
0.651466
9ba571bfbe1fb9d2a4beb3fe9e097ba9f66d3ba5
1,928
// // Rideau // // Copyright © 2019 Hiroshi Kimura // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(UIKit) import UIKit open class RideauThumbView : UIView { private let shapeLayer: CAShapeLayer = .init() public override init(frame: CGRect) { super.init(frame: .zero) layer.addSublayer(shapeLayer) shapeLayer.fillColor = UIColor(white: 0, alpha: 0.15).cgColor } open override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: 3) } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) shapeLayer.frame = bounds shapeLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: .infinity).cgPath } } #endif
35.054545
87
0.738589
7502a0bad64b8b4f5e22641e6286a465b9349201
636
// // TheMovieDBService.swift // MovieApp // // Created by Firoz Khursheed on 10/12/17. // Copyright © 2017 Firoz Khursheed. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class TheMovieDBService { static func fetchData(fromSavedUrl url: String, parameters: [String: String]? = nil, callback: ((JSON?, Error?) -> Void)?) { Alamofire.request(url, parameters: parameters).validate().responseJSON { response in if let error = response.error { callback?(nil, error) } else { let json = JSON(response.result.value as Any) callback?(json, nil) } } } }
25.44
126
0.663522
bbbf63d5d4c40f6f00e5e738433c84172dabd07e
844
import XCTest import Nimble class BeAnInstanceOfTest: XCTestCase { func testPositiveMatch() { expect(nil as NSNull?).toNot(beAnInstanceOf(NSNull)) expect(NSNull()).to(beAnInstanceOf(NSNull)) expect(NSNumber(integer:1)).toNot(beAnInstanceOf(NSDate)) } func testFailureMessages() { failsWithErrorMessage("expected <nil> to be an instance of NSString") { expect(nil as NSString?).to(beAnInstanceOf(NSString)) } failsWithErrorMessage("expected <__NSCFNumber instance> to be an instance of NSString") { expect(NSNumber(integer:1)).to(beAnInstanceOf(NSString)) } failsWithErrorMessage("expected <__NSCFNumber instance> to not be an instance of NSNumber") { expect(NSNumber(integer:1)).toNot(beAnInstanceOf(NSNumber)) } } }
35.166667
101
0.671801
67615cc205d369840f7867a0eb9eeb81e94bb405
274,042
// // ViewController.swift // MYAlbum // // Created by Chitaranjan Sahu on 07/03/17. // Copyright © 2017 Ithink. All rights reserved. // import UIKit import Photos import AVKit import NYTPhotoViewer import Letters import Alamofire import SDWebImage import DKImagePickerController import NVActivityIndicatorView //import SABlurImageView let SCREENHEIGHT = UIScreen.main.bounds.height let SCREENWIDTH = UIScreen.main.bounds.width let cache = NSCache<NSString, UIImage>() let font = UIFont(name: "Raleway-Light", size: 18) let subfont = UIFont(name: "Raleway-Regular", size: 14) class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDelegateFlowLayout,NVActivityIndicatorViewable,SetPartitionAfterInsideUpload,SaveDescriptionDelegate,autoScrollDelegate,UITextFieldDelegate,SaveCoverTitleDelegate { let MAX : UInt32 = 999999999 let MIN : UInt32 = 1 let TXTMAX : UInt64 = 99999999999999 let TXTMIN : UInt64 = 1 @IBOutlet var keyboardView: UIView! lazy var collectionView :UICollectionView = { let layout = ZLBalancedFlowLayout() layout.setPartitionDelegate = self layout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width , height: UIScreen.main.bounds.height) layout.footerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2) layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) layout.minimumLineSpacing = 2 layout.minimumInteritemSpacing = 2 var collectionView = UICollectionView(frame: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.width, height: self.view.frame.height), collectionViewLayout: layout) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColor.white collectionView.alwaysBounceVertical = true collectionView.bounces = true collectionView.register(UINib(nibName: "ImageCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: self.cellIdentifier) collectionView.register(UINib(nibName: "TextCellStory", bundle: nil), forCellWithReuseIdentifier: self.cellTextIdentifier) collectionView.register(UINib(nibName: "PictureHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView") collectionView.register(UINib(nibName: "FooterReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FotterView") return collectionView }() var editTurnOn = false var upload = false lazy var singleTap: UITapGestureRecognizer = { var singleTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.uploadCoverImageBtnAction)) singleTap.numberOfTapsRequired = 1 return singleTap }() lazy var barButtonActivityIndicator : NVActivityIndicatorView = { var barButtonActivityIndicator = NVActivityIndicatorView.init(frame: CGRect(x:30, y:30, width: 30, height: 30)) barButtonActivityIndicator.type = .semiCircleSpin barButtonActivityIndicator.tintColor = UIColor.white return barButtonActivityIndicator }() var sourceCell :UICollectionViewCell? // after upload collection view scroll var scrollToPostionAfterUpload = 0 lazy var scrollViewForColors :UIScrollView = { var colors = UIScrollView.init(frame: CGRect(x: 0, y: 0, width: SCREENWIDTH - 60, height: self.editToolBar.frame.size.height)) colors.showsVerticalScrollIndicator = false colors.showsHorizontalScrollIndicator = false colors.backgroundColor = UIColor.white // CGSize(width: width, height: self.editToolBar.frame.size.height) return colors }() typealias partitionType = Array<Array<Array<String>>> //UIView *lineView; var cellsToMove0 = NSMutableArray.init() var selectedIndexPath = 0 var colorCodeArray = ["#c6bfe5","#1f1f1f","#686869","#7a797d","#645c64","#19B5FE","#87D37C","#FDE3A7","#EB974E","#6C7A89","#1BA39C"] lazy var editToolBar: UIToolbar = { var edit = UIToolbar(frame: CGRect(x: 0, y: SCREENHEIGHT - 50, width: SCREENWIDTH, height: 50)) return edit }() lazy var autoBarButton:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "Auto", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 0 return element }() lazy var threeToTwo:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "3:2", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 1 return element }() lazy var twoToThree:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "2:3", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 2 return element }() lazy var oneToOne:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "3:1", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 3 return element }() lazy var threeToOne:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "1:1", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 4 return element }() lazy var oneToThree:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "1:3", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 5 return element }() lazy var editToolbarItemDoneshape:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "check"), landscapeImagePhone: UIImage(named: "check"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.turnOnEditMode)) return upload }() lazy var uploadMorePhotoButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "img-album"), landscapeImagePhone: UIImage(named: "img-album"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(morePhotoUpload)) return upload }() lazy var addTextButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "typ-cursor"), landscapeImagePhone: UIImage(named: "typ-cursor"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(addTextCell)) return upload }() lazy var leftAlign:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "AlignL"), landscapeImagePhone: UIImage(named: "AlignL"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(alignTextInTextCell(_:))) upload.tag = 0 return upload }() lazy var centered:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "AlignM"), landscapeImagePhone: UIImage(named: "AlignM"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(alignTextInTextCell(_:))) upload.tag = 1 return upload }() lazy var rightAlign:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "rightA"), landscapeImagePhone: UIImage(named: "rightA"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(alignTextInTextCell(_:))) upload.tag = 2 return upload }() lazy var justify:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "AlignF"), landscapeImagePhone: UIImage(named: "AlignF"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(alignTextInTextCell(_:))) upload.tag = 3 return upload }() lazy var backBarButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "ios-previous"), landscapeImagePhone: UIImage(named: "ios-previous"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.cancelClicked)) return upload }() lazy var moreButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "ios-more"), landscapeImagePhone: UIImage(named: "ios-more"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.dontDoAnything)) return upload }() lazy var shareButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "share"), landscapeImagePhone: UIImage(named: "share"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.dontDoAnything)) return upload }() lazy var editTextCellButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "edit"), landscapeImagePhone: UIImage(named: "edit"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.addTitleToTextCell)) return upload }() lazy var editToolbarItemDone:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "check"), landscapeImagePhone: UIImage(named: "check"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.editToolbarConfigurationForTextCells)) upload.tintColor = UIColor.green return upload }() lazy var coverBarButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "profile-1"), landscapeImagePhone: UIImage(named: "profile-1"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.setCoverPhoto(_:))) return upload }() lazy var shapeBarButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "shape"), landscapeImagePhone: UIImage(named: "shape"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.setToolbarConfigurationForShapeOfCells)) return upload }() // lazy var deleteBarButton1:UIBarButtonItem = { // var upload = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.trash, target: self, action: #selector(ViewController.dontDoAnything)) // // return upload // }() lazy var alignmentButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "AlignM"), landscapeImagePhone: UIImage(named: "AlignM"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.editToolbarConfigurationForTextAlignment)) return upload }() lazy var colorButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "color"), landscapeImagePhone: UIImage(named: "color"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.editToolbarForTextCellColor)) return upload }() lazy var deleteBarButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.trash, target: self, action: #selector(ViewController.deleteSelectedItem(_:))) return upload }() lazy var fixedSpace:UIBarButtonItem = { var upload = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: self, action: #selector(ViewController.dontDoAnything)) return upload }() lazy var flexibleSpace:UIBarButtonItem = { var upload = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) return upload }() lazy var editButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "edit"), landscapeImagePhone: UIImage(named: "edit"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.turnOnEditMode)) return upload }() lazy var closeEdit:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "ui-cross_1"), landscapeImagePhone: UIImage(named: "ui-cross_1"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.closeEditInStory)) return upload }() var cellsToMove1 = NSMutableArray.init() var lineView : UIView = UIView(frame: CGRect.zero) var localPartition = Array<Array<Array<String>>>() let CustomEverythingPhotoIndex = 1, DefaultLoadingSpinnerPhotoIndex = 3, NoReferenceViewPhotoIndex = 4 fileprivate var imageCount : NSNumber = 0 var requestOptions = PHImageRequestOptions() var requestOptionsVideo = PHVideoRequestOptions() fileprivate var videoCount : NSNumber = 0 var mutablePhotos: [ExamplePhoto] = [] var originalIndexPath: IndexPath? var swapImageView: UIImageView? var stopped : Bool = false var storyId :String = "" var storyImageUrl :String = "" var editingTextFieldIndex = Int.init() var selectedItemIndex = Int.init() let defaults = UserDefaults.standard var swapView: UIView? var draggingIndexPath: IndexPath? var frameOfDragingIndexPath : CGPoint? var draggingView: UIView? var coverdata : UIImage? var dragOffset = CGPoint.zero var longPressGesture : UILongPressGestureRecognizer? fileprivate var images = [UIImage](), needsResetLayout = false let PrimaryImageName = "NYTimesBuilding" let PlaceholderImageName = "NYTimesBuildingPlaceholder" fileprivate let cellIdentifier = "ImageCell", headerIdentifier = "header", footerIdentifier = "footer" fileprivate let cellTextIdentifier = "TextCell" var collectionArray = [[AnyHashable:Any]]() var headerView : PictureHeaderCollectionReusableView? var originalYOffset = CGFloat() //storyDetails var creatingStory = false var viewStoryId = 0 var writen_by = "" var story_cover_photo_path = "" var story_cover_photo_code = "" var story_cover_photo_slice_code = "" var story_json = [[String:AnyObject]]() var isViewStory = false var isLoadingStory = true var isFirstTime = false var reloadHeaderView = true var storyTitle = "" var storySubtitle = "" var headerCellTextFieldEditing = false //var pickerController: GMImagePickerCon! // var assets: [DKAsset]? // MARK:- ViewLifeCycle override func viewDidLoad() { super.viewDidLoad() selectedItemIndex = -1 editingTextFieldIndex = -1 defaults.set(false, forKey: "isViewStory") if creatingStory{ defaults.set(true, forKey: "FirstTimeUpload") self.IbaOpenGallery() } defaults.removeObject(forKey: "partition") defaults.removeObject(forKey: "addedMorePhotos") defaults.set(false, forKey: "insideUploads") defaults.synchronize() self.registerForKeyboardNotifications() //flag for story View or not if !isViewStory{ if storyId == ""{ storyId = String(randomNumber()) }else{ isViewStory = true editTurnOn = false self.loadCoverImage(imageUrl: story_cover_photo_path, completion: { (image) in guard let image = image else { self.navigationController?.popViewController(animated: true) return } DispatchQueue.main.async { self.coverdata = image self.isLoadingStory = true var coverImg = [AnyHashable:Any]() coverImg.updateValue(self.story_cover_photo_path, forKey: "cloudFilePath") coverImg.updateValue(0, forKey: "cover") coverImg.updateValue(self.story_cover_photo_path, forKey: "filePath") //coverImg.updateValue( (dataArray.first?["color_codes"]!)! , forKey: "hexCode") // uploadData[0].updateValue("#322e20,#d3d5db,#97989d,#aeb2b9,#858176" as AnyObject, forKey: "hexCode") let height = self.coverdata?.size.height let width = self.coverdata?.size.width let sizeImage = CGSize(width: width!, height: height!) coverImg.updateValue(sizeImage, forKey: "item_size") coverImg.updateValue(self.story_cover_photo_path, forKey: "item_url") coverImg.updateValue("img", forKey: "type") self.collectionArray.append(coverImg) self.view.addSubview(self.collectionView) self.collectionView.reloadData() self.setUI() } self.getDetailStoryWithId(storyId: self.storyId) { runOnMainThread { self.swapView = UIView(frame: CGRect.zero) self.swapImageView = UIImageView(image: UIImage(named: "Swap-white")) self.isViewStory = true self.isLoadingStory = false self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() } } }) } }else{ //not view } } override func viewWillAppear(_ animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { self.creatingStory = false self.editTurnOn = false self.upload = false NotificationCenter.default.removeObserver(self) self.deRegisterForKeyboardNotifications() } func loadCoverImage(imageUrl:String,completion: @escaping ((_ data: UIImage?) -> Void)) { if let cachedVersion = cache.object(forKey: "\(imageUrl)" as NSString) { completion(cachedVersion) }else{ let manager: SDWebImageManager = SDWebImageManager.shared() manager.imageDownloader?.downloadImage(with: URL(string: imageUrl), options: [], progress: { (receivedSize, expectedSize, url) in }, completed: { (image, data, error, finished) in if error != nil{ completion(nil) } guard let data = data, error == nil else { return } guard let image = image, error == nil else { return } cache.setObject(image, forKey: "\(imageUrl)" as NSString) completion(image) }) } } func setCoverPhoto(_ sender: UIBarButtonItem) { let alertView = UIAlertController(title: "Cover photo", message: "Do you want to use this photo as the cover photo of your album.", preferredStyle: .alert) let action = UIAlertAction(title: "Yes", style: .default, handler: { (alert) in if let headerAttributes = self.collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)){ let data = self.collectionArray[self.selectedItemIndex] if let story_cover_photo_path = data["item_url"] as? String { var url = story_cover_photo_path var urlImage = url.components(separatedBy: "album") let totalPath = URLConstants.imgDomain if urlImage.count == 2 { let second = urlImage[1] url = totalPath + second }else{ if let first = urlImage.first{ url = totalPath + first } } self.story_cover_photo_path = url //url = totalPath + (urlImage?[1])! var version = url.components(separatedBy: "compressed") var afterAppending = url.components(separatedBy: "compressed") var widthImage = (version.first)! + "1080" + (afterAppending[1]) DispatchQueue.global(qos: .background).async { self.headerView?.iboHeaderImage.sd_setImage(with: URL(string: widthImage), placeholderImage: UIImage(named: ""), options: SDWebImageOptions.progressiveDownload, completed: { (image, data, error, finished) in guard let image = image else { return } print("Image loaded!") self.headerView?.iboHeaderImage.contentMode = UIViewContentMode.scaleAspectFill self.headerView?.iboHeaderImage.image = image self.coverdata = image DispatchQueue.main.async { self.collectionView.reloadData() self.collectionView.setContentOffset(CGPoint(x: 0, y: (headerAttributes.frame.origin.x)), animated: true) } }) } } self.collectionView.setContentOffset(CGPoint(x: 0, y: (headerAttributes.frame.origin.x)), animated: true) } }) let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { (alert) in }) alertView.addAction(action) alertView.addAction(cancel) self.present(alertView, animated: true, completion: nil) } // MARK:-shape images func setToolbarConfigurationForShapeOfCells() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } self.editToolBar.items = [autoBarButton,fixedSpace,threeToTwo,fixedSpace,twoToThree,fixedSpace,oneToOne,flexibleSpace,threeToOne,flexibleSpace,oneToThree,flexibleSpace,editToolbarItemDoneshape] } func setBackgroundColorForTextCell(_ sender:UIButton) { let hexCodeBg = self.colorCodeArray[sender.tag] self.collectionArray[self.selectedItemIndex]["backgroundColor"] = hexCodeBg guard let cell = self.collectionView.cellForItem(at: IndexPath(item: selectedItemIndex, section: 0)) as? TextCellStoryCollectionViewCell else{return} let screenshotOfTextCell = screenShotOfView(of: cell) if let TextCell = screenshotOfTextCell{ self.collectionArray[selectedIndexPath].updateValue(TextCell, forKey: "text_image") } DispatchQueue.main.async { self.collectionView.reloadItems(at: [IndexPath(item: self.selectedItemIndex, section: 0)]) } } func alignTextInTextCell(_ sender: UIBarButtonItem) { switch sender.tag { case 0: self.collectionArray[self.selectedItemIndex]["textAlignment"] = 0 case 1: self.collectionArray[self.selectedItemIndex]["textAlignment"] = 1 case 2: self.collectionArray[self.selectedItemIndex]["textAlignment"] = 2 case 3: self.collectionArray[self.selectedItemIndex]["textAlignment"] = 3 default: break } guard let cell = self.collectionView.cellForItem(at: IndexPath(item: selectedItemIndex, section: 0)) as? TextCellStoryCollectionViewCell else{return} let screenshotOfTextCell = screenShotOfView(of: cell) if let TextCell = screenshotOfTextCell{ self.collectionArray[selectedIndexPath].updateValue(TextCell, forKey: "text_image") } DispatchQueue.main.async { self.collectionView.reloadItems(at: [IndexPath(item: self.selectedItemIndex, section: 0)]) } } func changeAspectRatioOfSelectedItem(_ sender: UIBarButtonItem) { let item = self.collectionArray[self.selectedItemIndex] let oldSizeString = item["original_size"] as! CGSize // let oldSize = CGSizeFromString(oldSizeString) let newWidth = oldSizeString.width let newHeight = oldSizeString.height let squaredVal = newWidth * newHeight var newlySize = CGSize.init() if sender.tag == 0 { newlySize = oldSizeString }else if sender.tag == 1{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal/6), widthConstant: 3, heightConstant: 2) as! CGSize }else if sender.tag == 2{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal/6), widthConstant: 2, heightConstant: 3) as! CGSize }else if sender.tag == 3{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal), widthConstant: 1, heightConstant: 1) as! CGSize }else if sender.tag == 4{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal/3), widthConstant: 3, heightConstant: 1) as! CGSize }else if sender.tag == 5{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal/3), widthConstant: 1, heightConstant: 3) as! CGSize } self.collectionArray[self.selectedItemIndex]["item_size"] = newlySize // self.collectionArray[self.selectedItemIndex] = newObj DispatchQueue.main.async { UIView.animate(withDuration: 2.0) { // self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() } } } func deleteSelectedItem(_ sender: UIBarButtonItem) { let alertView = UIAlertController(title: "Delete item", message: "Are you sure you wish to delete this item?", preferredStyle: .alert) let action = UIAlertAction(title: "Delete", style: .default, handler: { (alert) in DispatchQueue.main.async { self.title = "" self.collectionArray.remove(at: self.selectedItemIndex) let singletonArray = self.getSingletonArray() let obj = singletonArray[self.selectedItemIndex] let keys = obj.components(separatedBy: "-") var rowArray = self.localPartition[Int(keys.first!)!] var colArray = rowArray[Int(keys[1])!] colArray.remove(at: colArray.count - 1) if colArray.count > 0{ rowArray[Int(keys[1])!] = colArray self.localPartition[Int(keys.first!)!] = rowArray }else{ rowArray.remove(at: Int(keys[1])!) if rowArray.count > 0 { self.localPartition[Int(keys.first!)!] = rowArray }else{ self.localPartition.remove(at: Int(keys.first!)!) if let first = Int(keys.first!){ for i in first ..< self.localPartition.count{ var rowArray = self.localPartition[i] for j in 0 ..< rowArray.count{ var colArray = rowArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } rowArray[j] = colArray } self.localPartition[i] = rowArray } } } } self.defaults.set(self.localPartition, forKey: "partition") self.collectionView.performBatchUpdates({ let selectedIndex = IndexPath(item: self.selectedItemIndex, section: 0) self.collectionView.deleteItems(at: [selectedIndex]) }, completion: { (flag) in self.selectedItemIndex = -1 let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() self.setInitialToolbarConfiguration() }) } }) let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { (alert) in }) alertView.addAction(action) alertView.addAction(cancel) self.present(alertView, animated: true, completion: nil) } func textFieldDidBeginEditing(_ textField: UITextField) { if textField.tag == 98 || textField.tag == 99{ headerCellTextFieldEditing = true } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.tag == 99{ self.headerView?.iboSubTitle.becomeFirstResponder() //textField.becomeFirstResponder() } if textField.tag == 98{ textField.resignFirstResponder() } return true } func textFieldDidEndEditing(_ textField: UITextField) { if textField.tag == 98{ if textField.hasText{ storySubtitle = textField.text! } headerCellTextFieldEditing = false } else if textField.tag == 99{ if textField.hasText { storyTitle = textField.text! } headerCellTextFieldEditing = false } } func randomNumber() -> Int { var random_number = Int(arc4random_uniform(MAX) + MIN) print ("random = ", random_number); return random_number } func generateTextId() -> String{ var rnd : UInt64 = TXTMIN arc4random_buf(&rnd, MemoryLayout.size(ofValue: rnd)) return String(rnd % TXTMAX) } func addTitleToTextCell() { let textViewController = storyboard?.instantiateViewController(withIdentifier: "TextViewController") as! TextViewController textViewController.delegate = self textViewController.titleText = self.collectionArray[self.selectedItemIndex]["title"] as! String textViewController.subTitleText = self.collectionArray[self.selectedItemIndex]["description"] as! String //self.collectionArray[selectedIndex]["title"] = title // self.collectionArray[selectedIndex]["description"] = subtitle textViewController.selectedIndex = self.selectedItemIndex self.present(textViewController, animated: true, completion: nil) } func saveDescriptionDidFinish(_ controller:TextViewController,title:String,subtitle:String,indexToUpdate selectedIndex:Int) { self.collectionArray[selectedIndex]["title"] = title self.collectionArray[selectedIndex]["description"] = subtitle let titleHeight = title.height(withConstrainedWidth: SCREENWIDTH - 20, font: font!) let subtitle = subtitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: subfont!) let total = CGFloat(80) + titleHeight + subtitle var size = self.collectionArray[selectedIndex]["item_size"] as! CGSize size.height = total self.collectionArray[selectedIndex]["item_size"] = size selectedItemIndex = -1 if(selectedItemIndex != selectedIndex){ var previousSelected = selectedItemIndex selectedItemIndex = selectedIndex if previousSelected != -1{ } } DispatchQueue.main.async { self.collectionView.performBatchUpdates({ self.collectionView.reloadItems(at: [IndexPath(item: selectedIndex, section: 0)]) }) { (test) in } } } func setUI() { self.fixedSpace.width = 20 DispatchQueue.main.async { self.navigationController?.navigationBar.isHidden = false self.navigationController?.isNavigationBarHidden = false self.navigationController?.navigationBar.setBackgroundImage(UIImage.init(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage.init() self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.navigationBar.backgroundColor = UIColor.clear self.navigationController?.navigationBar.alpha = 1 self.navigationController?.setNavigationBarHidden(false, animated: true) self.navigationItem.setLeftBarButton(self.backBarButton, animated: true) self.navigationItem.leftBarButtonItem?.isEnabled = true self.navigationItem.setHidesBackButton(false, animated: true) self.navigationItem.setRightBarButtonItems([self.moreButton,self.shareButton,self.editButton], animated: true) self.navigationController?.navigationBar.tintColor = UIColor.white self.setNeedsStatusBarAppearanceUpdate() self.navigationController?.navigationBar.barTintColor = UIColor.white } } func morePhotoUpload() { if self.localPartition.count > 0{ defaults.set(true, forKey: "insideUploads") }else{ defaults.set(false, forKey: "insideUploads") } self.showImagePicker() } func setPartitionAfterInsideUpload() { if let local = defaults.object(forKey: "partition") as? partitionType{ self.localPartition = local } } func setNavigationBarForViewMode() { self.editToolBar.alpha = 0 let tranction = CATransition() tranction.duration = 0.5 tranction.type = kCATransitionReveal tranction.subtype = kCATransitionFromBottom tranction.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) self.editToolBar.layer.add(tranction, forKey: "slideInFromBottomTransition") CATransaction.setCompletionBlock({ self.editToolBar.removeFromSuperview() }) // self.title = "" self.navigationController?.setNavigationBarHidden(false, animated: true) //[self.navigationController setNavigationBarHidden:NO]; self.navigationItem.setLeftBarButton(backBarButton, animated: true) self.navigationController?.setNavigationBarHidden(false, animated: true) self.navigationItem.setRightBarButtonItems([moreButton,shareButton,editButton], animated: false) self.navigationController?.navigationBar.tintColor = UIColor.white } func giveGridFrame(index: Int,frame: [String]) -> CGRect{ var rectArray = frame.map { CGRectFromString($0) } return rectArray[index] } func giveFramesFrame(index: Int,framesFrame: [String]) -> CGRect { var rectArray = framesFrame.map { CGRectFromString($0) } return rectArray[index] } func giveKeyForValue(key:String,index:Int) -> Any { var temp = self.collectionArray[index] return temp[key] } enum ImagePosition { case LEFT case BOTTOM(Int) case NOTDEFIND } func compareReturnLeftOrBottom(parant:String,child:String) -> ImagePosition { var parantKeys = parant.components(separatedBy: "-") var childKeys = child.components(separatedBy: "-") if parantKeys[0] == childKeys[0]{ if parantKeys[1] < childKeys[1]{ return .LEFT }else{ if parantKeys[2] < childKeys[2]{ return .BOTTOM(Int(childKeys[1])!) }else{ return .NOTDEFIND } } }else{ return .NOTDEFIND } } func postDataForStoryMaking() { var id = [String]() var frmaes = defaults.object(forKey: "Frames") as! [String] print("frmaes\(frmaes)") var FramesForEachRow = defaults.object(forKey: "FramesForEachRow") as! [String] print("FramesForEachRow\(FramesForEachRow)") //self.localPartition for (index,element) in self.collectionArray.enumerated(){ var element_id = element["photo_id"] as! String id.append(element_id) } let singleArray = self.getSingletonArray() var storyJsonDictonary = [[AnyHashable:Any]]() var gridHeight = 0 var gridTop = CGFloat(0) var countNoOfElement = 0 for (index,element) in self.localPartition.enumerated(){ var gridHeightDict = [AnyHashable:Any]() gridHeightDict.updateValue(gridTop, forKey: "top") gridHeightDict.updateValue(0, forKey: "left") var giveGridFrame = self.giveGridFrame(index: index, frame: FramesForEachRow) gridHeightDict.updateValue(giveGridFrame.size.height, forKey: "height") var itemsDict = [[AnyHashable:Any]]() var parant = element[0].first for(index1,element1) in element.enumerated(){ var heightForTop = CGFloat(0) var widthForLeft = CGFloat(0) for(index2,element2) in element1.enumerated(){ if element1.count > 1 && index2 > 0{ parant = element1.first } var items = [AnyHashable:Any]() let frame = self.giveFramesFrame(index: countNoOfElement, framesFrame: frmaes) let type = self.giveKeyForValue(key: "type", index: countNoOfElement) let original_size = self.giveKeyForValue(key: "original_size", index: countNoOfElement) let url = self.giveKeyForValue(key: "item_url", index: countNoOfElement) as? String ?? "" var image_Path = "" if url.contains("http"){ image_Path = url }else{ image_Path = URLConstants.imgDomain + url } // let original_height = self.giveKeyForValue(key: "dh", index: countNoOfElement) guard let typeElement = type as? String else { return } var width_CGFloat = CGFloat.init() var height_CGFloat = CGFloat.init() var factor = CGFloat.init() if typeElement == "Text"{ width_CGFloat = SCREENWIDTH height_CGFloat = (CGSizeFromString(original_size as! String).height) }else if typeElement == "video"{ let item_size = self.giveKeyForValue(key: "item_size", index: countNoOfElement) let cgsize = item_size as! CGSize width_CGFloat = cgsize.width height_CGFloat = cgsize.height factor = width_CGFloat / height_CGFloat }else{ width_CGFloat = CGFloat((original_size as! CGSize).width) height_CGFloat = CGFloat((original_size as! CGSize).height) factor = width_CGFloat / height_CGFloat } if index1 == 0 && index2 == 0 { if typeElement == "Text"{ items.updateValue(0, forKey: "left") items.updateValue(0, forKey: "top") items.updateValue(id[countNoOfElement], forKey: "id") items.updateValue(id[countNoOfElement], forKey: "imagePath") items.updateValue(frame.size.width, forKey: "width") items.updateValue(frame.size.height, forKey: "height") items.updateValue("txt", forKey: "type") let title = self.giveKeyForValue(key: "title", index: countNoOfElement) as? String ?? "" let sub = self.giveKeyForValue(key: "description", index: countNoOfElement) as? String ?? "" let textAlignment = self.giveKeyForValue(key: "textAlignment", index: countNoOfElement) as? Int ?? 1 let backgroundColor = self.giveKeyForValue(key: "backgroundColor", index: countNoOfElement) as? String ?? "#ffffff" items.updateValue(title, forKey: "title") items.updateValue(sub, forKey: "description") items.updateValue(textAlignment, forKey: "textAlignment") items.updateValue("\(width_CGFloat)", forKey: "dw") items.updateValue(backgroundColor, forKey: "backgroundColor") items.updateValue("\(height_CGFloat)", forKey: "dh") // items.updateValue("\(factor)", forKey: "factor") // items.updateValue(color, forKey: "color") items.updateValue("", forKey: "below") }else{ items.updateValue(0, forKey: "left") items.updateValue(0, forKey: "top") items.updateValue(id[countNoOfElement], forKey: "id") items.updateValue(image_Path, forKey: "imagePath") items.updateValue(frame.size.width, forKey: "width") items.updateValue(frame.size.height, forKey: "height") items.updateValue(type, forKey: "type") items.updateValue("\(width_CGFloat)", forKey: "dw") items.updateValue("\(height_CGFloat)", forKey: "dh") items.updateValue("\(factor)", forKey: "factor") if typeElement != "video"{ let color = self.giveKeyForValue(key: "hexCode", index: countNoOfElement) items.updateValue(color, forKey: "color") } items.updateValue("", forKey: "below") } }else{ // var sourseKeys = element2.components(separatedBy: "-") var leftOrBottom = self.compareReturnLeftOrBottom(parant: parant!, child: element2) switch leftOrBottom { case .LEFT: let leftFrame = self.giveFramesFrame(index: countNoOfElement - 1, framesFrame: frmaes) widthForLeft += leftFrame.size.width items.updateValue(widthForLeft, forKey: "left") items.updateValue(0, forKey: "top") items.updateValue(id[countNoOfElement], forKey: "id") items.updateValue(image_Path, forKey: "imagePath") items.updateValue(frame.size.width, forKey: "width") items.updateValue(frame.size.height, forKey: "height") items.updateValue(type as! String, forKey: "type") items.updateValue("\(width_CGFloat)", forKey: "dw") items.updateValue("\(height_CGFloat)", forKey: "dh") items.updateValue(factor, forKey: "factor") if typeElement != "video"{ let color = self.giveKeyForValue(key: "hexCode", index: countNoOfElement) items.updateValue(color, forKey: "color") } items.updateValue("", forKey: "below") break case .BOTTOM(let postion): let index = singleArray.index(of: parant!) print(index) //let ph = self.giveKeyForValue(key: "photo_id", index: index) let photo_id = self.giveKeyForValue(key: "photo_id", index: index!) heightForTop += frame.size.height items.updateValue(widthForLeft, forKey: "left") items.updateValue(heightForTop, forKey: "top") items.updateValue(id[countNoOfElement], forKey: "id") items.updateValue(image_Path, forKey: "imagePath") items.updateValue(frame.size.width, forKey: "width") items.updateValue(frame.size.height, forKey: "height") items.updateValue(type as! String, forKey: "type") items.updateValue("\(width_CGFloat)", forKey: "dw") items.updateValue("\(height_CGFloat)", forKey: "dh") items.updateValue(factor, forKey: "factor") if typeElement != "video"{ let color = self.giveKeyForValue(key: "hexCode", index: countNoOfElement) items.updateValue(color, forKey: "color") } items.updateValue(photo_id as! String, forKey: "below") print(postion) break case .NOTDEFIND: break } } countNoOfElement += 1 print("singke element\(gridHeightDict)") print(element2) itemsDict.append(items) } } gridHeightDict.updateValue(itemsDict, forKey: "items") gridTop += giveGridFrame.size.height print("grid element\(gridHeightDict)") storyJsonDictonary.append(gridHeightDict) } print("grid element\(storyJsonDictonary)") do { let jsonData = try JSONSerialization.data(withJSONObject: storyJsonDictonary, options: .prettyPrinted) // here "jsonData" is the dictionary encoded in JSON data let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) var storyJSON = String.init(data: jsonData, encoding: String.Encoding.utf8) self.postStoryData(storyDataTosend: storyJSON!) } catch { print(error.localizedDescription) } } func dontDoAnything() { } func saveCoverTitleDidFinish(_ controller:CoverTitleViewEditViewController,title:String,subtitle:String) { if let header = self.headerView{ storyTitle = title storySubtitle = subtitle header.iboTitle.text = title header.iboSubTitle.text = subtitle } } func uploadCoverImageBtnAction() { var coverViewController = self.storyboard?.instantiateViewController(withIdentifier: "CoverTitleViewEditViewController") as! CoverTitleViewEditViewController coverViewController.delegate = self if let header = self.headerView{ coverViewController.coverImageView = self.coverdata if header.iboTitle.hasText{ coverViewController.titleText = header.iboTitle.text! } if header.iboSubTitle.hasText{ coverViewController.subTitleText = header.iboSubTitle.text! } } self.present(coverViewController, animated: true, completion: nil) } func appendStroyIdAnddetails(Params: inout [String:String]) { for (index,element) in self.collectionArray.enumerated(){ if (element["type"] as! String) != "Text"{ Params.updateValue(element["photo_id"] as! String, forKey: "story_photo[\(index)][photo_id]") let imgurl = element["item_url"] as! String let totalPath = URLConstants.imgDomain var url = "" var urlImage = imgurl.components(separatedBy: "album") if urlImage.count == 2 { var second = urlImage[1] second.remove(at: second.startIndex) url = totalPath + second }else{ let first = urlImage[0] url = totalPath + first } Params.updateValue(url , forKey: "story_photo[\(index)][photo_path]") if (element["type"] as! String) != "video"{ Params.updateValue(element["hexCode"] as! String, forKey: "story_photo[\(index)][color_codes]") } } // print(Params) } // return Params } func turnOnEditMode() { self.navigationItem.leftBarButtonItem = nil self.navigationItem.setHidesBackButton(true, animated: true) self.navigationItem.rightBarButtonItems = nil self.title = "Edit and enrich" self.navigationItem.setRightBarButton(closeEdit, animated: true) self.setInitialToolbarConfiguration() self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress)) self.collectionView.addGestureRecognizer(self.longPressGesture!) editTurnOn = true isViewStory = false if self.isFirstTime{ }else{ if self.collectionView.visibleCells.count == 0 { self.collectionView.scrollToItem(at: IndexPath(item: scrollToPostionAfterUpload, section: 0), at: .centeredVertically, animated: true) } } headerView?.iboHeaderImage.addGestureRecognizer(singleTap) } func closeEditInStory() { self.postDataForStoryMaking() //self.navigationController?.navigationBar.tintColor = UIColor.black self.setNavigationBarForViewMode() self.collectionView.removeGestureRecognizer(self.longPressGesture!) headerView?.iboHeaderImage.removeGestureRecognizer(singleTap) //selectedItemIndex = -1 } @IBAction func doneClicked(_ sender: UIButton) { if headerCellTextFieldEditing{ if let headerView = self.headerView{ UIView.animate(withDuration: 0.2, animations: { headerView.titleView.frame = CGRect(x: headerView.titleView.frame.origin.x, y: self.originalYOffset, width: headerView.titleView.frame.size.width, height: headerView.titleView.frame.size.height) }) } } sender.resignFirstResponder() self.view.endEditing(true) } @IBAction func dismissViewClicked(_ sender: UIBarButtonItem) { self.navigationController?.dismiss(animated: true, completion: nil) } func startAnimation(){ let size = CGSize(width: 30, height:30) startAnimating(size, message: "Loading...", type: NVActivityIndicatorType.ballScaleRipple) } func stopAnimationLoader() { stopAnimating() } func addTextCell() { editToolBar.isUserInteractionEnabled = true var visibleIndexPath = self.collectionView.indexPathsForVisibleItems print("addtextCell\(visibleIndexPath.count)") var previousIndexPath = IndexPath.init() if visibleIndexPath.count != 0{ previousIndexPath = (visibleIndexPath[0]) }else{ previousIndexPath = IndexPath(item: 0, section: 0) } print("previu\(previousIndexPath.item)") var singletonArray = self.getSingletonArray() print("si\(singletonArray)") var originalPaths = singletonArray[previousIndexPath.item] var keys = originalPaths.components(separatedBy: "-") var destRow = Int(keys.first!) var text = "\(destRow!)-0-0" var txtCellObj = [String]() txtCellObj.append(text) var objArray = [txtCellObj] var checkObj = "\(destRow!)-0-0" var indexOfNewItem = singletonArray.index(of: checkObj) print("text path\(objArray)") self.localPartition.insert(objArray, at: destRow!) for i in (destRow! + 1) ..< self.localPartition.count{ var destPartArray = self.localPartition[i] for j in 0 ..< destPartArray.count { var colArray = destPartArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } destPartArray[j] = colArray } self.localPartition[i] = destPartArray } defaults.set(localPartition, forKey: "partition") let txtSize = CGSize(width: SCREENWIDTH, height: 200) var textDict = [AnyHashable:Any]() textDict.updateValue("Text", forKey: "type") textDict.updateValue(txtSize, forKey: "item_size") textDict.updateValue(NSStringFromCGSize(txtSize), forKey: "original_size") let generatedId = generateTextId() textDict.updateValue(generatedId, forKey: "id") textDict.updateValue(generatedId, forKey: "photo_id") textDict.updateValue(generatedId, forKey: "imagePath") textDict.updateValue("#FFFFFF", forKey: "backgroundColor") textDict.updateValue("#000000", forKey: "textColor") textDict.updateValue(1, forKey: "textAlignment") textDict.updateValue(false, forKey: "cover") textDict.updateValue("", forKey: "title") textDict.updateValue("", forKey: "description") self.collectionArray.insert(textDict, at: indexOfNewItem!) //self.collectionArray[indexOfNewItem!] = textDict editingTextFieldIndex = indexOfNewItem! selectedItemIndex = indexOfNewItem! self.collectionView.performBatchUpdates({ self.collectionView.insertItems(at: [IndexPath(item: indexOfNewItem!, section: 0)]) }, completion: { (flag) in self.collectionView.scrollToItem(at: IndexPath(item: indexOfNewItem!, section: 0), at: UICollectionViewScrollPosition.top, animated: true) self.editToolbarConfigurationForTextCells() //self.initialiseColorCodeArray guard let TextCell = self.collectionView.cellForItem(at: IndexPath(item: indexOfNewItem!, section: 0)) as? TextCellStoryCollectionViewCell else{ return } TextCell.titleLabel.placeholder = "Title" TextCell.subTitleLabel.placeholder = "Enter your story here" // TextCell.titleLabel.inputAccessoryView = self.keyboardView //TextCell.subTitleLabel.inputAccessoryView = self.keyboardView //TextCell.titleLabel.becomeFirstResponder() self.editToolBar.isUserInteractionEnabled = true }) } func setInitialToolbarConfiguration() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } self.editToolBar.items = [uploadMorePhotoButton,addTextButton] self.editToolBar.tintColor = UIColor(hexString:"#15181B") if !editToolBar.isDescendant(of: self.view){ // self.view.addSubview(self.editToolBar) // CATransition *transition = [CATransition animation]; // transition.duration = 0.5; // transition.type = kCATransitionPush; // transition.subtype = kCATransitionFromLeft; // [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]]; // [parentView.layer addAnimation:transition forKey:nil]; // // [parentView addSubview:myVC.view]; self.editToolBar.alpha = 1 let tranction = CATransition() tranction.duration = 0.5 tranction.type = kCATransitionMoveIn tranction.subtype = kCATransitionFromTop tranction.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) tranction.fillMode = kCAFillModeRemoved self.editToolBar.layer.add(tranction, forKey: "slideInFromTopTransition") self.view.addSubview(self.editToolBar) CATransaction.setCompletionBlock({ }) } } func editToolbarConfigurationForTextAlignment() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } self.editToolBar.items = [leftAlign,fixedSpace,centered,fixedSpace,rightAlign,fixedSpace,justify,flexibleSpace,editToolbarItemDone] self.editToolBar.tintColor = UIColor(red: 21/255, green: 24/255, blue: 27/255, alpha: 1) } func editToolbarForTextCellColor() { self.editToolBar.items = nil self.editToolBar.items = [flexibleSpace,editToolbarItemDone] self.addScrollViewToToolbarWithItemsArray() self.editToolBar.tintColor = UIColor(red: 21/255, green: 24/255, blue: 27/255, alpha: 1) } func addScrollViewToToolbarWithItemsArray() { var width = CGFloat(40 * self.colorCodeArray.count) scrollViewForColors.contentSize = CGSize(width: width, height: self.editToolBar.frame.size.height) var xCoordinate = 10 for i in 0 ..< self.colorCodeArray.count{ let hexCode = self.colorCodeArray[i] let colorButtonText = UIButton.init(frame: CGRect(x: xCoordinate, y: 15, width: 30, height: 30)) colorButtonText.layer.cornerRadius = 15 colorButtonText.tag = i colorButtonText.backgroundColor = UIColor(hexString: hexCode) colorButtonText.addTarget(self, action: #selector(setBackgroundColorForTextCell(_:)), for: UIControlEvents.touchUpInside) xCoordinate += 40 self.scrollViewForColors.addSubview(colorButtonText) } self.editToolBar.addSubview(scrollViewForColors) } func screenShotOfView(of inputView:UIView) -> UIImage? { UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0) inputView.layer.render(in: UIGraphicsGetCurrentContext()!) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func changeToEnrichMode() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } let dict = self.collectionArray[selectedItemIndex] if let type = dict["type"] as? String{ if type == "video"{ self.editToolBar.items = [flexibleSpace,deleteBarButton] self.title = "Video" }else{ self.editToolBar.items = [coverBarButton,flexibleSpace,shapeBarButton,deleteBarButton] self.title = "Image" } } self.editToolBar.tintColor = UIColor(red: 21/255, green: 24/255, blue: 25/255, alpha: 1) } func editToolbarConfigurationForTextCells() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } self.editToolBar.items = [editTextCellButton,fixedSpace,alignmentButton,fixedSpace,colorButton,fixedSpace,deleteBarButton] self.editToolBar.tintColor = UIColor(hexString:"#15181B") if let cell = self.collectionView.cellForItem(at: IndexPath(item: selectedItemIndex, section: 0)) as? TextCellStoryCollectionViewCell{ let screenshotOfTextCell = screenShotOfView(of: cell) if let TextCell = screenshotOfTextCell{ var temp = self.collectionArray[selectedIndexPath] temp.updateValue(screenshotOfTextCell, forKey: "text_image") } } } //MARK :- ScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.collectionView{ self.headerView?.layoutHeaderViewForScrollViewOffset(offset: scrollView.contentOffset) } } @IBAction func displayStory(_ sender: UIButton) { defaults.set(true, forKey: "viewStory") storyId = "44" getDetailStoryWithId(storyId: storyId) { runOnMainThread { self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress)) self.collectionView.addGestureRecognizer(self.longPressGesture!) self.swapView = UIView(frame: CGRect.zero) self.swapImageView = UIImageView(image: UIImage(named: "Swap-white")) self.view.addSubview(self.collectionView) self.isViewStory = true self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() // let set :IndexSet = [0] // self.collectionView?.reloadSections(set) //self.collectionView?.reloadSections(IndexSet(set)) } } } // MARK:- StoryCalls func getDetailStoryWithId(storyId:String,handler: ((Void) -> Void)?) { let postUrl = URLConstants.BaseURL + "storyDetails/" + storyId Alamofire.request(postUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in switch response.result { case .success(let JSON): print("Success with JSON: \(JSON)") let response = JSON as! NSDictionary let errorCode: AnyObject = response.value(forKeyPath: "error.errorCode") as! NSNumber let errorMSG = response.value(forKeyPath: "error.errorMsg") print("postURL is :", (postUrl), "response is: \(response)", "error code is \(errorCode)") let compareCode: NSNumber = 0 if errorCode as! NSNumber == compareCode{ // if(self.allHomesArray.count == 0){ //print(self.allHomesArray.count) let dataArray = response.value(forKey: "results") as! [String: AnyObject] if let Id = dataArray["story_id"] as! Int?{ self.viewStoryId = Id } if let writen = dataArray["writen_by"] as! String?{ self.writen_by = writen } if let story_cover = dataArray["story_cover_photo_path"] as! String?{ self.story_cover_photo_path = story_cover } if let photo_code = dataArray["story_cover_photo_code"] as! String?{ self.story_cover_photo_code = photo_code } if let photo_code = dataArray["story_cover_photo_slice_code"] as! String?{ self.story_cover_photo_slice_code = photo_code } if let story_heading = dataArray["story_heading"] as! String?{ self.storyTitle = story_heading } if let story_heading_description = dataArray["story_heading_description"] as! String?{ self.storySubtitle = story_heading_description } if let story_json = dataArray["story_json"] as! String?{ let json: AnyObject? = story_json.parseJSONString print("Parsed JSON: \(json!)") self.story_json = json as! [[String:AnyObject]] //story_json.parseJSONString self.populateImage(objects: self.story_json) // story_json // self.story_json = } print(self.story_json) self.getPhoto() handler?() }else { // self.activityLoaderForFirstTime.stopAnimating() // AlertView.showAlert(self, title: "OOPS!", message: errorMSG! as AnyObject) } case .failure(let error): // self.activityLoaderForFirstTime.stopAnimating() print("Request failed with error: \(error)") // Toast.show(error.localizedDescription) // AlertView.showAlert(self, title: "", message: error) } } } //MARK:- KEYBOARD NOTIFICATION func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func deRegisterForKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardNotification(notification: NSNotification) { if let userInfo = notification.userInfo { let endFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw) if let longPressGesture = self.longPressGesture{ self.collectionView.removeGestureRecognizer(longPressGesture) } let offset = SCREENHEIGHT - (endFrame?.height)! + 40 if let hederView = self.headerView{ if (hederView.iboTitle.isFirstResponder) || (hederView.iboSubTitle.isFirstResponder){ originalYOffset = (hederView.titleView.frame.origin.y) let yOffsetHeader = offset - (hederView.titleView.frame.size.height) //let movementDuration:TimeInterval = 0.3 //UIView.beginAnimations( "animateView", context: nil) //UIView.setAnimationBeginsFromCurrentState(true) //UIView.setAnimationDuration(movementDuration ) // UIView.commitAnimations() UIView.animate(withDuration: 0.4, delay: TimeInterval(0), options: animationCurve, animations: { hederView.titleView.frame = CGRect(x: hederView.titleView.frame.origin.x, y: yOffsetHeader, width: hederView.titleView.frame.size.width, height: hederView.titleView.frame.size.height) }, completion: nil) } } } } func keyboardWillHide(notification: NSNotification) { if let longPressGesture = self.longPressGesture{ self.collectionView.addGestureRecognizer(longPressGesture) } } //MARK :- Populate Story func populateImage(objects:[[String:AnyObject]]) { var localpartitionGrid = [[[String]]]() var grid = [[[String]]]() var id = [String]() for (index, element) in objects.enumerated() { let items = element["items"] as! [[String:AnyObject]] var count = 0 for (index, element) in items.enumerated() { id.append(element["id"] as! String) //count += 1 } } var i = 0 self.collectionArray.remove(at: 0) self.localPartition.removeAll(keepingCapacity: true) var partitionGrid = [[String]]() for (indexOut, element) in objects.enumerated() { var partition = [[String]]() if indexOut == 0{} let item = element["items"] as! [[String:AnyObject]] var belowCount = 0 var leftCount = 0 var belowObject = [String]() var search = [String: Int]() for (index, element) in item.enumerated() { var singleObj = [String]() var singleGrid = [String]() var dictToAdd = [AnyHashable:Any]() if let type = element["type"] as? String{ if type == "txt"{ let id = element["id"] as? String ?? "" let imagePath = element["imagePath"] as? String ?? "" // let type = element["type"] as? String ?? "Text" var textTitle = element["title"] as? String ?? "" if textTitle == ""{ textTitle = "EmptyTitle" } var textSubTitle = element["description"] as? String ?? "" if textSubTitle == ""{ textSubTitle = "EmptySubTitle" } // let dw = element["dw"] as! String // let dh = element["dh"] as! String let height = element["height"] as? Int ?? 0 let width = element["width"] as? Int ?? 0 let txtSize = CGSize(width: SCREENWIDTH, height: CGFloat(height)) dictToAdd.updateValue(NSStringFromCGSize(txtSize), forKey: "original_size") let titleHeight = textTitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: font!) let subtitle = textSubTitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: subfont!) let total = CGFloat(80) + titleHeight + subtitle // txtSize.height = total // self.collectionArray[selectedIndex]["item_size"] = total // let original_size = CGSize(width: CGFloat((dw as NSString).floatValue), height: CGFloat((dh as NSString).floatValue)) var item_size = CGSize(width: SCREENWIDTH, height: CGFloat(200)) item_size.height = total dictToAdd.updateValue(id, forKey: "photo_id") dictToAdd.updateValue(imagePath, forKey: "item_url") dictToAdd.updateValue("Text", forKey: "type") let textAlignment = element["textAlignment"] as? Int ?? 1 dictToAdd.updateValue(textAlignment, forKey: "textAlignment") dictToAdd.updateValue("#322e20", forKey: "hexCode") //dictToAdd.updateValue(item_size, forKey: "original_size") dictToAdd.updateValue(item_size, forKey: "item_size") dictToAdd.updateValue(textTitle, forKey: "title") dictToAdd.updateValue(textSubTitle, forKey: "description") // dictToAdd.updateValue("xelpmoc story making processs", forKey: "textColor") dictToAdd.updateValue("#322e20", forKey: "textColor") let backgroundColor = element["backgroundColor"] as? String ?? "#FFFFFF" dictToAdd.updateValue(backgroundColor, forKey: "backgroundColor") singleObj.append("\(i)-\(leftCount)-\(0)") singleGrid.append(id) leftCount += 1 partitionGrid.append(singleGrid) partition.append(singleObj) // dictToAdd.updateValue(color, forKey: "hexCode") }else{ let below = element["below"] as! String if (below == ""){ search.updateValue(index, forKey: element["id"] as! String) let left = element["left"] as! Int if left == Int(0){ singleObj.append("\(i)-\(leftCount)-\(0)") singleGrid.append(element["id"] as! String) leftCount += 1 }else{ singleObj.append("\(i)-\(leftCount)-\(0)") singleGrid.append(element["id"] as! String) leftCount += 1 } partitionGrid.append(singleGrid) partition.append(singleObj) }else{ var index = "" // var indexToNest = id.index(of: below) var countLength = partition.count // var indexToInsert = search[below] belowCount += 1 var tempMiddle = leftCount - 1 partition[countLength-1].append("\(i)-\(tempMiddle)-\(belowCount)") } let id = element["id"] as? String ?? "" let imagePath = element["imagePath"] as? String ?? "" let type = element["type"] as? String ?? "" var dw = element["dw"] as? String ?? "" if dw == "undefined"{ dw = "0" } var dh = element["dh"] as? String ?? "" if dh == "undefined"{ dh = "0" } if let factor = element["factor"] as? AnyObject{ dictToAdd.updateValue("\(factor)", forKey: "factor") } if type != "video"{ let color = element["color"] as? String ?? "" dictToAdd.updateValue(color, forKey: "hexCode") } let height = element["height"] as? Int ?? 0 let width = element["width"] as? Int ?? 0 let original_size = CGSize(width: CGFloat((dw as NSString).floatValue), height: CGFloat((dh as NSString).floatValue)) let item_size = CGSize(width: CGFloat(width), height: CGFloat(height)) dictToAdd.updateValue(id, forKey: "photo_id") dictToAdd.updateValue(imagePath, forKey: "item_url") dictToAdd.updateValue(type, forKey: "type") dictToAdd.updateValue(original_size, forKey: "original_size") dictToAdd.updateValue(item_size, forKey: "item_size") // dictToAdd.updateValue(type, forKey: "type") } } self.collectionArray.append(dictToAdd) } localpartitionGrid.append(partitionGrid) localPartition.append(partition) i += 1 //partition.append(singleObj) } defaults.set(true, forKey: "isViewStory") defaults.set(localPartition, forKey: "partition") } //MARK: - Save Story func postStoryData(storyDataTosend:String) { var paramsDict = [String:String]() paramsDict.updateValue(storyId, forKey: "storyId") paramsDict.updateValue(self.storyTitle, forKey: "story_heading") paramsDict.updateValue(self.storySubtitle, forKey: "story_heading_description") paramsDict.updateValue("Chitaranjan", forKey: "writen_by") paramsDict.updateValue("CH", forKey: "writen_by_name_initials") paramsDict.updateValue("14946557868453", forKey: "writen_by_id") paramsDict.updateValue("chitaranjan", forKey: "writen_by_img") paramsDict.updateValue(story_cover_photo_path, forKey: "story_cover_photo_path") paramsDict.updateValue("#2b2b2a,#d2c6ad,#847f75,#9da29f,#6c86a2", forKey: "story_cover_photo_code") paramsDict.updateValue("#2b2b2a", forKey: "story_cover_photo_slice_code") paramsDict.updateValue(storyDataTosend, forKey: "storyJson") //print(paramsDict) // Params = Params + self.appendStroyIdAnddetails(Params: &paramsDict) //print(paramsDict) let pa = paramsDict as [String : Any] print(pa) var url = URLConstants.BaseURL + "addStory" Alamofire.request(url, method: .post, parameters: pa , encoding: URLEncoding.default, headers: nil) .validate() .responseJSON { (response:DataResponse<Any>) in print(response) switch response.result { case .success(let JSON): print("Success with JSON: \(JSON)") let response = JSON as! NSDictionary print("reee", response) let allKeys : NSArray = response.allKeys as NSArray; let tempVal : Bool = allKeys.contains("error") //retVal = [allKeys containsObject:key]; //return retVal; // if(response.key) if(tempVal == true){ let errorCode: AnyObject = response.value(forKeyPath: "error.errorCode") as! NSNumber let errorMSG = response.value(forKeyPath: "error.errorMsg") let compareCode: NSNumber = 0 if errorCode as! NSNumber == compareCode{ print("sucess") self.editTurnOn = false self.isViewStory = true } else { print("error") } }else{ print("error") AlertView.showAlert(self, title: "currently busy server", message: "Not reachable" as AnyObject) } case .failure(let error): print("Request failed with error: \(error)") AlertView.showAlert(self, title: "currently busy server", message: error as AnyObject) } } } func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) { let location = gestureReconizer.location(in: self.collectionView) switch gestureReconizer.state { case .began: if let local = defaults.object(forKey: "partition") as? partitionType{ localPartition = local } startDragAtLocation(location: location) break case .changed: guard let view = draggingView else { return } let cv = collectionView guard let originalIndexPath = originalIndexPath else {return} // view.center = CGPoint(x: location.x + dragOffset.x, y: location.y + dragOffset.y) var center = view.center center.x = location.x center.y = location.y view.center = center stopped = false scrollIfNeed(snapshotView: view) self.checkPreviousIndexPathAndCalculate(location: center, forScreenShort: view.frame, withSourceIndexPath: originalIndexPath) break case .ended: self.changeToIdentiPosition() editingTextFieldIndex = -1 self.editToolBar.isUserInteractionEnabled = true stopped = true endDragAtLocation(location: location) default: guard let view = draggingView else { return } var center = view.center center.y = location.y center.x = location.x view.center = center // break } } //MARK:- GestureRecognizer Methods func startDragAtLocation(location:CGPoint) { let vc = self.collectionView guard let indexPath = vc.indexPathForItem(at: location) else {return} guard let cell = vc.cellForItem(at: indexPath) else {return} self.sourceCell = cell if(selectedItemIndex != indexPath.item){ let previousSelected = selectedItemIndex selectedItemIndex = indexPath.item if previousSelected != -1{ self.collectionView.reloadItems(at: [IndexPath(item: previousSelected, section: 0)]) } } self.collectionView.performBatchUpdates({ self.collectionView.reloadData() }) { (test) in } self.editToolBar.isUserInteractionEnabled = false let selectedCell = collectionArray[indexPath.item] if let destType = selectedCell["type"] as? String { if destType == "Text"{ self.editToolbarConfigurationForTextCells() }else{ self.changeToEnrichMode() } } frameOfDragingIndexPath = cell.center originalIndexPath = indexPath draggingIndexPath = indexPath draggingView = cell.snapshotView(afterScreenUpdates: true) guard let view = draggingView else { return } view.frame = cell.frame print("center\(cell.center)") var center = cell.center view.center = CGPoint(x: center.x, y: location.y) vc.addSubview(view) view.layer.shadowPath = UIBezierPath(rect: (draggingView?.bounds)!).cgPath view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOpacity = 0.8 view.layer.shadowRadius = 10 view.alpha = 0.3 print("location \(location.y)") cell.alpha = 0.0 cell.isHidden = true UIView.animate(withDuration: 0.2, animations: { print("location \(location.y)") center.y = location.y view.center = CGPoint(x: location.x, y: location.y) if (cell.frame.size.height > SCREENHEIGHT * 0.75 || cell.frame.size.width > SCREENWIDTH * 0.8){ view.transform = CGAffineTransform(scaleX: 0.3, y: 0.3) }else{ view.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) } }) { (end) in } } func checkPreviousIndexPathAndCalculate(location:CGPoint,forScreenShort snapshot:CGRect,withSourceIndexPath sourceIndexPath:IndexPath){ self.changeToIdentiPosition() lineView.removeFromSuperview() self.swapView?.removeFromSuperview() var singletonArray = self.getSingletonArray() if let indexPath = self.collectionView.indexPathForItem(at: location){ guard var sourceCell = self.sourceCell else {return} if let destinationCell = self.collectionView.cellForItem(at: indexPath) { var destinationCellType = self.collectionArray[indexPath.item] var sourceCellType = self.collectionArray[sourceIndexPath.item] if indexPath.item != sourceIndexPath.item{ let topOffset = destinationCell.frame.origin.y + 25 let leftOffset = destinationCell.frame.origin.x + 25 let bottomOffset = destinationCell.frame.origin.y + destinationCell.frame.size.height - 25 let rightOffset = destinationCell.frame.origin.x + destinationCell.frame.size.width - 25 let differenceLeft = location.x - leftOffset let differenceRight = location.x - rightOffset let differenceTop = location.y - topOffset let differenceBottom = location.y - bottomOffset var frmaes = defaults.object(forKey: "FramesForEachRow") as! [String] if let destType = destinationCellType["type"] as? String { if destType != "Text"{ guard let sourceType = sourceCellType["type"] as? String else { return } var keys = singletonArray[indexPath.item].components(separatedBy: "-") if differenceLeft > -25 && differenceLeft < 0 && sourceType != "Text"{ var cellFrame = CGRectFromString(frmaes[Int(keys[0])!]) print("Insert to the left of cell line") lineView.removeFromSuperview() self.swapView?.removeFromSuperview() print("differenceLeft\(differenceLeft)") let xOffset = destinationCell.frame.origin.x print("\(xOffset)in left of the cell line ") let yValue = cellFrame.origin.y print("\(yValue)in left of the cell line ") let nestedWidth = 2.0 let nestedHeight = cellFrame.size.height self.collectionView.performBatchUpdates({ print("height destinationleft \(nestedHeight)") self.lineView.frame = CGRect(x: xOffset, y: yValue, width: CGFloat(nestedWidth), height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) }, completion: { (test) in self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 0) }) // } }else if differenceRight < 25 && differenceRight > 0 && sourceType != "Text"{ var cellFrame = CGRectFromString(frmaes[Int(keys[0])!]) print("Insert to the right of the cell line") print("differenceright\(differenceRight)") lineView.removeFromSuperview() self.swapView?.removeFromSuperview() let xOffset = destinationCell.frame.origin.x + destinationCell.frame.size.width let yValue = cellFrame.origin.y let nestedWidth = 2.0 let nestedHeight = cellFrame.size.height self.collectionView.performBatchUpdates({ print("height destinationright \(nestedHeight)") self.lineView.frame = CGRect(x: xOffset, y: yValue, width: CGFloat(nestedWidth), height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) }, completion: { (test) in self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 0) }) }else if (differenceTop > -20 && differenceTop < 0 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16) && sourceType != "Text"){ print("Insert to the TOP of the cell line") lineView.removeFromSuperview() self.swapView?.removeFromSuperview() let xOffset = destinationCell.frame.origin.x let yValue = destinationCell.frame.origin.y let nestedWidth = destinationCell.frame.size.width let nestedHeight = 2.0 self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: CGFloat(nestedWidth), height: CGFloat(nestedHeight)) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) }, completion: { (test) in self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }) }else if(differenceBottom > 0 && differenceBottom < 20 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16) && sourceType != "Text"){ print("Insert to the Bottom of the cell line") lineView.removeFromSuperview() self.swapView?.removeFromSuperview() let xOffset = destinationCell.frame.origin.x let yValue = destinationCell.frame.origin.y + destinationCell.frame.size.height + 2 let nestedWidth = destinationCell.frame.size.width let nestedHeight = 2.0 self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: CGFloat(nestedWidth), height: CGFloat(nestedHeight)) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) }, completion: { (test) in self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }) }else{ let dict = self.collectionArray[(originalIndexPath?.item)!] if let type = dict["type"] as? String{ if type != "Text"{ self.lineView.removeFromSuperview() self.swapView?.removeFromSuperview() self.collectionView.performBatchUpdates({ self.swapView?.frame = destinationCell.contentView.bounds self.swapView?.backgroundColor = UIColor.black self.swapView?.alpha = 0.6 self.swapImageView?.center = CGPoint(x: (self.swapView?.frame.size.width)! / 2, y: (self.swapView?.frame.size.height)! / 2) self.swapView?.addSubview(self.swapImageView!) destinationCell.contentView.addSubview(self.swapView!) }, completion: { (boolTest) in }) }else{ let delta: CGFloat = 0.00001 if abs(sourceCell.frame.size.width - destinationCell.frame.size.width) < delta { self.lineView.removeFromSuperview() self.swapView?.removeFromSuperview() self.collectionView.performBatchUpdates({ self.swapView?.frame = destinationCell.contentView.bounds self.swapView?.backgroundColor = UIColor.black self.swapView?.alpha = 0.6 self.swapImageView?.center = CGPoint(x: (self.swapView?.frame.size.width)! / 2, y: (self.swapView?.frame.size.height)! / 2) self.swapView?.addSubview(self.swapImageView!) destinationCell.contentView.addSubview(self.swapView!) }, completion: { (boolTest) in }) }else{ self.lineView.removeFromSuperview() } } } } }else{ if (sourceCell.frame.size.width == destinationCell.frame.size.width){ self.lineView.removeFromSuperview() self.swapView?.removeFromSuperview() self.collectionView.performBatchUpdates({ self.swapView?.frame = destinationCell.contentView.bounds self.swapView?.backgroundColor = UIColor.black self.swapView?.alpha = 0.6 self.swapImageView?.center = CGPoint(x: (self.swapView?.frame.size.width)! / 2, y: (self.swapView?.frame.size.height)! / 2) self.swapView?.addSubview(self.swapImageView!) destinationCell.contentView.addSubview(self.swapView!) }, completion: { (boolTest) in }) }else{ self.lineView.removeFromSuperview() } } } } else{ self.lineView.removeFromSuperview() print("outofsource") print("removed") // moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) } } }else{ let pIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x - 6, y: location.y)) let nIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x + 6, y: location.y)) let uIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y - 6)) let lIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y + 6)) var frmaes = defaults.object(forKey: "FramesForEachRow") as! [String] var sourceCellType = self.collectionArray[sourceIndexPath.item] guard let sourceType = sourceCellType["type"] as? String else { return } if var pIndexPath = pIndexPath,var nIndexPath = nIndexPath, sourceType != "Text"{ print("Insert in between two cells in the same row taken as horizontally line") var keys = singletonArray[pIndexPath.item].components(separatedBy: "-") if let pCell = self.collectionView.cellForItem(at:pIndexPath){ var cellFrame = CGRectFromString(frmaes[Int(keys[0])!]) self.lineView.removeFromSuperview() let xOffset = pCell.frame.origin.x + pCell.frame.size.width let yValue = cellFrame.origin.y let nestedHeight = cellFrame.size.height let nestedWidth = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 0) }, completion: { (bool) in }) } }else if var uIndexPath = uIndexPath,var lIndexPath = lIndexPath{ print("Insert in between two cells in the same row taken as vertically line") if let uCell = self.collectionView.cellForItem(at:uIndexPath){ var uKey = singletonArray[uIndexPath.item].components(separatedBy: "-") var lKey = singletonArray[lIndexPath.item].components(separatedBy: "-") var cellFrame = CGRectFromString(frmaes[Int(uKey[0])!]) if Int(uKey[0]) == Int(lKey[0]) { if sourceType != "Text"{ let xOffset = uCell.frame.origin.x let yValue = uCell.frame.origin.y + uCell.frame.size.height + 2 let nestedWidth = uCell.frame.size.width let nestedHeight = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }, completion: { (bool) in }) }else{ self.lineView.removeFromSuperview() } }else{ print("Different row") let xOffset = cellFrame.origin.x let yValue = uCell.frame.origin.y + uCell.frame.size.height + 3 let nestedWidth = cellFrame.size.width let nestedHeight = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }, completion: { (bool) in }) } } }else if var uIndexPath = uIndexPath , lIndexPath == nil{ var uKey = singletonArray[uIndexPath.item].components(separatedBy: "-") if ((Int(uKey[0])!) == localPartition.count - 1) { print("insert at the bottom of collection view line") let cellFrame = CGRectFromString(frmaes[Int(uKey[0])!]) let xOffset = cellFrame.origin.x let yValue = cellFrame.origin.y + cellFrame.size.height + 3 let nestedWidth = cellFrame.size.width let nestedHeight = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }, completion: { (bool) in }) }else{ self.lineView.removeFromSuperview() } }else if var lIndexPath = lIndexPath , uIndexPath == nil{ var lKey = singletonArray[lIndexPath.item].components(separatedBy: "-") if ((Int(lKey[0])!) == 0) { print("Insert at the top of collection view line") let cellFrame = CGRectFromString(frmaes[Int(lKey[0])!]) let xOffset = cellFrame.origin.x let yValue = cellFrame.origin.y let nestedWidth = cellFrame.size.width let nestedHeight = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }, completion: { (bool) in }) }else{ self.lineView.removeFromSuperview() } }else{ print("move snapshot to its original position line") self.lineView.removeFromSuperview() } } } func endDragAtLocation(location:CGPoint){ let vc = collectionView guard let originalIndexPath = originalIndexPath else {return} guard var dragView = self.draggingView else {return} guard var cell = self.sourceCell else {return} if let indexPath = vc.indexPathForItem(at: location),let destination = vc.cellForItem(at: indexPath) { //added if let indexPath = vc.indexPathForItem(at: location){ let sourceCell = vc.cellForItem(at: originalIndexPath) if let destinationCell = vc.cellForItem(at: indexPath) { self.changeToIdentiPosition() lineView.removeFromSuperview() self.swapView?.removeFromSuperview() // print("\(indexPath.item)source but destination\(sourceIndexPath.item)") if indexPath.item != originalIndexPath.item{ let dict = self.collectionArray[originalIndexPath.item] if let type = dict["type"] as? String{ if type != "Text"{ let topOffset = destinationCell.frame.origin.y + 20 let leftOffset = destinationCell.frame.origin.x + 20 let bottomOffset = destinationCell.frame.origin.y + destinationCell.frame.size.height - 20 let rightOffset = destinationCell.frame.origin.x + destinationCell.frame.size.width - 20 let differenceLeft = location.x - leftOffset let differenceRight = location.x - rightOffset // print("destination\(destinationCell.frame)") let differenceTop = location.y - topOffset let differenceBottom = location.y - bottomOffset if differenceLeft > -20 && differenceLeft < 0 { print("Insert to the left of cell line") self.insertNewCellAtPoint(location: location, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) sourceCell?.isHidden = false // originalIndexPath = nil sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() // dragView = nil //[snapshot removeFromSuperview]; //snapshot = nil; }else if differenceRight < 20 && differenceRight > 0{ print("Insert to the right of the cell line") self.insertNewCellAtPoint(location: location, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) sourceCell?.isHidden = false // originalIndexPath = nil sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() // dragView = nil // need to remove top should be uncomment }else if (differenceTop > -20 && differenceTop < 0 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16)){ print("Insert to the TOP of the cell line") self.insertNewCellAtPoint(location: location, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) sourceCell?.isHidden = false // originalIndexPath = nil sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() //self.draggingView = nil }else if(differenceBottom > 0 && differenceBottom < 20 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16)){ print("Insert to the Bottom of the cell line") self.insertNewCellAtPoint(location: location, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: (self.draggingView?.frame)!) sourceCell?.isHidden = false //originalIndexPath = nil sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() //self.draggingView = nil }else{ let dict = self.collectionArray[(indexPath.item)] if let type = dict["type"] as? String{ if type != "Text"{ self.exchangeDataSource(sourceIndex: indexPath.item, destIndex: (self.originalIndexPath?.item)!) vc.performBatchUpdates({ // print("\(UserDefaults.standard.object(forKey: "partition"))final partation") self.collectionView.moveItem(at: self.originalIndexPath!, to: indexPath) self.collectionView.moveItem(at: indexPath, to: self.originalIndexPath!) }, completion: { (Bool) in UIView.animate(withDuration: 0.2, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1 }, completion: { (end) in self.draggingView!.alpha = 0.0 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) // // cell.alpha = 1 // cell.isHidden = false // dragView.removeFromSuperview() // // vc.layoutIfNeeded() // // vc.setNeedsLayout() // self.originalIndexPath = nil // self.draggingView = nil }) }else{ let delta: CGFloat = 0.00001 if abs(cell.frame.size.width - destinationCell.frame.size.width) < delta { self.exchangeDataSource(sourceIndex: indexPath.item, destIndex: (self.originalIndexPath?.item)!) self.selectedItemIndex = indexPath.item vc.performBatchUpdates({ self.collectionView.moveItem(at: self.originalIndexPath!, to: indexPath) self.collectionView.moveItem(at: indexPath, to: self.originalIndexPath!) }, completion: { (Bool) in UIView.animate(withDuration: 0.2, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1 }, completion: { (end) in self.draggingView!.alpha = 0.0 cell.alpha = 1 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) // cell.alpha = 1 // cell.isHidden = false // dragView.removeFromSuperview() // self.originalIndexPath = nil // self.draggingView = nil }) }else{ self.lineView.removeFromSuperview() cell.alpha = 0 UIView.animate(withDuration: 0.3, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1 }, completion: { (end) in self.draggingView!.alpha = 0.0 cell.alpha = 1 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) } } } } }else{ //Swap the images let delta: CGFloat = 0.00001 if abs(cell.frame.size.width - destinationCell.frame.size.width) < delta { self.exchangeDataSource(sourceIndex: indexPath.item, destIndex: (self.originalIndexPath?.item)!) self.selectedItemIndex = indexPath.item vc.performBatchUpdates({ self.collectionView.moveItem(at: self.originalIndexPath!, to: indexPath) self.collectionView.moveItem(at: indexPath, to: self.originalIndexPath!) }, completion: { (Bool) in UIView.animate(withDuration: 0.2, animations: { dragView.frame = cell.frame dragView.alpha = 1 }, completion: { (end) in dragView.alpha = 0.0 cell.alpha = 1 cell.isHidden = false dragView.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil // dragView = nil }) // cell.alpha = 1 // cell.isHidden = false // dragView.removeFromSuperview() // self.originalIndexPath = nil // self.draggingView = nil }) }else{ self.lineView.removeFromSuperview() cell.alpha = 0 UIView.animate(withDuration: 0.3, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1.0 }, completion: { (end) in cell.alpha = 1 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) } } } } else{ print("testign not visible") print("outofsource") self.lineView.removeFromSuperview() // cell.alpha = 0 UIView.animate(withDuration: 0.3, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1 // cell.alpha = 1 }, completion: { (end) in cell.alpha = 1 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) } } } }else{ self.changeToIdentiPosition() lineView.removeFromSuperview() self.swapView?.removeFromSuperview() let pIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x - 6, y: location.y)) let nIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x + 6, y: location.y)) let uIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y - 6)) let lIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y + 6)) // guard let indexPath = vc.indexPathForItem(at: location)else{ return } let dict = self.collectionArray[originalIndexPath.item] let type = dict["type"] as! String if var pIndexPath = pIndexPath,var nIndexPath = nIndexPath,type != "Text"{ let dict = self.collectionArray[(originalIndexPath.item)] if let type = dict["type"] as? String{ if type != "Text"{ print("Insert in between two cells in the same row taken as horizontally gesture") self.insertNewCellAtPoint(location: dragView.center, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) let sourceCell = vc.cellForItem(at: originalIndexPath) sourceCell?.isHidden = false sourceCell?.alpha = 1 dragView.removeFromSuperview() } } }else if var uIndexPath = uIndexPath,var lIndexPath = lIndexPath{ // let dict = self.collectionArray[(originalIndexPath.item)] print("Insert in between two cells in the same row taken as vertically gesture") self.insertNewCellAtPoint(location: dragView.center, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) let sourceCell = vc.cellForItem(at: originalIndexPath) sourceCell?.isHidden = false sourceCell?.alpha = 1 // originalIndexPath = nil //sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() }else if var uIndexPath = uIndexPath, lIndexPath == nil{ print("insert at the bottom of collection view gesture") self.insertNewCellAtPoint(location: dragView.center, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) let sourceCell = vc.cellForItem(at: originalIndexPath) sourceCell?.isHidden = false sourceCell?.alpha = 1 //originalIndexPath = nil //sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() } else if var lIndexPath = lIndexPath, uIndexPath == nil{ print("insert at the top of collection view gesture") self.insertNewCellAtPoint(location: dragView.center, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) let sourceCell = vc.cellForItem(at: originalIndexPath) sourceCell?.isHidden = false sourceCell?.alpha = 1 // originalIndexPath = nil dragView.removeFromSuperview() }else{ self.lineView.removeFromSuperview() guard var frameOfDraging = self.frameOfDragingIndexPath else { return } guard var sourceCell = self.sourceCell else {return} // guard let sourceCell = self.collectionView.cellForItem(at:originalIndexPath)else { return } UIView.animate(withDuration: 0.25, animations: { dragView.center = frameOfDraging dragView.transform = CGAffineTransform.identity dragView.alpha = 0.0; sourceCell.alpha = 1.0; }, completion: { (flag) in sourceCell.isHidden = false self.originalIndexPath = nil dragView.removeFromSuperview() }) } } } func scrollIfNeed(snapshotView:UIView) { var cellCenter = snapshotView.center var newOffset = collectionView.contentOffset let buffer = CGFloat(10) let bottomY = collectionView.contentOffset.y + collectionView.frame.size.height - 100 // print("bottomY\(bottomY)") //print("(snapshotView.frame.maxY - buffer)\((snapshotView.frame.maxY - buffer))") //print("condition \(bottomY < (snapshotView.frame.maxY - buffer))") if (bottomY < (snapshotView.frame.maxY - buffer)){ newOffset.y = newOffset.y + 1 // print("uppppp") if (((newOffset.y) + (collectionView.bounds.size.height)) > (collectionView.contentSize.height)) { return } cellCenter.y = cellCenter.y + 1 } let offsetY = collectionView.contentOffset.y // print("chita \(offsetY)") if (snapshotView.frame.minY + buffer < offsetY) { // print("Atul\(snapshotView.frame.minY + buffer)") // We're scrolling up newOffset.y = newOffset.y - 1 // print("downnnn") if ((newOffset.y) <= CGFloat(0)) { return } // adjust cell's center by 1 cellCenter.y = cellCenter.y - 1 } collectionView.contentOffset = newOffset snapshotView.center = cellCenter; // Repeat until we went to far. if(self.stopped == true){ return }else { let deadlineTime = DispatchTime.now() + 0.3 DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: { self.scrollIfNeed(snapshotView: snapshotView) }) } } func autoScroll() { if self.collectionArray.count > 1{ self.collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .centeredVertically, animated: true) } } func autoScrollToTop() { if let headerAttributes = self.collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)){ self.collectionView.setContentOffset(CGPoint(x: 0, y: (headerAttributes.frame.origin.x)), animated: true) } } //MARK :- Supplementary DataSource func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { if reloadHeaderView == true{ headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) as? PictureHeaderCollectionReusableView headerView?.delegate = self self.headerView?.iboTitle.delegate = self self.headerView?.iboSubTitle.delegate = self if isLoadingStory{ self.barButtonActivityIndicator.startAnimating() self.headerView?.iboScrollDownBrn.setImage(nil, for: .normal) self.headerView?.iboScrollDownBrn.addSubview(barButtonActivityIndicator) }else{ self.barButtonActivityIndicator.stopAnimating() barButtonActivityIndicator.removeFromSuperview() self.headerView?.iboScrollDownBrn.setImage(UIImage(named: "down"), for: .normal) UIView.animate(withDuration: 0.3, animations: { self.headerView?.iboScrollDownBrn.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) }, completion: { _ in UIView.animate(withDuration: 0.3) { self.headerView?.iboScrollDownBrn.transform = CGAffineTransform.identity } }) } if self.isViewStory{ headerView?.iboHeaderImage.removeGestureRecognizer(singleTap) self.headerView?.iboHeaderImage.backgroundColor = UIColor(hexString: self.story_cover_photo_slice_code) var urlImage = self.story_cover_photo_path.components(separatedBy: "album") self.headerView?.iboTitle.text = self.storyTitle self.headerView?.iboSubTitle.text = self.storySubtitle self.headerView?.iboTitle.isUserInteractionEnabled = false self.headerView?.iboSubTitle.isUserInteractionEnabled = false var totalPath = URLConstants.imgDomain if let data = coverdata { //self.headerView?.iboHeaderImage.contentMode = UIViewContentMode.scaleAspectFill DispatchQueue.main.async { self.headerView?.iboHeaderImage.image = data } }else { self.headerView?.iboHeaderImage.sd_setImage(with: URL(string: totalPath + urlImage[1]), placeholderImage: UIImage(named: ""), options: SDWebImageOptions.progressiveDownload, completed: { (image, data, error, finished) in guard let image = image else { return } print("Image loaded!") self.headerView?.iboHeaderImage.contentMode = UIViewContentMode.scaleAspectFill self.headerView?.iboHeaderImage.image = image self.coverdata = image // self.iboProfileLoaderIndicator.stopAnimating() }) } }else{ if isFirstTime { self.perform(#selector(checkForHeaderTitle), with: nil, afterDelay: 0.5) } self.headerView?.iboTitle.isUserInteractionEnabled = true self.headerView?.iboSubTitle.isUserInteractionEnabled = true headerView?.iboHeaderImage.addGestureRecognizer(singleTap) if let coverData = coverdata{ self.headerView?.iboHeaderImage.image = coverData } } } return headerView! } else if kind == UICollectionElementKindSectionFooter { // assert(0) let fotterView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FotterView", for: indexPath) as! FooterReusableView fotterView.iboOwnerImg.setImage(string: "Chitaranjan sahu", color: UIColor(hexString:"#7FC9F1"), circular: true) fotterView.delegate = self fotterView.backgroundColor = UIColor.white return fotterView }else{ return UICollectionReusableView() } } func checkForHeaderTitle() { if isFirstTime { self.headerView?.iboTitle.becomeFirstResponder() self.isFirstTime = false } } func sameRowOrNot(sourceIndexPath: Int,destinationIndexPath :Int ) -> Bool { var singletonArray = self.getSingletonArray() let destPaths = singletonArray[sourceIndexPath] let sourcePaths = singletonArray[destinationIndexPath] var destKeys = destPaths.components(separatedBy: "-") var sourceKeys = destPaths.components(separatedBy: "-") if destKeys[0] == sourceKeys[0]{ return true }else{ return false } } func moveCellsApartWithFrame(frame:CGRect,andOrientation orientation:Int) { var certOne = CGRect.zero var certTwo = CGRect.zero cellsToMove0.removeAllObjects() cellsToMove1.removeAllObjects() if orientation == 0 { certOne = CGRect(x: frame.origin.x, y: frame.origin.y, width: CGFloat.greatestFiniteMagnitude, height: frame.size.height) certTwo = CGRect(x: 0.0, y: frame.origin.y, width: frame.origin.x, height: frame.size.height) print("\(certOne)first One") print("\(certTwo)secondOne") }else{ certOne = CGRect(x: frame.origin.x, y: frame.origin.y, width: CGFloat.greatestFiniteMagnitude, height: frame.size.height) certTwo = CGRect(x: frame.origin.x, y: 0.0, width: frame.size.width, height: frame.origin.y) } for i in 0 ..< self.collectionArray.count{ let indexPath = IndexPath(item: i, section: 0) if let cell = self.collectionView.cellForItem(at: indexPath){ if (cell.frame.intersects(certOne)){ cellsToMove0.add(cell) }else if (cell.frame.intersects(certTwo)) { cellsToMove1.add(cell) } } } self.collectionView.performBatchUpdates({ for i in 0 ..< self.cellsToMove0.count{ if orientation == 0{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove0[i] as! UICollectionViewCell cell.transform = CGAffineTransform(translationX: 5.0, y: 0.0) }) }else{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove0[i] as! UICollectionViewCell cell.transform = CGAffineTransform(translationX: 0.0, y: 5.0) }) } } for i in 0 ..< self.cellsToMove1.count{ if orientation == 0{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove1[i] as! UICollectionViewCell cell.transform = CGAffineTransform(translationX: -5.0, y: 0.0) }) }else{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove1[i] as! UICollectionViewCell cell.transform = CGAffineTransform(translationX: 0.0, y: -5.0) }) } } }, completion: { (Bool) in }) } func changeToIdentiPosition() { self.collectionView.performBatchUpdates({ for i in 0 ..< self.cellsToMove0.count{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove0[i] as! UICollectionViewCell cell.transform = CGAffineTransform.identity }) } for i in 0 ..< self.cellsToMove1.count{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove1[i] as! UICollectionViewCell cell.transform = CGAffineTransform.identity }) } }, completion: { (test) in }) } func cancelClicked() { self.defaults.removeObject(forKey: "isViewStory") if upload{ self.navigationController?.dismiss(animated: true, completion: nil) self.upload = false }else{ _ = self.navigationController?.popViewController(animated: true) } } func insertNewCellAtPoint(location:CGPoint ,withSourceIndexPathwithSourceIndexPath sourceIndexPath : IndexPath ,forSnapshot snapshot:CGRect){ if let destinationIndexPath = self.collectionView.indexPathForItem(at: location){ if let destinationCell = self.collectionView.cellForItem(at: destinationIndexPath){ let temp = collectionArray[destinationIndexPath.row] let source = collectionArray[sourceIndexPath.row] let type = temp["type"] as! String let sourceType = source["type"] as! String if destinationIndexPath.item != sourceIndexPath.item{ if (type != "Text") { let topOffset = destinationCell.frame.origin.y + 20 let leftOffset = destinationCell.frame.origin.x + 20 let bottomOffset = destinationCell.frame.origin.y + destinationCell.frame.size.height - 20 let rightOffset = destinationCell.frame.origin.x + destinationCell.frame.size.width - 20 let differenceLeft = location.x - leftOffset let differenceRight = location.x - rightOffset let differenceTop = location.y - topOffset let differenceBottom = location.y - bottomOffset var singletonArray = self.getSingletonArray() var sourseKey = singletonArray[sourceIndexPath.item] var sourseKeys = sourseKey.components(separatedBy: "-") // if let sourseKeys = findWithIndex(array: singletonArray, index: sourceIndexPath.item){ if(differenceLeft > -20 && differenceLeft < 0 && sourceType != "Text"){ print("Inserting to the left of cell") let destPaths = singletonArray[destinationIndexPath.item] // let destPaths = findWithIndex(array: singletonArray, index: destinationIndexPath.item) var destKeys = destPaths.components(separatedBy: "-") let rowNumber = self.localPartition[Int(destKeys[0])!] //let rowNumber :NSArray = self.localPartition.object(at: Int(destKeys[0])!) as! NSArray // let rowNumber : NSMutableArray = self.localPartition.object(at: destKeys[0]) let rowTemp = rowNumber let nextItem = rowTemp[Int(destKeys[1])!] let searchString = nextItem.first var destIndex = singletonArray.index(of: searchString!) if sourceIndexPath.item < destinationIndexPath.item && destIndex != 0{ destIndex = destIndex! - 1 } var insertRow = self.localPartition[Int((destKeys[0]))!] var insertRowArray = insertRow let columnNumber = Int((destKeys[1]))! guard let newIndex = Int(destKeys.first!) else { return } print("New index \(newIndex)") let ArrayWithObj = "\(newIndex)-\(columnNumber)-\(0)" var arrayObj = [ArrayWithObj] //var arrayObj = NSArray(array: [ArrayWithObj]) // arrayObj.adding(ArrayWithObj) // arrayObj.append(ArrayWithObj) insertRowArray.insert(arrayObj, at: columnNumber) print("start\(insertRowArray)") for i in columnNumber ..< insertRowArray.count{ var insertColumn = insertRowArray[i] // let insertColumnArray = [insertColumn] // let insertColumnArray = NSMutableArray.init(array: [insertColumn]) print("start\(insertColumn)") for j in 0 ..< insertColumn.count{ insertColumn[j] = "\(newIndex)-\(i)-\(j)" // insertColumnArray.replaceObject(at: j, with: "\(newIndex)-\(i)-\(j)") } insertRowArray[i] = insertColumn } self.localPartition[newIndex] = insertRowArray print("NEW Index\(destIndex)") let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) print("locacl Part") let sourseKeysSecond = Int(sourseKeys[1])! + 1 if (Int(sourseKeys[0])) == Int(destKeys[0]){ if (Int(sourseKeys[1]) )! >= Int(destKeys[1])!{ sourseKeys[0] = "\(Int(sourseKeys[0])!)" sourseKeys[1] = "\(sourseKeysSecond)" sourseKeys[2] = "\(Int(sourseKeys[2])!)" } } let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ // UIView.setAnimationsEnabled(false) self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // UIView.setAnimationsEnabled(true) // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) }else if (differenceRight < 20 && differenceRight > 0 && sourceType != "Text"){ print("Inserting to the right of cell") let destPaths = singletonArray[destinationIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") let rowNumber = self.localPartition[Int(destKeys[0])!] let rowTemp = rowNumber let nextItem = rowTemp[Int(destKeys[1])!] let searchString = nextItem.last var destIndex = singletonArray.index(of: searchString!) let columnNumber = Int((destKeys[1]))! + 1 destKeys[0] = destKeys[0] destKeys[1] = "\(columnNumber)" destKeys[2] = destKeys[2] if sourceIndexPath.item > destIndex!{ destIndex = destIndex! + 1 } var insertRow = self.localPartition[Int((destKeys[0]))!] var insertRowArray = insertRow guard let newIndex = Int(destKeys.first!) else { return } print("New index \(newIndex)") let ArrayWithObj = "\(newIndex)-\(columnNumber)-\(0)" var arrayObj = [ArrayWithObj] //var arrayObj = NSArray(array: [ArrayWithObj]) // arrayObj.adding(ArrayWithObj) // arrayObj.append(ArrayWithObj) insertRowArray.insert(arrayObj, at: columnNumber) print("start\(insertRowArray)") for i in columnNumber ..< insertRowArray.count{ var insertColumn = insertRowArray[i] // let insertColumnArray = [insertColumn] // let insertColumnArray = NSMutableArray.init(array: [insertColumn]) print("start\(insertColumn)") for j in 0 ..< insertColumn.count{ insertColumn[j] = "\(newIndex)-\(i)-\(j)" // insertColumnArray.replaceObject(at: j, with: "\(newIndex)-\(i)-\(j)") } insertRowArray[i] = insertColumn } self.localPartition[newIndex] = insertRowArray print("NEW Index\(destIndex)") let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) selectedItemIndex = destIndex! print("locacl Part") let sourseKeysSecond = Int(sourseKeys[1])! + 1 if (Int(sourseKeys[0])) == Int(destKeys[0]){ if (Int(sourseKeys[1]) )! >= Int(destKeys[1])!{ sourseKeys[0] = "\(Int(sourseKeys[0])!)" sourseKeys[1] = "\(sourseKeysSecond)" sourseKeys[2] = "\(Int(sourseKeys[2])!)" //sourseKeys = ["\(Int(sourseKeys[0])!)-\(sourseKeysSecond)-\(Int(sourseKeys[2])!)"] } } let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) }else if (differenceTop > -20 && differenceTop < 0 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16) && sourceType != "Text"){ print("Insert to the top of that cell") let destPaths = singletonArray[destinationIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var destIndex = destinationIndexPath.item if sourceIndexPath.item < destIndex { destIndex = destIndex - 1 } var destRowArray = self.localPartition[Int(destKeys[0])!] var destColArray = destRowArray[Int(destKeys[1])!] // let searchString = nextItem.first var newObj = destKeys[0] + "-" + destKeys[1] + "-" + "\(destColArray.count)" destColArray.append(newObj) destRowArray[Int(destKeys[1])!] = destColArray localPartition[Int(destKeys[0])!] = destRowArray let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex) var rowArray = self.localPartition[(Int(sourseKeys[0]))!] var columnArray = rowArray[(Int(sourseKeys[1]))!] print("column array \(columnArray)") columnArray.remove(at: columnArray.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &rowArray , andColumn: &columnArray, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex, section: 0), at: .centeredVertically, animated: true) }) }else if(differenceBottom > 0 && differenceBottom < 20 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16) && sourceType != "Text"){ print("Insert to the bottom of that cell") let destPaths = singletonArray[destinationIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var destRowArray = self.localPartition[Int(destKeys[0])!] var destIndex = destinationIndexPath.item if sourceIndexPath.item > destIndex { destIndex = destIndex + 1 } var destColArray = destRowArray[Int(destKeys[1])!] // let searchString = nextItem.first var newObj = destKeys[0] + "-" + destKeys[1] + "-" + "\(destColArray.count)" destColArray.append(newObj) destRowArray[Int(destKeys[1])!] = destColArray localPartition[Int(destKeys[0])!] = destRowArray let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex) var rowArray = self.localPartition[(Int(sourseKeys[0]))!] var columnArray = rowArray[(Int(sourseKeys[1]))!] print("column array \(columnArray)") columnArray.remove(at: columnArray.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &rowArray , andColumn: &columnArray, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex, section: 0), at: .centeredVertically, animated: true) }) }else{ self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() } }else{ self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() } }else{ self.lineView.removeFromSuperview() } } }else{ let pIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x - 6, y: location.y)) let nIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x + 6, y: location.y)) let uIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y - 6)) let lIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y + 6)) //guard let indexPath = self.collectionView?.indexPathForItem(at: location)else{ return } var singletonArray = self.getSingletonArray() var sourseKey = singletonArray[sourceIndexPath.item] var sourseKeys = sourseKey.components(separatedBy: "-") let temp = collectionArray[sourceIndexPath.row] let type = temp["type"] as! String if var pIndexPath = pIndexPath,var nIndexPath = nIndexPath, type != "Text"{ let dict = self.collectionArray[sourceIndexPath.item] if let type = dict["type"] as? String{ if type != "Text"{ print("Insert in between two cells in the same row taken as horizontally") print("Inserting to the right of cell") let destPaths = singletonArray[pIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") let rowNumber = self.localPartition[Int(destKeys[0])!] let rowTemp = rowNumber let nextItem = rowTemp[Int(destKeys[1])!] let searchString = nextItem.first // let nextItem = rowNumber.object(at: destKeys[1]) var destIndex = singletonArray.index(of: searchString!) if sourceIndexPath.item > destIndex!{ destIndex = destIndex! + 1 } var insertRow = self.localPartition[Int((destKeys[0]))!] var insertRowArray = insertRow let columnNumber = Int((destKeys[1]))! guard let newIndex = Int(destKeys.first!) else { return } print("New index \(newIndex)") let ArrayWithObj = "\(newIndex)-\(columnNumber)-\(0)" var arrayObj = [ArrayWithObj] //var arrayObj = NSArray(array: [ArrayWithObj]) // arrayObj.adding(ArrayWithObj) // arrayObj.append(ArrayWithObj) insertRowArray.insert(arrayObj, at: columnNumber) print("start\(insertRowArray)") for i in columnNumber ..< insertRowArray.count{ var insertColumn = insertRowArray[i] // let insertColumnArray = [insertColumn] // let insertColumnArray = NSMutableArray.init(array: [insertColumn]) print("start\(insertColumn)") for j in 0 ..< insertColumn.count{ insertColumn[j] = "\(newIndex)-\(i)-\(j)" // insertColumnArray.replaceObject(at: j, with: "\(newIndex)-\(i)-\(j)") } insertRowArray[i] = insertColumn } self.localPartition[newIndex] = insertRowArray print("NEW Index\(destIndex)") let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) selectedItemIndex = destIndex! print("locacl Part") let sourseKeysSecond = Int(sourseKeys[1])! + 1 if (Int(sourseKeys[0])) == Int(destKeys[0]){ if (Int(sourseKeys[1]) )! >= Int(destKeys[1])!{ sourseKeys[0] = "\(Int(sourseKeys[0])!)" sourseKeys[1] = "\(sourseKeysSecond)" sourseKeys[2] = "\(Int(sourseKeys[2])!)" //sourseKeys = ["\(Int(sourseKeys[0])!)-\(sourseKeysSecond)-\(Int(sourseKeys[2])!)"] } } let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) } } }else if var uIndexPath = uIndexPath,var lIndexPath = lIndexPath{ print("Insert in between two cells in the same row taken as vertically line") if let uCell = self.collectionView.cellForItem(at:uIndexPath){ var uKey = singletonArray[uIndexPath.item].components(separatedBy: "-") var lKey = singletonArray[lIndexPath.item].components(separatedBy: "-") // var cellFrame = CGRectFromString(frmaes[Int(uKey[0])!]) if Int(uKey[0]) == Int(lKey[0]) { let dict = self.collectionArray[sourceIndexPath.item] if let type = dict["type"] as? String{ if type != "Text"{ print("Inserting to the right of cell") let destPaths = singletonArray[uIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") let rowNumber = self.localPartition[Int(destKeys[0])!] let rowTemp = rowNumber let nextItem = rowTemp[Int(destKeys[1])!] let searchString = nextItem.first // let nextItem = rowNumber.object(at: destKeys[1]) var destIndex = singletonArray.index(of: searchString!) if sourceIndexPath.item > destIndex!{ destIndex = destIndex! + 1 } var insertRow = self.localPartition[Int((destKeys[0]))!] var destColArray = insertRow[Int((destKeys[1]))!] let columnNumber = Int((destKeys[1]))! guard let newIndex = Int(destKeys.first!) else { return } print("New index \(newIndex)") let ArrayWithObj = "\(newIndex)-\(columnNumber)-\(destColArray.count)" destColArray.append(ArrayWithObj) insertRow[columnNumber] = destColArray self.localPartition[Int((destKeys[0]))!] = insertRow let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) selectedItemIndex = destIndex! let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) }else{ self.reloadHeaderView = false self.lineView.removeFromSuperview() let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() } } }else{ print("Different row") let destPaths = singletonArray[uIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var lastItem = self.localPartition[Int(destKeys[0])!] var nested = lastItem.last var thirdNested = nested?.last var destIndex = singletonArray.index(of: thirdNested!) destIndex! = destIndex! + 1 if sourceIndexPath.item < destIndex!{ destIndex = destIndex! - 1 } var destRow = Int(destKeys.first!)! + 1 var newObj = ["\(destRow)-0-0"] var insertObj = [newObj] self.localPartition.insert(insertObj, at: destRow) // self.localPartition[destRow] = insertObj for i in (destRow + 1) ..< self.localPartition.count{ var rowArray = self.localPartition[i] for j in 0 ..< rowArray.count{ var colArray = rowArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } rowArray[j] = colArray } self.localPartition[i] = rowArray } let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) selectedItemIndex = destIndex! var sourceRow = (Int(sourseKeys[0]))! if(destRow <= sourceRow){ sourceRow = sourceRow + 1 } sourseKeys[0] = "\(sourceRow)" sourseKeys[1] = sourseKeys[1] sourseKeys[2] = sourseKeys[2] //sourseKeys = ["\(sourceRow)",sourseKeys[1],sourseKeys[2]] var rowArray = self.localPartition[sourceRow] var columnArray = rowArray[(Int(sourseKeys[1]))!] print("column array \(columnArray)") columnArray.remove(at: columnArray.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &rowArray , andColumn: &columnArray, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) } } }else if var uIndexPath = uIndexPath, lIndexPath == nil{ var uKey = singletonArray[uIndexPath.item] var uKey1 = uKey.components(separatedBy: "-") if Int(uKey1[0])! == (self.localPartition.count - 1){ print("insert at the bottom of collection view") var destPaths = singletonArray[uIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var destIndex = singletonArray.count - 1 var destRow = Int(destKeys.first!)! + 1 var newObj = ["\(destRow)-0-0"] var insertObj = [newObj] self.localPartition.insert(insertObj, at: destRow) // self.localPartition[destRow] = insertObj for i in destRow+1 ..< self.localPartition.count{ var rowArray = self.localPartition[i] for j in 0 ..< rowArray.count{ var colArray = rowArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } rowArray[j] = colArray } localPartition[i] = rowArray } // self.localPartition[newIndex] = insertRowArray // print("NEW Index\(destIndex)") let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex) print("locacl Part") let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex, section: 0), at: .centeredVertically, animated: true) }) }else{ self.lineView.removeFromSuperview() var indexSet :IndexSet = [0] self.collectionView.reloadSections(indexSet) } }else if var lIndexPath = lIndexPath, uIndexPath == nil { var lKey = singletonArray[lIndexPath.item] var lKey1 = lKey.components(separatedBy: "-") if( Int(lKey1[0])! == 0) { print("Insert at the top of collection view") var destPaths = singletonArray[lIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var destIndex = 0 var destRow = Int(destKeys.first!)! var newObj = ["\(destRow)-0-0"] var insertObj = [newObj] self.localPartition.insert(insertObj, at: destRow) // self.localPartition[destRow] = insertObj for i in destRow+1 ..< self.localPartition.count{ var rowArray = self.localPartition[i] for j in 0 ..< rowArray.count{ var colArray = rowArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } rowArray[j] = colArray } localPartition[i] = rowArray } let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex) print("locacl Part") selectedItemIndex = destIndex var sourceRow = Int(sourseKeys[0])! if(destRow <= sourceRow){ sourceRow = sourceRow + 1 } sourseKeys[0] = "\(sourceRow)" sourseKeys[1] = sourseKeys[1] sourseKeys[2] = sourseKeys[2] let rowArray = self.localPartition[(Int(sourceRow))] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex, section: 0), at: .centeredVertically, animated: true) }) }else{ self.reloadHeaderView = false self.lineView.removeFromSuperview() let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() } }else{ self.lineView.removeFromSuperview() } } self.changeToIdentiPosition() } func changePartitionForSourceRowWithRow(rowArray :inout Array<Array<String>>,andColumn columnArray:inout Array<String>,andSourceKeys keys: inout Array<String>,andDestKeys destKeys:inout Array<String>) { if (columnArray.count > 0){ //rowArray[Int(keys[1])!] = columnArray rowArray[Int(keys[1])!] = columnArray // rowArray.replaceObject(at: Int(keys[1] as! String)! , with: columnArray) localPartition[Int(keys[0])!] = rowArray // localPartition.replaceObject(at:Int(keys[0] as! String)!, with: rowArray) }else{ rowArray.remove(at: Int(keys[1])!) // rowArray.removeObject(at: keys[1] as! Int) if rowArray.count != 0{ if rowArray.count == 1 && (rowArray[0].count > 1){ localPartition.remove(at: Int(keys[0])!) let sourceRow = Int(keys[0])! let rowCount = rowArray[0].count for i in sourceRow..<(sourceRow + rowCount) { let ArrayWithObj = "\(i)-\(0)-\(0)" var arrayObj = [ArrayWithObj] let rowObject = [arrayObj] localPartition.insert(rowObject, at: i) //localPartition.insert(rowObject, at: i) } for j in (sourceRow+rowCount) ..< localPartition.count{ var rowArray = localPartition[j] //let rowArray : NSMutableArray = localPartition.object(at: j) as! NSMutableArray for k in 0 ..< rowArray.count{ var colArray1 = rowArray[k] //let colArray1:NSMutableArray = rowArray.object(at: k) as! NSMutableArray for l in 0 ..< colArray1.count{ colArray1[l] = "\(j)-\(k)-\(l)" //colArray1.replaceObject(at: l, with: "\(j)-\(k)-\(l)") } rowArray[k] = colArray1 //rowArray.replaceObject(at: k, with: colArray1) } localPartition[j] = rowArray //localPartition.replaceObject(at: j, with: rowArray) } }else{ for i in Int(keys[1])! ..< rowArray.count { var colArray = rowArray[i] //let colArray :NSMutableArray = rowArray.object(at: i) as! NSMutableArray for j in 0 ..< colArray.count { colArray[j] = "\(Int(keys[0])!)-\(i)-\(j)" // colArray.replaceObject(at: j, with: "\(keys.firstObject as! Int)-\(i)-\(j)") } rowArray[i] = colArray // rowArray.replaceObject(at: i, with: colArray) } localPartition[Int(keys[0])!] = rowArray //localPartition.replaceObject(at: keys.firstObject as! Int, with: rowArray) } }else{ localPartition.remove(at: Int(keys[0])!) //localPartition.removeObject(at: keys.firstObject as! Int) for i in Int(keys[0])! ..< localPartition.count { var rowArray = localPartition[i] //let rowArray :NSMutableArray = localPartition.object(at: i) as! NSMutableArray for j in 0 ..< rowArray.count { var colArray = rowArray[j] //let colArray :NSMutableArray = rowArray.object(at: j) as! NSMutableArray for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" //colArray.replaceObject(at: j, with: "\(i)-\(j)-\(k)") } rowArray[j] = colArray //rowArray.replaceObject(at: j, with: colArray) } localPartition[i] = rowArray } } } print("final update \(localPartition)") } func findWithIndex(array : [String],index i : Int = 0) -> String? { for j in 0...array.count { if j == i { return array[i] } } return nil } func getSingletonArray() -> Array<String>{ var returnArray = Array<String>() for (_,indexArray) in localPartition.enumerated(){ for (_,insideArray) in indexArray.enumerated(){ for (_,inside) in insideArray.enumerated(){ returnArray.append(inside) } } } return returnArray } func exchangeDataSource(sourceIndex:Int,destIndex:Int) { var temp = self.collectionArray[sourceIndex] self.collectionArray[sourceIndex] = self.collectionArray[destIndex] self.collectionArray[destIndex] = temp } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } //MARK: - showImagePicker func showImagePicker() { let pickerController = DKImagePickerController() pickerController.allowMultipleTypes = true pickerController.autoDownloadWhenAssetIsInCloud = true pickerController.showsCancelButton = true self.present(pickerController, animated: true) {} pickerController.didCancel = { () in self.navigationController?.dismiss(animated: true, completion: nil) //self.navigationController?.popViewController(animated: true) } pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in self.defaults.set(false, forKey: "FirstTimeUpload") print("didSelectAssets") if assets.count > 0{ self.startAnimation() } self.requestOptions.resizeMode = .exact self.requestOptions.deliveryMode = .highQualityFormat self.requestOptions.isSynchronous = false self.requestOptions.isNetworkAccessAllowed = true let manager: PHImageManager = PHImageManager.default() var assetsOriginal = [PHAsset]() for dKasset :DKAsset in assets{ assetsOriginal.append(dKasset.originalAsset!) } var newItemsArray = [[AnyHashable:Any]]() DispatchQueue.global(qos: .background).async { for asset: PHAsset in assetsOriginal { if asset.mediaType == .video { self.requestOptionsVideo.deliveryMode = .highQualityFormat self.requestOptionsVideo.isNetworkAccessAllowed = true manager.requestAVAsset(forVideo: asset, options: self.requestOptionsVideo, resultHandler: { (assert:AVAsset?, audio:AVAudioMix?, info:[AnyHashable : Any]?) in let UrlLocal: URL = ((assert as? AVURLAsset)?.url)! let videoData = NSData(contentsOf: UrlLocal) guard let track = AVAsset(url: UrlLocal).tracks(withMediaType: AVMediaTypeVideo).first else { return } // var tracks = ass.tracks(withMediaType: "AVMediaTypeVideo").first // let track = tracks let trackDimensions = track.naturalSize let length = (videoData?.length)! / 1000000 var dictToAdd = Dictionary<AnyHashable, Any>() dictToAdd.updateValue(UrlLocal, forKey: "item_url") dictToAdd.updateValue("", forKey: "cover") dictToAdd.updateValue("#322e20,#d3d5db,#97989d,#aeb2b9,#858176", forKey: "hexCode") dictToAdd.updateValue(trackDimensions, forKey: "item_size") dictToAdd.updateValue(videoData, forKey: "data") dictToAdd.updateValue(UrlLocal, forKey: "item_url") dictToAdd.updateValue("video", forKey: "type") newItemsArray.append(dictToAdd) if assetsOriginal.count == newItemsArray.count{ if(self.localPartition.count > 0){ self.defaults.set(newItemsArray.count, forKey: "addedMorePhotos") } var uploadViewController = self.storyboard?.instantiateViewController(withIdentifier: "ImagesUploadViewController") as! ImagesUploadViewController uploadViewController.uploadData = newItemsArray uploadViewController.storyId = String(self.randomNumber()) uploadViewController.dismissView = {(sender : UIViewController?,initialize:Bool?,newObjects:[[AnyHashable:Any]]?) -> Void in if self.collectionArray.count > 0{ self.defaults.set(true, forKey: "deletedAllItems") }else{ self.defaults.set(false, forKey: "deletedAllItems") } if self.localPartition.count > 0{ if !(initialize!){ self.scrollToPostionAfterUpload = self.collectionArray.count - 1 self.collectionArray.append(contentsOf: newObjects!) self.upload = true runOnMainThread { if let local = self.defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ self.localPartition = local } self.reloadHeaderView = true self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.getPhotobyupload() self.stopAnimationLoader() self.turnOnEditMode() } } }else{ self.collectionArray = newObjects! self.scrollToPostionAfterUpload = 0 self.isFirstTime = true self.isLoadingStory = false runOnMainThread { self.reloadHeaderView = true let temp = self.collectionArray[0] var sizeOrg = temp["cloudFilePath"] as? String sizeOrg = URLConstants.imgDomain + sizeOrg! self.story_cover_photo_path = sizeOrg! self.getDataFromUrl(url: URL(string: sizeOrg!)!) { (data, response, error) in guard let data = data, error == nil else { return } self.coverdata = data DispatchQueue.main.async() { () -> Void in self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress)) self.collectionView.addGestureRecognizer(self.longPressGesture!) self.swapView = UIView(frame: CGRect.zero) self.swapImageView = UIImageView(image: UIImage(named: "Swap-white")) self.view.addSubview(self.collectionView) self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.upload = true self.getPhotobyupload() self.stopAnimationLoader() self.turnOnEditMode() //defaults.set(localPartition, forKey: "partition") if let local = self.defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ self.localPartition = local } } } } } } self.present(uploadViewController, animated: true, completion: { self.stopAnimationLoader() }) } }) }else{ manager.requestImageData(for: asset, options: self.requestOptions, resultHandler: { (data: Data?, identificador: String?, orientaciomImage: UIImageOrientation, info: [AnyHashable: Any]?) in // print(info) var dictToAdd = Dictionary<AnyHashable, Any>() let compressedImage = UIImage(data: data!) // self.images.append(compressedImage!) let urlString = "\(((((info as! Dictionary<String,Any>)["PHImageFileURLKey"])! as! URL)))" dictToAdd.updateValue(urlString, forKey: "cloudFilePath") dictToAdd.updateValue(0, forKey: "cover") dictToAdd.updateValue(urlString, forKey: "filePath") dictToAdd.updateValue("#322e20,#d3d5db,#97989d,#aeb2b9,#858176", forKey: "hexCode") // dictToAdd.updateValue("#322e20,#d3d5db,#97989d,#aeb2b9,#858176" as AnyObject, forKey: "hexCode") let sizeImage = compressedImage?.size dictToAdd.updateValue(sizeImage, forKey: "item_size") dictToAdd.updateValue(urlString, forKey: "item_url") dictToAdd.updateValue(data, forKey: "data") dictToAdd.updateValue(sizeImage, forKey: "original_size") dictToAdd.updateValue("img", forKey: "type") newItemsArray.append(dictToAdd) if assetsOriginal.count == newItemsArray.count{ if(self.localPartition.count > 0){ self.defaults.set(newItemsArray.count, forKey: "addedMorePhotos") } var uploadViewController = self.storyboard?.instantiateViewController(withIdentifier: "ImagesUploadViewController") as! ImagesUploadViewController uploadViewController.uploadData = newItemsArray uploadViewController.storyId = String(self.randomNumber()) //let addHomes = self.storyboard?.instantiateViewController(withIdentifier: "AddHomesVC") as! AddHomesVC // var uploadViewController = ImagesUploadViewController(with: self.collectionArray, storyId: "5678") uploadViewController.dismissView = {(sender : UIViewController?,initialize:Bool?,newObjects:[[AnyHashable:Any]]?) -> Void in if self.collectionArray.count > 0{ self.defaults.set(true, forKey: "deletedAllItems") }else{ self.defaults.set(false, forKey: "deletedAllItems") } if self.localPartition.count > 0{ if !(initialize!){ self.scrollToPostionAfterUpload = self.collectionArray.count - 1 self.collectionArray.append(contentsOf: newObjects!) self.upload = true runOnMainThread { if let local = self.defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ self.localPartition = local } self.reloadHeaderView = true self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.getPhotobyupload() self.stopAnimationLoader() self.turnOnEditMode() } } }else{ self.collectionArray = newObjects! self.scrollToPostionAfterUpload = 0 self.isFirstTime = true self.isLoadingStory = false runOnMainThread { self.reloadHeaderView = true let temp = self.collectionArray[0] var sizeOrg = temp["cloudFilePath"] as? String sizeOrg = URLConstants.imgDomain + sizeOrg! self.story_cover_photo_path = sizeOrg! self.getDataFromUrl(url: URL(string: sizeOrg!)!) { (data, response, error) in guard let data = data, error == nil else { return } self.coverdata = data DispatchQueue.main.async() { () -> Void in self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress)) self.collectionView.addGestureRecognizer(self.longPressGesture!) self.swapView = UIView(frame: CGRect.zero) self.swapImageView = UIImageView(image: UIImage(named: "Swap-white")) self.view.addSubview(self.collectionView) self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.upload = true self.getPhotobyupload() self.stopAnimationLoader() self.turnOnEditMode() if let local = self.defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ self.localPartition = local } } } } } } self.navigationController?.present(uploadViewController, animated: true, completion: { self.stopAnimationLoader() }) } }) } } } } } func getDataFromUrl(url: URL, completion: @escaping (_ data: UIImage?, _ response: URLResponse?, _ error: Error?) -> Void) { URLSession.shared.dataTask(with: url) { (data, response, error) in if let cachedVersion = cache.object(forKey: "\(url)" as NSString) { completion(cachedVersion, response, error) }else{ let image = UIImage(data: data!) cache.setObject(image!, forKey: "\(url)" as NSString) completion(image, response, error) } }.resume() } func IbaOpenGallery() { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: runOnMainThread { self.showImagePicker() } defaults.set(true, forKey: "forStoryMaking") break case .denied, .restricted : break //handle denied status case .notDetermined: // ask for permissions PHPhotoLibrary.requestAuthorization() { (status) -> Void in switch status { case .authorized: runOnMainThread { self.showImagePicker() } self.defaults.set(true, forKey: "forStoryMaking") // as above case .denied, .restricted: break // as above case .notDetermined: break // won't happen but still } } } } func selectPhotoFromPhotoLibrary() { } func getPhoto() { var totalPath = URLConstants.imgDomain for photoIndex in 0 ..< self.collectionArray.count { let temp = collectionArray[photoIndex] if let type = temp["type"] as? String{ if type == "Text"{ let textFrame = CGRect(x: 0, y: 0, width: SCREENWIDTH, height: SCREENHEIGHT - 100) let textImageView = UIView(frame: textFrame) let backgroundColor = temp["backgroundColor"] as? String ?? "" textImageView.backgroundColor = UIColor(hexString:backgroundColor) let title = temp["title"] as? String ?? "" let subTitle = temp["description"] as? String ?? "" let titleFont = UIFont(name: "Raleway-Regular", size: 18.0) let titleLabel = UILabel.init() titleLabel.text = title let textColor = temp["textColor"] as? String ?? "#000000" titleLabel.textColor = UIColor(hexString:textColor) titleLabel.numberOfLines = 0 titleLabel.font = titleFont // let textAlignment = temp["textAlignment"] as? Int ?? 1 let titleHeight = title.height(withConstrainedWidth: SCREENWIDTH - 20, font: titleFont!) let titleFrame = CGRect(x: 10, y: 40, width: SCREENWIDTH - 20, height: 100) titleLabel.frame = titleFrame let descriptionLabel = UILabel.init() descriptionLabel.text = title descriptionLabel.textColor = UIColor(hexString:textColor) descriptionLabel.numberOfLines = 0 descriptionLabel.font = titleFont // descriptionLabel.textAlignment = .center // CGFloat titleHeight = [self getHeightForText:title withFont:titleFont andWidth:SCREENWIDTH - 20]; // CGRect titleFrame = CGRectMake(10.0, 40.0, SCREENWIDTH - 20, 100); // titleLabel.frame = titleFrame; // [textImageView addSubview:titleLabel]; let titledescriptionHeight = subTitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: titleFont!) let titledescriptionFrame = CGRect(x: 10, y: titleHeight + 80, width: SCREENWIDTH - 20, height: titledescriptionHeight) descriptionLabel.frame = titledescriptionFrame if let allign = temp["textAlignment"] as? Int{ switch allign { case 0: titleLabel.textAlignment = .left descriptionLabel.textAlignment = .left case 1: titleLabel.textAlignment = .center descriptionLabel.textAlignment = .center case 2: titleLabel.textAlignment = .right descriptionLabel.textAlignment = .right case 3: titleLabel.textAlignment = .justified descriptionLabel.textAlignment = .justified default: break } } // titleLabel.textAlignment = .center // CGFloat titleHeight = [self getHeightForText:title withFont:titleFont andWidth:SCREENWIDTH - 20]; // CGRect titleFrame = CGRectMake(10.0, 40.0, SCREENWIDTH - 20, 100); // titleLabel.frame = titleFrame; // [textImageView addSubview:titleLabel]; textImageView.addSubview(titleLabel) textImageView.addSubview(descriptionLabel) let imageView = UIImage(view: textImageView) let Ptitle = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: Ptitle, video: false) // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } // photo.video = false mutablePhotos.append(photo) }else{ var url = temp["item_url"] as! String //if url.contains("http"){ // totalPath = url if type == "img"{ var urlImage = url.components(separatedBy: "album") if urlImage.count == 2 { var second = urlImage[1] second.remove(at: second.startIndex) url = totalPath + second }else{ let first = urlImage[0] url = totalPath + first } var version = url.components(separatedBy: "compressed") var afterAppending = url.components(separatedBy: "compressed") var widthImage = (version[0]) + "1440" + (afterAppending[1]) // totalPath = URLConstants.imgDomain + widthImage let data = NSData.init(contentsOf: URL(string: widthImage)!) let imageView = UIImage(data: data as! Data) let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title, video: false) // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } mutablePhotos.append(photo) }else if type == "video"{ if let image = thumbnailImageForFileUrl(URL(string: url)!){ if let data = UIImagePNGRepresentation(image){ // let data = NSData.init(contentsOf: URL(string: totalPath)!) let imageView = UIImage(data: data as! Data) let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title,videoUrl: url,video:true) // photo.videoUrl = URL(string: url)! //photo.video = true mutablePhotos.append(photo) } } } } }else{ var url = temp["item_url"] as? String if url != ""{ var urlImage = url?.components(separatedBy: "album") var totalPath = URLConstants.imgDomain url = totalPath + (urlImage?[1])! var version = url?.components(separatedBy: "compressed") var afterAppending = url?.components(separatedBy: "compressed") var widthImage = (version?[0])! + "1080" + (afterAppending?[1])! // let sizeOrg = (temp as AnyObject).object(forKey: "data") as? Data let data = NSData.init(contentsOf: URL(string: widthImage)!) let imageView = UIImage(data: data as! Data) //let image = images[photoIndex] let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title, video: false) mutablePhotos.append(photo) } } } } func getPhotobyupload() { for photoIndex in 0 ..< self.collectionArray.count { let temp = collectionArray[photoIndex] var totalPath = URLConstants.imgDomain let type = temp["type"] as! String if type == "Text"{ let textFrame = CGRect(x: 0, y: 0, width: SCREENWIDTH, height: SCREENHEIGHT - 100) let textImageView = UIView(frame: textFrame) textImageView.backgroundColor = UIColor.blue let title = temp["title"] as! String let subTitle = temp["description"] as! String let titleFont = UIFont(name: "Raleway-Regular", size: 18.0) let titleLabel = UILabel.init() titleLabel.text = title titleLabel.textColor = UIColor(hexString:temp["textColor"] as! String) titleLabel.numberOfLines = 0 titleLabel.font = titleFont titleLabel.textAlignment = .center let titleHeight = title.height(withConstrainedWidth: SCREENWIDTH - 20, font: titleFont!) let titleFrame = CGRect(x: 10, y: 40, width: SCREENWIDTH - 20, height: 100) titleLabel.frame = titleFrame textImageView.addSubview(titleLabel) let descriptionLabel = UILabel.init() descriptionLabel.text = title descriptionLabel.textColor = UIColor(hexString:temp["textColor"] as! String) descriptionLabel.numberOfLines = 0 descriptionLabel.font = titleFont descriptionLabel.textAlignment = .center // CGFloat titleHeight = [self getHeightForText:title withFont:titleFont andWidth:SCREENWIDTH - 20]; // CGRect titleFrame = CGRectMake(10.0, 40.0, SCREENWIDTH - 20, 100); // titleLabel.frame = titleFrame; // [textImageView addSubview:titleLabel]; let titledescriptionHeight = subTitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: titleFont!) let titledescriptionFrame = CGRect(x: 10, y: titleHeight + 80, width: SCREENWIDTH - 20, height: titledescriptionHeight) descriptionLabel.frame = titledescriptionFrame textImageView.addSubview(descriptionLabel) let imageView = UIImage(view: textImageView) let Ptitle = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: Ptitle, video: false) // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } // photo.video = false mutablePhotos.append(photo) }else{ var url = temp["item_url"] as! String if type == "img"{ var urlImage = url.components(separatedBy: "album") if urlImage.count == 2 { var second = urlImage[1] second.remove(at: second.startIndex) url = totalPath + second }else{ let first = urlImage[0] url = totalPath + first } var version = url.components(separatedBy: "compressed") var afterAppending = url.components(separatedBy: "compressed") var widthImage = (version[0]) + "1920" + (afterAppending[1]) // totalPath = URLConstants.imgDomain + widthImage let data = NSData.init(contentsOf: URL(string: widthImage)!) let imageView = UIImage(data: data as! Data) let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title, video: false) // // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } // photo.video = false mutablePhotos.append(photo) }else if type == "video"{ if let image = thumbnailImageForFileUrl(URL(string: url)!){ if let data = UIImagePNGRepresentation(image){ // let data = NSData.init(contentsOf: URL(string: totalPath)!) let imageView = UIImage(data: data as! Data) let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title,videoUrl: url,video:true) // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } // photo.videoUrl = URL(string: url)! // photo.video = true mutablePhotos.append(photo) } } } } } } func thumbnailImageForFileUrl(_ fileUrl: URL) -> UIImage? { if let cachedVersion = cache.object(forKey: "\(fileUrl)" as NSString) { return cachedVersion }else{ let asset = AVAsset(url: fileUrl) let imageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.appliesPreferredTrackTransform = true let durationSeconds = CMTimeGetSeconds(asset.duration) do { let thumbnailCGImage = try imageGenerator.copyCGImage(at: CMTimeMake(Int64(durationSeconds/1.0), 600), actualTime: nil) let images = UIImage(cgImage: thumbnailCGImage) cache.setObject(images, forKey: "\(fileUrl)" as NSString) return images } catch let err { print(err) } } return nil } } extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource,NYTPhotosViewControllerDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.collectionArray.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // UNDO This Comments if editTurnOn{ let previouslySelectedItem = selectedItemIndex if editingTextFieldIndex == -1{ if(selectedItemIndex == indexPath.item){ self.setInitialToolbarConfiguration() //[self setInitialToolbarConfiguration]; selectedItemIndex = -1 self.title = "" }else{ selectedItemIndex = indexPath.item let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if type == "Text"{ self.editToolbarConfigurationForTextCells() self.title = "Text" } else{ self.changeToEnrichMode() } } var indexPathsToReload = [IndexPath]() if previouslySelectedItem != -1{ indexPathsToReload.append(IndexPath(item: previouslySelectedItem, section: 0)) } if self.selectedItemIndex != -1{ indexPathsToReload.append(IndexPath(item: self.selectedItemIndex, section: 0)) } DispatchQueue.main.async { self.collectionView.performBatchUpdates({ print(indexPathsToReload) self.collectionView.reloadItems(at: indexPathsToReload) }, completion: { (test) in }) } } }else{ selectedIndexPath = indexPath.item let photosViewController = NYTPhotosViewController(photos: mutablePhotos) let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if type == "Text"{ guard let textCell = self.collectionView.cellForItem(at: indexPath) as? TextCellStoryCollectionViewCell else{ return } let screenshotOfTextCell = UIImage(view: textCell) }else if type == "video"{ guard let VideoCell = self.collectionView.cellForItem(at: indexPath) as? ImageViewCollectionViewCell else{ return } guard let player = VideoCell.player else { return } if (player.error == nil) && (player.rate == 0){ VideoCell.player.pause() }else{ VideoCell.player.play() } }else{ let set :IndexSet = [0] self.collectionView.reloadSections(set) selectedItemIndex = indexPath.row photosViewController.display(mutablePhotos[indexPath.row], animated: false) photosViewController.delegate = self self.present(photosViewController, animated: true, completion: nil) } } } func photosViewControllerDidDismiss(_ photosViewController: NYTPhotosViewController) { // self.collectionView.reloadData() } func photosViewController(_ photosViewController: NYTPhotosViewController, didNavigateTo photo: NYTPhoto, at photoIndex: UInt) { self.selectedIndexPath = Int(photoIndex) let visiblePaths = self.collectionView.indexPathsForVisibleItems if (visiblePaths.contains(IndexPath(item: self.selectedIndexPath, section: 0))){ self.collectionView.selectItem(at: IndexPath(item: self.selectedIndexPath, section: 0), animated: false, scrollPosition: .centeredVertically) } } func photosViewController(_ photosViewController: NYTPhotosViewController, referenceViewFor photo: NYTPhoto) -> UIView? { let itemAtIndex = self.collectionArray[selectedIndexPath] let type = itemAtIndex["type"] as? String ?? "Img" if type == "Text"{ guard let textCell = self.collectionView.cellForItem(at: IndexPath(item: selectedIndexPath, section: 0)) as? TextCellStoryCollectionViewCell else{ return nil } return textCell.contentView }else{ guard let imgCell = self.collectionView.cellForItem(at: IndexPath(item: selectedIndexPath, section: 0)) as? ImageViewCollectionViewCell else{ return nil } // let btn = UIButton(frame: CGRect(x: self.view.frame.size.width/2, y: self.view.frame.size.height/2, width: 40, height: 40)) // btn.addTarget(self, action: #selector(setBackgroundColorForTextCell(_:)), for: UIControlEvents.touchUpInside) // // // imgCell.contentView.addSubview(btn) return imgCell.contentView } return nil } // - (void)fullScreenButtonTapped:(UIButton *)sender { // // ImageCollectionViewCell *cell = (ImageCollectionViewCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:sender.tag inSection:0]]; // cell.player.muted = YES; // [cell.volumeButton setImage:[UIImage imageNamed:@"volume_mute"] forState:UIControlStateNormal]; // // NSURL *videoUrl = [NSURL URLWithString:[[_collectionViewItemsArray objectAtIndex:sender.tag] objectForKey:@"cloudFilePath"]]; // NSLog(@"singleTapf=gesture == %@",videoUrl); // // // AVPlayer *player = [AVPlayer playerWithURL:videoUrl]; // // // create a player view controller // AVPlayerViewController *controller = [[AVPlayerViewController alloc] init]; // [self presentViewController:controller animated:YES completion:nil]; // controller.player = player; // [player play]; // } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var size = CGSize.zero let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if isViewStory { if type == "Text"{ size = temp["item_size"] as? CGSize ?? CGSize(width: SCREENWIDTH, height: 200) // var cgsize = CGSizeFromString(sizeOrg) // size = cgsize }else{ let sizeOrg = temp["item_size"] as? CGSize size = sizeOrg! } }else{ if type == "video"{ size = temp["item_size"] as! CGSize // var cgsize = CGSizeFromString(sizeOrg!) //= cgsize }else if type == "Text"{ size = temp["item_size"] as? CGSize ?? CGSize(width: SCREENWIDTH, height: 200) // = CGSizeFromString(sizeOrg!) }else{ size = imageForIndexPath(indexPath) } } return size //CGSize(width: size.width*percentWidth/4, height: size.height/4) } func imageForIndexPath(_ indexPath:IndexPath) -> CGSize { let temp = collectionArray[indexPath.row] let sizeOrg = temp["item_size"] as? CGSize ?? CGSize.zero return sizeOrg } func getDataFromUrl(urL:URL, completion: @escaping ((_ data: NSData?) -> Void)) { URLSession.shared.dataTask(with: urL) { (data, response, error) in completion(data as NSData?) }.resume() } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if isViewStory { if type == "Text"{ if let cell = cell as? TextCellStoryCollectionViewCell{ if selectedItemIndex == indexPath.item{ cell.layer.borderWidth = 2 cell.layer.borderColor = UIColor(hexString:"#32C5B6").cgColor } cell.alpha = 1 cell.isHidden = false cell.titleLabel.isUserInteractionEnabled = false cell.subTitleLabel.isUserInteractionEnabled = false cell.layer.borderWidth = CGFloat.leastNormalMagnitude cell.layer.borderColor = UIColor.clear.cgColor if let title = temp["title"] as? String{ cell.titleLabel.text = title }else{ } if let subTitleLabel = temp["description"] as? String{ cell.subTitleLabel.text = subTitleLabel }else{ } //let backgroundColor = temp["backgroundColor"] as? String ?? "#ffffff" if let allign = temp["textAlignment"] as? Int{ switch allign { case 0: cell.titleLabel.textAlignment = .left cell.subTitleLabel.textAlignment = .left case 1: cell.titleLabel.textAlignment = .center cell.subTitleLabel.textAlignment = .center case 2: cell.titleLabel.textAlignment = .right cell.subTitleLabel.textAlignment = .right case 3: cell.titleLabel.textAlignment = .justified cell.subTitleLabel.textAlignment = .justified default: break } } //cell.titleLabel.inputAccessoryView = self.keyboardView //cell.subTitleLabel.inputAccessoryView = self.keyboardView if let textColor = temp["textColor"] as? String { cell.titleLabel.textColor = UIColor(hexString:textColor) }else{ cell.titleLabel.textColor = UIColor(hexString:"#ffffff") } if let backgroundColor = temp["backgroundColor"] as? String { cell.myView.backgroundColor = UIColor(hexString:backgroundColor) }else{ cell.myView.backgroundColor = UIColor(hexString:"#ffffff") } } }else{ if let imageViewCell = cell as? ImageViewCollectionViewCell{ if type == "video"{ imageViewCell.layer.borderWidth = CGFloat.leastNormalMagnitude imageViewCell.layer.borderColor = UIColor.clear.cgColor imageViewCell.videoAsSubView.isHidden = false imageViewCell.volumeBtn.isHidden = false //imageViewCell.fullScreenBtn.isHidden = false if let player_layer = temp["player_layer"] as? AVPlayerLayer{ let layer = temp["player"] as! AVPlayer if let isLayerPresent = (imageViewCell.videoAsSubView.layer.sublayers?.contains(player_layer)){ if !isLayerPresent{ imageViewCell.videoAsSubView.layer.addSublayer(player_layer) imageViewCell.player = layer //imageViewCell.playerItm = temp.playerItm imageViewCell.player.isMuted = false // imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill // imageViewCell.playerLayer.needsDisplayOnBoundsChange = true // imageViewCell.volumeBtn.setImage(UIImage(named: "icon_muted"), for: .normal) imageViewCell.player.play() NotificationCenter.default.addObserver(self,selector: #selector(self.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: imageViewCell.player.currentItem) }else{ imageViewCell.videoAsSubView.layer.addSublayer(player_layer) imageViewCell.player = layer // imageViewCell.playerItm = temp.playerItm imageViewCell.player.isMuted = false //imageViewCell.iboSound.setImage(UIImage(named: "icon_muted"), for: .normal) imageViewCell.player.play() // imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill print("layer is there") // imageViewCell.playerLayer.needsDisplayOnBoundsChange = true NotificationCenter.default.addObserver(self,selector: #selector(self.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: imageViewCell.player.currentItem) } }else{ // imageViewCell.iboVideoView.addGestureRecognizer(doubleTapVideo) // imageViewCell.iboVideoView.addGestureRecognizer(singleTapvideo) // singleTapvideo.require(toFail: doubleTapVideo) imageViewCell.videoAsSubView.layer.addSublayer(player_layer) imageViewCell.player = layer // imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill //imageViewCell.playerItm = temp.playerItm imageViewCell.player.isMuted = false // imageViewCell.iboSound.setImage(UIImage(named: "icon_muted"), for: .normal) imageViewCell.player.play() NotificationCenter.default.addObserver(self,selector: #selector(self.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: imageViewCell.player.currentItem) } }else{ var video_url = temp["item_url"] as? String ?? "" if (video_url.contains("http")){ }else{ video_url = URLConstants.imgDomain + video_url } imageViewCell.videoAsSubView.isHidden = true // imageViewCell.volumeBtn.isHidden = true imageViewCell.imageViewToShow.image = UIImage(named: "process") imageViewCell.imageViewToShow.contentMode = .scaleAspectFill DispatchQueue.global(qos: .userInitiated).async { imageViewCell.playerItm = AVPlayerItem.init(url: URL(string: video_url)!) DispatchQueue.main.sync(execute: { imageViewCell.player = AVPlayer(playerItem: imageViewCell.playerItm) imageViewCell.playerLayer = AVPlayerLayer(player: imageViewCell.player) imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill imageViewCell.player.actionAtItemEnd = .none imageViewCell.playerLayer.frame = imageViewCell.videoAsSubView.bounds imageViewCell.playerLayer.needsDisplayOnBoundsChange = true //cell.playerLayer.frame = cell.videoAsSubview.bounds; imageViewCell.player.isMuted = true // imageViewCell.volumeBtn.setImage(UIImage(named: "icon_muted"), for: .normal) //cell.iboVideoView.layer.sublayers = nil imageViewCell.imageViewToShow.image = nil imageViewCell.videoAsSubView.isHidden = false // imageViewCell.volumeBtn.isHidden = false imageViewCell.videoAsSubView.layer.addSublayer(imageViewCell.playerLayer) imageViewCell.player.play() self.collectionArray[indexPath.row].updateValue(imageViewCell.playerLayer, forKey: "player_layer") self.collectionArray[indexPath.row].updateValue(imageViewCell.player, forKey: "player") //temp // dictToAdd.updateValue("Video" as AnyObject, forKey: "type") // temp.player = imageViewCell.player //temp.playerLayer = imageViewCell.playerLayer NotificationCenter.default.addObserver(self,selector: #selector(self.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: imageViewCell.player.currentItem) }) } } } else{ var url = temp["item_url"] as? String var urlImage = url?.components(separatedBy: "album") let totalPath = URLConstants.imgDomain if urlImage?.count == 2 { let second = urlImage?[1] url = totalPath + second! }else{ if let first = urlImage?[0]{ url = totalPath + first } } //url = totalPath + (urlImage?[1])! var version = url?.components(separatedBy: "compressed") var afterAppending = url?.components(separatedBy: "compressed") var widthImage = (version?[0])! + "1080" + (afterAppending?[1])! imageViewCell.imageViewToShow.sd_setImage(with: URL(string: widthImage), placeholderImage: UIImage(named: "")) imageViewCell.imageViewToShow.contentMode = .scaleAspectFill imageViewCell.videoAsSubView.isHidden = true imageViewCell.volumeBtn.isHidden = true //imageViewCell.fullScreenBtn.isHidden = true imageViewCell.videoPlayBtn.isHidden = true //imageViewCell.backgroundColor = UIColor.brown imageViewCell.clipsToBounds = true } } } }else{ // edit mode On if let imageViewCell = cell as? ImageViewCollectionViewCell{ if selectedItemIndex == indexPath.item{ imageViewCell.layer.borderWidth = 2 imageViewCell.layer.borderColor = UIColor(red: 50/255, green: 197/255, blue: 182/255, alpha: 1).cgColor } //imageViewCell.alpha = 1 // imageViewCell.isHidden = false if type == "img"{ let temp = collectionArray[indexPath.row] var url = temp["item_url"] as? String var urlImage = url?.components(separatedBy: "album") let totalPath = URLConstants.imgDomain if urlImage?.count == 2 { let second = urlImage?[1] url = totalPath + second! }else{ if let first = urlImage?[0]{ url = totalPath + first } } //url = totalPath + (urlImage?[1])! var version = url?.components(separatedBy: "compressed") var afterAppending = url?.components(separatedBy: "compressed") var widthImage = (version?[0])! + "1080" + (afterAppending?[1])! imageViewCell.videoAsSubView.isHidden = true imageViewCell.videoPlayBtn.isHidden = true imageViewCell.volumeBtn.isHidden = true //imageViewCell.fullScreenBtn.isHidden = true imageViewCell.imageViewToShow.sd_setImage(with: URL(string: widthImage), placeholderImage: UIImage(named: "")) imageViewCell.imageViewToShow.contentMode = .scaleAspectFill imageViewCell.clipsToBounds = true }else if type == "video"{ let temp = collectionArray[indexPath.row] imageViewCell.videoAsSubView.layer.sublayers = nil imageViewCell.videoAsSubView.isHidden = false imageViewCell.volumeBtn.isHidden = false // imageViewCell.player.isMuted = true //imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill //imageViewCell.playerLayer.needsDisplayOnBoundsChange = true imageViewCell.layer.borderWidth = CGFloat.leastNormalMagnitude imageViewCell.layer.borderColor = UIColor.clear.cgColor // imageViewCell.player.pause() DispatchQueue.global(qos: .userInitiated).async { var url = temp["item_url"] as? String ?? "" if (url.contains("http")){ }else{ url = URLConstants.imgDomain + url } if let image = self.thumbnailImageForFileUrl(URL(string: url)!){ DispatchQueue.main.async { imageViewCell.imageViewToShow.image = image } } } } }else{ if type == "Text"{ if let cell = cell as? TextCellStoryCollectionViewCell{ if selectedItemIndex == indexPath.item{ cell.layer.borderWidth = 2 cell.layer.borderColor = UIColor(red: 50/255, green: 197/255, blue: 182/255, alpha: 1).cgColor } cell.alpha = 1 cell.isHidden = false cell.titleLabel.isUserInteractionEnabled = false cell.subTitleLabel.isUserInteractionEnabled = false cell.layer.borderWidth = CGFloat.leastNormalMagnitude cell.layer.borderColor = UIColor.clear.cgColor cell.titleLabel.text = temp["title"] as! String cell.subTitleLabel.text = temp["description"] as! String //cell.subTitleLabel.textColor = if let allign = temp["textAlignment"] as? Int{ switch allign { case 0: cell.titleLabel.textAlignment = .left cell.subTitleLabel.textAlignment = .left case 1: cell.titleLabel.textAlignment = .center cell.subTitleLabel.textAlignment = .center case 2: cell.titleLabel.textAlignment = .right cell.subTitleLabel.textAlignment = .right case 3: cell.titleLabel.textAlignment = .justified cell.subTitleLabel.textAlignment = .justified default: break } } //cell.titleLabel.inputAccessoryView = self.keyboardView //cell.subTitleLabel.inputAccessoryView = self.keyboardView cell.titleLabel.textColor = UIColor(hexString:(temp["textColor"] as? String ?? "#ffffff")) cell.myView.backgroundColor = UIColor(hexString:(temp["backgroundColor"] as? String ?? "#ffffff")) } } } } } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if !editTurnOn{ let indexData = self.collectionArray[indexPath.item] let type = indexData["type"] as! String if type == "video" { if let cell1 = cell as? ImageViewCollectionViewCell{ //cell1.player.replaceCurrentItem(with: nil) if let player = cell1.player{ player.isMuted = true } } } } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if type == "Text" { var textViewCell:TextCellStoryCollectionViewCell! if (textViewCell == nil) { textViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellTextIdentifier, for: indexPath) as! TextCellStoryCollectionViewCell } textViewCell.myView.layer.borderWidth = CGFloat.greatestFiniteMagnitude textViewCell.myView.layer.borderColor = UIColor.clear.cgColor if editTurnOn { if selectedItemIndex == indexPath.item{ textViewCell.myView.layer.borderWidth = 2 // textViewCell.backgroundColor = UIColor.red textViewCell.myView.layer.borderColor = UIColor(red: 50/255, green: 197/255, blue: 182/255, alpha: 1).cgColor } } return textViewCell }else{ var imageViewCell:ImageViewCollectionViewCell! if (imageViewCell == nil) { imageViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellIdentifier, for: indexPath) as! ImageViewCollectionViewCell } imageViewCell.layer.borderWidth = CGFloat.greatestFiniteMagnitude imageViewCell.layer.borderColor = UIColor.clear.cgColor if editTurnOn { if selectedItemIndex == indexPath.item{ imageViewCell.layer.borderWidth = 2 imageViewCell.layer.borderColor = UIColor(red: 50/255, green: 197/255, blue: 182/255, alpha: 1).cgColor } } if type != "video"{ let code = temp["hexCode"] as? String ?? "#e0cfb9" let components = code.components(separatedBy: ",") imageViewCell.backgroundColor = UIColor(hexString:components.first!) } //imageViewCell.alpha = 1 // imageViewCell.isHidden = false imageViewCell.layer.shouldRasterize = true; imageViewCell.layer.rasterizationScale = UIScreen.main.scale return imageViewCell } } func restartVideoFromBeginning(notification:NSNotification) { let seconds : Int64 = 0 let preferredTimeScale : Int32 = 1 let seekTime : CMTime = CMTimeMake(seconds, preferredTimeScale) let player : AVPlayerItem = notification.object as! AVPlayerItem player.seek(to: seekTime) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } } extension String { var parseJSONString: AnyObject? { let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false) if let jsonData = data { // Will return an object or nil if JSON decoding fails return try! JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject? } else { // Lossless conversion of the string was not possible return nil } } } extension Dictionary { mutating func update(other:Dictionary) { for (key,value) in other { self.updateValue(value, forKey:key) } } }
48.632121
282
0.466947
56dcbb420a1f00e8b16f502736f58405877f3601
166,809
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: steammessages_clientserver_friends.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } struct CMsgClientFriendMsg { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var steamid: UInt64 { get {return _steamid ?? 0} set {_steamid = newValue} } /// Returns true if `steamid` has been explicitly set. var hasSteamid: Bool {return self._steamid != nil} /// Clears the value of `steamid`. Subsequent reads from it will return its default value. mutating func clearSteamid() {self._steamid = nil} var chatEntryType: Int32 { get {return _chatEntryType ?? 0} set {_chatEntryType = newValue} } /// Returns true if `chatEntryType` has been explicitly set. var hasChatEntryType: Bool {return self._chatEntryType != nil} /// Clears the value of `chatEntryType`. Subsequent reads from it will return its default value. mutating func clearChatEntryType() {self._chatEntryType = nil} var message: Data { get {return _message ?? Data()} set {_message = newValue} } /// Returns true if `message` has been explicitly set. var hasMessage: Bool {return self._message != nil} /// Clears the value of `message`. Subsequent reads from it will return its default value. mutating func clearMessage() {self._message = nil} var rtime32ServerTimestamp: UInt32 { get {return _rtime32ServerTimestamp ?? 0} set {_rtime32ServerTimestamp = newValue} } /// Returns true if `rtime32ServerTimestamp` has been explicitly set. var hasRtime32ServerTimestamp: Bool {return self._rtime32ServerTimestamp != nil} /// Clears the value of `rtime32ServerTimestamp`. Subsequent reads from it will return its default value. mutating func clearRtime32ServerTimestamp() {self._rtime32ServerTimestamp = nil} var echoToSender: Bool { get {return _echoToSender ?? false} set {_echoToSender = newValue} } /// Returns true if `echoToSender` has been explicitly set. var hasEchoToSender: Bool {return self._echoToSender != nil} /// Clears the value of `echoToSender`. Subsequent reads from it will return its default value. mutating func clearEchoToSender() {self._echoToSender = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _steamid: UInt64? = nil fileprivate var _chatEntryType: Int32? = nil fileprivate var _message: Data? = nil fileprivate var _rtime32ServerTimestamp: UInt32? = nil fileprivate var _echoToSender: Bool? = nil } struct CMsgClientFriendMsgIncoming { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var steamidFrom: UInt64 { get {return _steamidFrom ?? 0} set {_steamidFrom = newValue} } /// Returns true if `steamidFrom` has been explicitly set. var hasSteamidFrom: Bool {return self._steamidFrom != nil} /// Clears the value of `steamidFrom`. Subsequent reads from it will return its default value. mutating func clearSteamidFrom() {self._steamidFrom = nil} var chatEntryType: Int32 { get {return _chatEntryType ?? 0} set {_chatEntryType = newValue} } /// Returns true if `chatEntryType` has been explicitly set. var hasChatEntryType: Bool {return self._chatEntryType != nil} /// Clears the value of `chatEntryType`. Subsequent reads from it will return its default value. mutating func clearChatEntryType() {self._chatEntryType = nil} var fromLimitedAccount: Bool { get {return _fromLimitedAccount ?? false} set {_fromLimitedAccount = newValue} } /// Returns true if `fromLimitedAccount` has been explicitly set. var hasFromLimitedAccount: Bool {return self._fromLimitedAccount != nil} /// Clears the value of `fromLimitedAccount`. Subsequent reads from it will return its default value. mutating func clearFromLimitedAccount() {self._fromLimitedAccount = nil} var message: Data { get {return _message ?? Data()} set {_message = newValue} } /// Returns true if `message` has been explicitly set. var hasMessage: Bool {return self._message != nil} /// Clears the value of `message`. Subsequent reads from it will return its default value. mutating func clearMessage() {self._message = nil} var rtime32ServerTimestamp: UInt32 { get {return _rtime32ServerTimestamp ?? 0} set {_rtime32ServerTimestamp = newValue} } /// Returns true if `rtime32ServerTimestamp` has been explicitly set. var hasRtime32ServerTimestamp: Bool {return self._rtime32ServerTimestamp != nil} /// Clears the value of `rtime32ServerTimestamp`. Subsequent reads from it will return its default value. mutating func clearRtime32ServerTimestamp() {self._rtime32ServerTimestamp = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _steamidFrom: UInt64? = nil fileprivate var _chatEntryType: Int32? = nil fileprivate var _fromLimitedAccount: Bool? = nil fileprivate var _message: Data? = nil fileprivate var _rtime32ServerTimestamp: UInt32? = nil } struct CMsgClientAddFriend { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var steamidToAdd: UInt64 { get {return _steamidToAdd ?? 0} set {_steamidToAdd = newValue} } /// Returns true if `steamidToAdd` has been explicitly set. var hasSteamidToAdd: Bool {return self._steamidToAdd != nil} /// Clears the value of `steamidToAdd`. Subsequent reads from it will return its default value. mutating func clearSteamidToAdd() {self._steamidToAdd = nil} var accountnameOrEmailToAdd: String { get {return _accountnameOrEmailToAdd ?? String()} set {_accountnameOrEmailToAdd = newValue} } /// Returns true if `accountnameOrEmailToAdd` has been explicitly set. var hasAccountnameOrEmailToAdd: Bool {return self._accountnameOrEmailToAdd != nil} /// Clears the value of `accountnameOrEmailToAdd`. Subsequent reads from it will return its default value. mutating func clearAccountnameOrEmailToAdd() {self._accountnameOrEmailToAdd = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _steamidToAdd: UInt64? = nil fileprivate var _accountnameOrEmailToAdd: String? = nil } struct CMsgClientAddFriendResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var eresult: Int32 { get {return _eresult ?? 2} set {_eresult = newValue} } /// Returns true if `eresult` has been explicitly set. var hasEresult: Bool {return self._eresult != nil} /// Clears the value of `eresult`. Subsequent reads from it will return its default value. mutating func clearEresult() {self._eresult = nil} var steamIDAdded: UInt64 { get {return _steamIDAdded ?? 0} set {_steamIDAdded = newValue} } /// Returns true if `steamIDAdded` has been explicitly set. var hasSteamIDAdded: Bool {return self._steamIDAdded != nil} /// Clears the value of `steamIDAdded`. Subsequent reads from it will return its default value. mutating func clearSteamIDAdded() {self._steamIDAdded = nil} var personaNameAdded: String { get {return _personaNameAdded ?? String()} set {_personaNameAdded = newValue} } /// Returns true if `personaNameAdded` has been explicitly set. var hasPersonaNameAdded: Bool {return self._personaNameAdded != nil} /// Clears the value of `personaNameAdded`. Subsequent reads from it will return its default value. mutating func clearPersonaNameAdded() {self._personaNameAdded = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _eresult: Int32? = nil fileprivate var _steamIDAdded: UInt64? = nil fileprivate var _personaNameAdded: String? = nil } struct CMsgClientRemoveFriend { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var friendid: UInt64 { get {return _friendid ?? 0} set {_friendid = newValue} } /// Returns true if `friendid` has been explicitly set. var hasFriendid: Bool {return self._friendid != nil} /// Clears the value of `friendid`. Subsequent reads from it will return its default value. mutating func clearFriendid() {self._friendid = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _friendid: UInt64? = nil } struct CMsgClientHideFriend { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var friendid: UInt64 { get {return _friendid ?? 0} set {_friendid = newValue} } /// Returns true if `friendid` has been explicitly set. var hasFriendid: Bool {return self._friendid != nil} /// Clears the value of `friendid`. Subsequent reads from it will return its default value. mutating func clearFriendid() {self._friendid = nil} var hide: Bool { get {return _hide ?? false} set {_hide = newValue} } /// Returns true if `hide` has been explicitly set. var hasHide: Bool {return self._hide != nil} /// Clears the value of `hide`. Subsequent reads from it will return its default value. mutating func clearHide() {self._hide = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _friendid: UInt64? = nil fileprivate var _hide: Bool? = nil } struct CMsgClientFriendsList { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var bincremental: Bool { get {return _bincremental ?? false} set {_bincremental = newValue} } /// Returns true if `bincremental` has been explicitly set. var hasBincremental: Bool {return self._bincremental != nil} /// Clears the value of `bincremental`. Subsequent reads from it will return its default value. mutating func clearBincremental() {self._bincremental = nil} var friends: [CMsgClientFriendsList.Friend] = [] var maxFriendCount: UInt32 { get {return _maxFriendCount ?? 0} set {_maxFriendCount = newValue} } /// Returns true if `maxFriendCount` has been explicitly set. var hasMaxFriendCount: Bool {return self._maxFriendCount != nil} /// Clears the value of `maxFriendCount`. Subsequent reads from it will return its default value. mutating func clearMaxFriendCount() {self._maxFriendCount = nil} var activeFriendCount: UInt32 { get {return _activeFriendCount ?? 0} set {_activeFriendCount = newValue} } /// Returns true if `activeFriendCount` has been explicitly set. var hasActiveFriendCount: Bool {return self._activeFriendCount != nil} /// Clears the value of `activeFriendCount`. Subsequent reads from it will return its default value. mutating func clearActiveFriendCount() {self._activeFriendCount = nil} var friendsLimitHit: Bool { get {return _friendsLimitHit ?? false} set {_friendsLimitHit = newValue} } /// Returns true if `friendsLimitHit` has been explicitly set. var hasFriendsLimitHit: Bool {return self._friendsLimitHit != nil} /// Clears the value of `friendsLimitHit`. Subsequent reads from it will return its default value. mutating func clearFriendsLimitHit() {self._friendsLimitHit = nil} var unknownFields = SwiftProtobuf.UnknownStorage() struct Friend { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var ulfriendid: UInt64 { get {return _ulfriendid ?? 0} set {_ulfriendid = newValue} } /// Returns true if `ulfriendid` has been explicitly set. var hasUlfriendid: Bool {return self._ulfriendid != nil} /// Clears the value of `ulfriendid`. Subsequent reads from it will return its default value. mutating func clearUlfriendid() {self._ulfriendid = nil} var efriendrelationship: UInt32 { get {return _efriendrelationship ?? 0} set {_efriendrelationship = newValue} } /// Returns true if `efriendrelationship` has been explicitly set. var hasEfriendrelationship: Bool {return self._efriendrelationship != nil} /// Clears the value of `efriendrelationship`. Subsequent reads from it will return its default value. mutating func clearEfriendrelationship() {self._efriendrelationship = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _ulfriendid: UInt64? = nil fileprivate var _efriendrelationship: UInt32? = nil } init() {} fileprivate var _bincremental: Bool? = nil fileprivate var _maxFriendCount: UInt32? = nil fileprivate var _activeFriendCount: UInt32? = nil fileprivate var _friendsLimitHit: Bool? = nil } struct CMsgClientFriendsGroupsList { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var bremoval: Bool { get {return _bremoval ?? false} set {_bremoval = newValue} } /// Returns true if `bremoval` has been explicitly set. var hasBremoval: Bool {return self._bremoval != nil} /// Clears the value of `bremoval`. Subsequent reads from it will return its default value. mutating func clearBremoval() {self._bremoval = nil} var bincremental: Bool { get {return _bincremental ?? false} set {_bincremental = newValue} } /// Returns true if `bincremental` has been explicitly set. var hasBincremental: Bool {return self._bincremental != nil} /// Clears the value of `bincremental`. Subsequent reads from it will return its default value. mutating func clearBincremental() {self._bincremental = nil} var friendGroups: [CMsgClientFriendsGroupsList.FriendGroup] = [] var memberships: [CMsgClientFriendsGroupsList.FriendGroupsMembership] = [] var unknownFields = SwiftProtobuf.UnknownStorage() struct FriendGroup { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var nGroupID: Int32 { get {return _nGroupID ?? 0} set {_nGroupID = newValue} } /// Returns true if `nGroupID` has been explicitly set. var hasNGroupID: Bool {return self._nGroupID != nil} /// Clears the value of `nGroupID`. Subsequent reads from it will return its default value. mutating func clearNGroupID() {self._nGroupID = nil} var strGroupName: String { get {return _strGroupName ?? String()} set {_strGroupName = newValue} } /// Returns true if `strGroupName` has been explicitly set. var hasStrGroupName: Bool {return self._strGroupName != nil} /// Clears the value of `strGroupName`. Subsequent reads from it will return its default value. mutating func clearStrGroupName() {self._strGroupName = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _nGroupID: Int32? = nil fileprivate var _strGroupName: String? = nil } struct FriendGroupsMembership { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var ulSteamID: UInt64 { get {return _ulSteamID ?? 0} set {_ulSteamID = newValue} } /// Returns true if `ulSteamID` has been explicitly set. var hasUlSteamID: Bool {return self._ulSteamID != nil} /// Clears the value of `ulSteamID`. Subsequent reads from it will return its default value. mutating func clearUlSteamID() {self._ulSteamID = nil} var nGroupID: Int32 { get {return _nGroupID ?? 0} set {_nGroupID = newValue} } /// Returns true if `nGroupID` has been explicitly set. var hasNGroupID: Bool {return self._nGroupID != nil} /// Clears the value of `nGroupID`. Subsequent reads from it will return its default value. mutating func clearNGroupID() {self._nGroupID = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _ulSteamID: UInt64? = nil fileprivate var _nGroupID: Int32? = nil } init() {} fileprivate var _bremoval: Bool? = nil fileprivate var _bincremental: Bool? = nil } struct CMsgClientPlayerNicknameList { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var removal: Bool { get {return _removal ?? false} set {_removal = newValue} } /// Returns true if `removal` has been explicitly set. var hasRemoval: Bool {return self._removal != nil} /// Clears the value of `removal`. Subsequent reads from it will return its default value. mutating func clearRemoval() {self._removal = nil} var incremental: Bool { get {return _incremental ?? false} set {_incremental = newValue} } /// Returns true if `incremental` has been explicitly set. var hasIncremental: Bool {return self._incremental != nil} /// Clears the value of `incremental`. Subsequent reads from it will return its default value. mutating func clearIncremental() {self._incremental = nil} var nicknames: [CMsgClientPlayerNicknameList.PlayerNickname] = [] var unknownFields = SwiftProtobuf.UnknownStorage() struct PlayerNickname { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var steamid: UInt64 { get {return _steamid ?? 0} set {_steamid = newValue} } /// Returns true if `steamid` has been explicitly set. var hasSteamid: Bool {return self._steamid != nil} /// Clears the value of `steamid`. Subsequent reads from it will return its default value. mutating func clearSteamid() {self._steamid = nil} var nickname: String { get {return _nickname ?? String()} set {_nickname = newValue} } /// Returns true if `nickname` has been explicitly set. var hasNickname: Bool {return self._nickname != nil} /// Clears the value of `nickname`. Subsequent reads from it will return its default value. mutating func clearNickname() {self._nickname = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _steamid: UInt64? = nil fileprivate var _nickname: String? = nil } init() {} fileprivate var _removal: Bool? = nil fileprivate var _incremental: Bool? = nil } struct CMsgClientSetPlayerNickname { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var steamid: UInt64 { get {return _steamid ?? 0} set {_steamid = newValue} } /// Returns true if `steamid` has been explicitly set. var hasSteamid: Bool {return self._steamid != nil} /// Clears the value of `steamid`. Subsequent reads from it will return its default value. mutating func clearSteamid() {self._steamid = nil} var nickname: String { get {return _nickname ?? String()} set {_nickname = newValue} } /// Returns true if `nickname` has been explicitly set. var hasNickname: Bool {return self._nickname != nil} /// Clears the value of `nickname`. Subsequent reads from it will return its default value. mutating func clearNickname() {self._nickname = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _steamid: UInt64? = nil fileprivate var _nickname: String? = nil } struct CMsgClientSetPlayerNicknameResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var eresult: UInt32 { get {return _eresult ?? 0} set {_eresult = newValue} } /// Returns true if `eresult` has been explicitly set. var hasEresult: Bool {return self._eresult != nil} /// Clears the value of `eresult`. Subsequent reads from it will return its default value. mutating func clearEresult() {self._eresult = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _eresult: UInt32? = nil } struct CMsgClientRequestFriendData { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var personaStateRequested: UInt32 { get {return _personaStateRequested ?? 0} set {_personaStateRequested = newValue} } /// Returns true if `personaStateRequested` has been explicitly set. var hasPersonaStateRequested: Bool {return self._personaStateRequested != nil} /// Clears the value of `personaStateRequested`. Subsequent reads from it will return its default value. mutating func clearPersonaStateRequested() {self._personaStateRequested = nil} var friends: [UInt64] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _personaStateRequested: UInt32? = nil } struct CMsgClientChangeStatus { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var personaState: UInt32 { get {return _personaState ?? 0} set {_personaState = newValue} } /// Returns true if `personaState` has been explicitly set. var hasPersonaState: Bool {return self._personaState != nil} /// Clears the value of `personaState`. Subsequent reads from it will return its default value. mutating func clearPersonaState() {self._personaState = nil} var playerName: String { get {return _playerName ?? String()} set {_playerName = newValue} } /// Returns true if `playerName` has been explicitly set. var hasPlayerName: Bool {return self._playerName != nil} /// Clears the value of `playerName`. Subsequent reads from it will return its default value. mutating func clearPlayerName() {self._playerName = nil} var isAutoGeneratedName: Bool { get {return _isAutoGeneratedName ?? false} set {_isAutoGeneratedName = newValue} } /// Returns true if `isAutoGeneratedName` has been explicitly set. var hasIsAutoGeneratedName: Bool {return self._isAutoGeneratedName != nil} /// Clears the value of `isAutoGeneratedName`. Subsequent reads from it will return its default value. mutating func clearIsAutoGeneratedName() {self._isAutoGeneratedName = nil} var highPriority: Bool { get {return _highPriority ?? false} set {_highPriority = newValue} } /// Returns true if `highPriority` has been explicitly set. var hasHighPriority: Bool {return self._highPriority != nil} /// Clears the value of `highPriority`. Subsequent reads from it will return its default value. mutating func clearHighPriority() {self._highPriority = nil} var personaSetByUser: Bool { get {return _personaSetByUser ?? false} set {_personaSetByUser = newValue} } /// Returns true if `personaSetByUser` has been explicitly set. var hasPersonaSetByUser: Bool {return self._personaSetByUser != nil} /// Clears the value of `personaSetByUser`. Subsequent reads from it will return its default value. mutating func clearPersonaSetByUser() {self._personaSetByUser = nil} var personaStateFlags: UInt32 { get {return _personaStateFlags ?? 0} set {_personaStateFlags = newValue} } /// Returns true if `personaStateFlags` has been explicitly set. var hasPersonaStateFlags: Bool {return self._personaStateFlags != nil} /// Clears the value of `personaStateFlags`. Subsequent reads from it will return its default value. mutating func clearPersonaStateFlags() {self._personaStateFlags = nil} var needPersonaResponse: Bool { get {return _needPersonaResponse ?? false} set {_needPersonaResponse = newValue} } /// Returns true if `needPersonaResponse` has been explicitly set. var hasNeedPersonaResponse: Bool {return self._needPersonaResponse != nil} /// Clears the value of `needPersonaResponse`. Subsequent reads from it will return its default value. mutating func clearNeedPersonaResponse() {self._needPersonaResponse = nil} var isClientIdle: Bool { get {return _isClientIdle ?? false} set {_isClientIdle = newValue} } /// Returns true if `isClientIdle` has been explicitly set. var hasIsClientIdle: Bool {return self._isClientIdle != nil} /// Clears the value of `isClientIdle`. Subsequent reads from it will return its default value. mutating func clearIsClientIdle() {self._isClientIdle = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _personaState: UInt32? = nil fileprivate var _playerName: String? = nil fileprivate var _isAutoGeneratedName: Bool? = nil fileprivate var _highPriority: Bool? = nil fileprivate var _personaSetByUser: Bool? = nil fileprivate var _personaStateFlags: UInt32? = nil fileprivate var _needPersonaResponse: Bool? = nil fileprivate var _isClientIdle: Bool? = nil } struct CMsgPersonaChangeResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var result: UInt32 { get {return _result ?? 0} set {_result = newValue} } /// Returns true if `result` has been explicitly set. var hasResult: Bool {return self._result != nil} /// Clears the value of `result`. Subsequent reads from it will return its default value. mutating func clearResult() {self._result = nil} var playerName: String { get {return _playerName ?? String()} set {_playerName = newValue} } /// Returns true if `playerName` has been explicitly set. var hasPlayerName: Bool {return self._playerName != nil} /// Clears the value of `playerName`. Subsequent reads from it will return its default value. mutating func clearPlayerName() {self._playerName = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _result: UInt32? = nil fileprivate var _playerName: String? = nil } struct CMsgClientPersonaState { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var statusFlags: UInt32 { get {return _statusFlags ?? 0} set {_statusFlags = newValue} } /// Returns true if `statusFlags` has been explicitly set. var hasStatusFlags: Bool {return self._statusFlags != nil} /// Clears the value of `statusFlags`. Subsequent reads from it will return its default value. mutating func clearStatusFlags() {self._statusFlags = nil} var friends: [CMsgClientPersonaState.Friend] = [] var unknownFields = SwiftProtobuf.UnknownStorage() struct Friend { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var friendid: UInt64 { get {return _storage._friendid ?? 0} set {_uniqueStorage()._friendid = newValue} } /// Returns true if `friendid` has been explicitly set. var hasFriendid: Bool {return _storage._friendid != nil} /// Clears the value of `friendid`. Subsequent reads from it will return its default value. mutating func clearFriendid() {_uniqueStorage()._friendid = nil} var personaState: UInt32 { get {return _storage._personaState ?? 0} set {_uniqueStorage()._personaState = newValue} } /// Returns true if `personaState` has been explicitly set. var hasPersonaState: Bool {return _storage._personaState != nil} /// Clears the value of `personaState`. Subsequent reads from it will return its default value. mutating func clearPersonaState() {_uniqueStorage()._personaState = nil} var gamePlayedAppID: UInt32 { get {return _storage._gamePlayedAppID ?? 0} set {_uniqueStorage()._gamePlayedAppID = newValue} } /// Returns true if `gamePlayedAppID` has been explicitly set. var hasGamePlayedAppID: Bool {return _storage._gamePlayedAppID != nil} /// Clears the value of `gamePlayedAppID`. Subsequent reads from it will return its default value. mutating func clearGamePlayedAppID() {_uniqueStorage()._gamePlayedAppID = nil} var gameServerIp: UInt32 { get {return _storage._gameServerIp ?? 0} set {_uniqueStorage()._gameServerIp = newValue} } /// Returns true if `gameServerIp` has been explicitly set. var hasGameServerIp: Bool {return _storage._gameServerIp != nil} /// Clears the value of `gameServerIp`. Subsequent reads from it will return its default value. mutating func clearGameServerIp() {_uniqueStorage()._gameServerIp = nil} var gameServerPort: UInt32 { get {return _storage._gameServerPort ?? 0} set {_uniqueStorage()._gameServerPort = newValue} } /// Returns true if `gameServerPort` has been explicitly set. var hasGameServerPort: Bool {return _storage._gameServerPort != nil} /// Clears the value of `gameServerPort`. Subsequent reads from it will return its default value. mutating func clearGameServerPort() {_uniqueStorage()._gameServerPort = nil} var personaStateFlags: UInt32 { get {return _storage._personaStateFlags ?? 0} set {_uniqueStorage()._personaStateFlags = newValue} } /// Returns true if `personaStateFlags` has been explicitly set. var hasPersonaStateFlags: Bool {return _storage._personaStateFlags != nil} /// Clears the value of `personaStateFlags`. Subsequent reads from it will return its default value. mutating func clearPersonaStateFlags() {_uniqueStorage()._personaStateFlags = nil} var onlineSessionInstances: UInt32 { get {return _storage._onlineSessionInstances ?? 0} set {_uniqueStorage()._onlineSessionInstances = newValue} } /// Returns true if `onlineSessionInstances` has been explicitly set. var hasOnlineSessionInstances: Bool {return _storage._onlineSessionInstances != nil} /// Clears the value of `onlineSessionInstances`. Subsequent reads from it will return its default value. mutating func clearOnlineSessionInstances() {_uniqueStorage()._onlineSessionInstances = nil} var personaSetByUser: Bool { get {return _storage._personaSetByUser ?? false} set {_uniqueStorage()._personaSetByUser = newValue} } /// Returns true if `personaSetByUser` has been explicitly set. var hasPersonaSetByUser: Bool {return _storage._personaSetByUser != nil} /// Clears the value of `personaSetByUser`. Subsequent reads from it will return its default value. mutating func clearPersonaSetByUser() {_uniqueStorage()._personaSetByUser = nil} var playerName: String { get {return _storage._playerName ?? String()} set {_uniqueStorage()._playerName = newValue} } /// Returns true if `playerName` has been explicitly set. var hasPlayerName: Bool {return _storage._playerName != nil} /// Clears the value of `playerName`. Subsequent reads from it will return its default value. mutating func clearPlayerName() {_uniqueStorage()._playerName = nil} var queryPort: UInt32 { get {return _storage._queryPort ?? 0} set {_uniqueStorage()._queryPort = newValue} } /// Returns true if `queryPort` has been explicitly set. var hasQueryPort: Bool {return _storage._queryPort != nil} /// Clears the value of `queryPort`. Subsequent reads from it will return its default value. mutating func clearQueryPort() {_uniqueStorage()._queryPort = nil} var steamidSource: UInt64 { get {return _storage._steamidSource ?? 0} set {_uniqueStorage()._steamidSource = newValue} } /// Returns true if `steamidSource` has been explicitly set. var hasSteamidSource: Bool {return _storage._steamidSource != nil} /// Clears the value of `steamidSource`. Subsequent reads from it will return its default value. mutating func clearSteamidSource() {_uniqueStorage()._steamidSource = nil} var avatarHash: Data { get {return _storage._avatarHash ?? Data()} set {_uniqueStorage()._avatarHash = newValue} } /// Returns true if `avatarHash` has been explicitly set. var hasAvatarHash: Bool {return _storage._avatarHash != nil} /// Clears the value of `avatarHash`. Subsequent reads from it will return its default value. mutating func clearAvatarHash() {_uniqueStorage()._avatarHash = nil} var lastLogoff: UInt32 { get {return _storage._lastLogoff ?? 0} set {_uniqueStorage()._lastLogoff = newValue} } /// Returns true if `lastLogoff` has been explicitly set. var hasLastLogoff: Bool {return _storage._lastLogoff != nil} /// Clears the value of `lastLogoff`. Subsequent reads from it will return its default value. mutating func clearLastLogoff() {_uniqueStorage()._lastLogoff = nil} var lastLogon: UInt32 { get {return _storage._lastLogon ?? 0} set {_uniqueStorage()._lastLogon = newValue} } /// Returns true if `lastLogon` has been explicitly set. var hasLastLogon: Bool {return _storage._lastLogon != nil} /// Clears the value of `lastLogon`. Subsequent reads from it will return its default value. mutating func clearLastLogon() {_uniqueStorage()._lastLogon = nil} var lastSeenOnline: UInt32 { get {return _storage._lastSeenOnline ?? 0} set {_uniqueStorage()._lastSeenOnline = newValue} } /// Returns true if `lastSeenOnline` has been explicitly set. var hasLastSeenOnline: Bool {return _storage._lastSeenOnline != nil} /// Clears the value of `lastSeenOnline`. Subsequent reads from it will return its default value. mutating func clearLastSeenOnline() {_uniqueStorage()._lastSeenOnline = nil} var clanRank: UInt32 { get {return _storage._clanRank ?? 0} set {_uniqueStorage()._clanRank = newValue} } /// Returns true if `clanRank` has been explicitly set. var hasClanRank: Bool {return _storage._clanRank != nil} /// Clears the value of `clanRank`. Subsequent reads from it will return its default value. mutating func clearClanRank() {_uniqueStorage()._clanRank = nil} var gameName: String { get {return _storage._gameName ?? String()} set {_uniqueStorage()._gameName = newValue} } /// Returns true if `gameName` has been explicitly set. var hasGameName: Bool {return _storage._gameName != nil} /// Clears the value of `gameName`. Subsequent reads from it will return its default value. mutating func clearGameName() {_uniqueStorage()._gameName = nil} var gameid: UInt64 { get {return _storage._gameid ?? 0} set {_uniqueStorage()._gameid = newValue} } /// Returns true if `gameid` has been explicitly set. var hasGameid: Bool {return _storage._gameid != nil} /// Clears the value of `gameid`. Subsequent reads from it will return its default value. mutating func clearGameid() {_uniqueStorage()._gameid = nil} var gameDataBlob: Data { get {return _storage._gameDataBlob ?? Data()} set {_uniqueStorage()._gameDataBlob = newValue} } /// Returns true if `gameDataBlob` has been explicitly set. var hasGameDataBlob: Bool {return _storage._gameDataBlob != nil} /// Clears the value of `gameDataBlob`. Subsequent reads from it will return its default value. mutating func clearGameDataBlob() {_uniqueStorage()._gameDataBlob = nil} var clanData: CMsgClientPersonaState.Friend.ClanData { get {return _storage._clanData ?? CMsgClientPersonaState.Friend.ClanData()} set {_uniqueStorage()._clanData = newValue} } /// Returns true if `clanData` has been explicitly set. var hasClanData: Bool {return _storage._clanData != nil} /// Clears the value of `clanData`. Subsequent reads from it will return its default value. mutating func clearClanData() {_uniqueStorage()._clanData = nil} var clanTag: String { get {return _storage._clanTag ?? String()} set {_uniqueStorage()._clanTag = newValue} } /// Returns true if `clanTag` has been explicitly set. var hasClanTag: Bool {return _storage._clanTag != nil} /// Clears the value of `clanTag`. Subsequent reads from it will return its default value. mutating func clearClanTag() {_uniqueStorage()._clanTag = nil} var richPresence: [CMsgClientPersonaState.Friend.KV] { get {return _storage._richPresence} set {_uniqueStorage()._richPresence = newValue} } var broadcastID: UInt64 { get {return _storage._broadcastID ?? 0} set {_uniqueStorage()._broadcastID = newValue} } /// Returns true if `broadcastID` has been explicitly set. var hasBroadcastID: Bool {return _storage._broadcastID != nil} /// Clears the value of `broadcastID`. Subsequent reads from it will return its default value. mutating func clearBroadcastID() {_uniqueStorage()._broadcastID = nil} var gameLobbyID: UInt64 { get {return _storage._gameLobbyID ?? 0} set {_uniqueStorage()._gameLobbyID = newValue} } /// Returns true if `gameLobbyID` has been explicitly set. var hasGameLobbyID: Bool {return _storage._gameLobbyID != nil} /// Clears the value of `gameLobbyID`. Subsequent reads from it will return its default value. mutating func clearGameLobbyID() {_uniqueStorage()._gameLobbyID = nil} var watchingBroadcastAccountid: UInt32 { get {return _storage._watchingBroadcastAccountid ?? 0} set {_uniqueStorage()._watchingBroadcastAccountid = newValue} } /// Returns true if `watchingBroadcastAccountid` has been explicitly set. var hasWatchingBroadcastAccountid: Bool {return _storage._watchingBroadcastAccountid != nil} /// Clears the value of `watchingBroadcastAccountid`. Subsequent reads from it will return its default value. mutating func clearWatchingBroadcastAccountid() {_uniqueStorage()._watchingBroadcastAccountid = nil} var watchingBroadcastAppid: UInt32 { get {return _storage._watchingBroadcastAppid ?? 0} set {_uniqueStorage()._watchingBroadcastAppid = newValue} } /// Returns true if `watchingBroadcastAppid` has been explicitly set. var hasWatchingBroadcastAppid: Bool {return _storage._watchingBroadcastAppid != nil} /// Clears the value of `watchingBroadcastAppid`. Subsequent reads from it will return its default value. mutating func clearWatchingBroadcastAppid() {_uniqueStorage()._watchingBroadcastAppid = nil} var watchingBroadcastViewers: UInt32 { get {return _storage._watchingBroadcastViewers ?? 0} set {_uniqueStorage()._watchingBroadcastViewers = newValue} } /// Returns true if `watchingBroadcastViewers` has been explicitly set. var hasWatchingBroadcastViewers: Bool {return _storage._watchingBroadcastViewers != nil} /// Clears the value of `watchingBroadcastViewers`. Subsequent reads from it will return its default value. mutating func clearWatchingBroadcastViewers() {_uniqueStorage()._watchingBroadcastViewers = nil} var watchingBroadcastTitle: String { get {return _storage._watchingBroadcastTitle ?? String()} set {_uniqueStorage()._watchingBroadcastTitle = newValue} } /// Returns true if `watchingBroadcastTitle` has been explicitly set. var hasWatchingBroadcastTitle: Bool {return _storage._watchingBroadcastTitle != nil} /// Clears the value of `watchingBroadcastTitle`. Subsequent reads from it will return its default value. mutating func clearWatchingBroadcastTitle() {_uniqueStorage()._watchingBroadcastTitle = nil} var isCommunityBanned: Bool { get {return _storage._isCommunityBanned ?? false} set {_uniqueStorage()._isCommunityBanned = newValue} } /// Returns true if `isCommunityBanned` has been explicitly set. var hasIsCommunityBanned: Bool {return _storage._isCommunityBanned != nil} /// Clears the value of `isCommunityBanned`. Subsequent reads from it will return its default value. mutating func clearIsCommunityBanned() {_uniqueStorage()._isCommunityBanned = nil} var playerNamePendingReview: Bool { get {return _storage._playerNamePendingReview ?? false} set {_uniqueStorage()._playerNamePendingReview = newValue} } /// Returns true if `playerNamePendingReview` has been explicitly set. var hasPlayerNamePendingReview: Bool {return _storage._playerNamePendingReview != nil} /// Clears the value of `playerNamePendingReview`. Subsequent reads from it will return its default value. mutating func clearPlayerNamePendingReview() {_uniqueStorage()._playerNamePendingReview = nil} var avatarPendingReview: Bool { get {return _storage._avatarPendingReview ?? false} set {_uniqueStorage()._avatarPendingReview = newValue} } /// Returns true if `avatarPendingReview` has been explicitly set. var hasAvatarPendingReview: Bool {return _storage._avatarPendingReview != nil} /// Clears the value of `avatarPendingReview`. Subsequent reads from it will return its default value. mutating func clearAvatarPendingReview() {_uniqueStorage()._avatarPendingReview = nil} var unknownFields = SwiftProtobuf.UnknownStorage() struct ClanData { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var oggAppID: UInt32 { get {return _oggAppID ?? 0} set {_oggAppID = newValue} } /// Returns true if `oggAppID` has been explicitly set. var hasOggAppID: Bool {return self._oggAppID != nil} /// Clears the value of `oggAppID`. Subsequent reads from it will return its default value. mutating func clearOggAppID() {self._oggAppID = nil} var chatGroupID: UInt64 { get {return _chatGroupID ?? 0} set {_chatGroupID = newValue} } /// Returns true if `chatGroupID` has been explicitly set. var hasChatGroupID: Bool {return self._chatGroupID != nil} /// Clears the value of `chatGroupID`. Subsequent reads from it will return its default value. mutating func clearChatGroupID() {self._chatGroupID = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _oggAppID: UInt32? = nil fileprivate var _chatGroupID: UInt64? = nil } struct KV { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var key: String { get {return _key ?? String()} set {_key = newValue} } /// Returns true if `key` has been explicitly set. var hasKey: Bool {return self._key != nil} /// Clears the value of `key`. Subsequent reads from it will return its default value. mutating func clearKey() {self._key = nil} var value: String { get {return _value ?? String()} set {_value = newValue} } /// Returns true if `value` has been explicitly set. var hasValue: Bool {return self._value != nil} /// Clears the value of `value`. Subsequent reads from it will return its default value. mutating func clearValue() {self._value = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _key: String? = nil fileprivate var _value: String? = nil } init() {} fileprivate var _storage = _StorageClass.defaultInstance } init() {} fileprivate var _statusFlags: UInt32? = nil } struct CMsgClientFriendProfileInfo { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var steamidFriend: UInt64 { get {return _steamidFriend ?? 0} set {_steamidFriend = newValue} } /// Returns true if `steamidFriend` has been explicitly set. var hasSteamidFriend: Bool {return self._steamidFriend != nil} /// Clears the value of `steamidFriend`. Subsequent reads from it will return its default value. mutating func clearSteamidFriend() {self._steamidFriend = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _steamidFriend: UInt64? = nil } struct CMsgClientFriendProfileInfoResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var eresult: Int32 { get {return _eresult ?? 2} set {_eresult = newValue} } /// Returns true if `eresult` has been explicitly set. var hasEresult: Bool {return self._eresult != nil} /// Clears the value of `eresult`. Subsequent reads from it will return its default value. mutating func clearEresult() {self._eresult = nil} var steamidFriend: UInt64 { get {return _steamidFriend ?? 0} set {_steamidFriend = newValue} } /// Returns true if `steamidFriend` has been explicitly set. var hasSteamidFriend: Bool {return self._steamidFriend != nil} /// Clears the value of `steamidFriend`. Subsequent reads from it will return its default value. mutating func clearSteamidFriend() {self._steamidFriend = nil} var timeCreated: UInt32 { get {return _timeCreated ?? 0} set {_timeCreated = newValue} } /// Returns true if `timeCreated` has been explicitly set. var hasTimeCreated: Bool {return self._timeCreated != nil} /// Clears the value of `timeCreated`. Subsequent reads from it will return its default value. mutating func clearTimeCreated() {self._timeCreated = nil} var realName: String { get {return _realName ?? String()} set {_realName = newValue} } /// Returns true if `realName` has been explicitly set. var hasRealName: Bool {return self._realName != nil} /// Clears the value of `realName`. Subsequent reads from it will return its default value. mutating func clearRealName() {self._realName = nil} var cityName: String { get {return _cityName ?? String()} set {_cityName = newValue} } /// Returns true if `cityName` has been explicitly set. var hasCityName: Bool {return self._cityName != nil} /// Clears the value of `cityName`. Subsequent reads from it will return its default value. mutating func clearCityName() {self._cityName = nil} var stateName: String { get {return _stateName ?? String()} set {_stateName = newValue} } /// Returns true if `stateName` has been explicitly set. var hasStateName: Bool {return self._stateName != nil} /// Clears the value of `stateName`. Subsequent reads from it will return its default value. mutating func clearStateName() {self._stateName = nil} var countryName: String { get {return _countryName ?? String()} set {_countryName = newValue} } /// Returns true if `countryName` has been explicitly set. var hasCountryName: Bool {return self._countryName != nil} /// Clears the value of `countryName`. Subsequent reads from it will return its default value. mutating func clearCountryName() {self._countryName = nil} var headline: String { get {return _headline ?? String()} set {_headline = newValue} } /// Returns true if `headline` has been explicitly set. var hasHeadline: Bool {return self._headline != nil} /// Clears the value of `headline`. Subsequent reads from it will return its default value. mutating func clearHeadline() {self._headline = nil} var summary: String { get {return _summary ?? String()} set {_summary = newValue} } /// Returns true if `summary` has been explicitly set. var hasSummary: Bool {return self._summary != nil} /// Clears the value of `summary`. Subsequent reads from it will return its default value. mutating func clearSummary() {self._summary = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _eresult: Int32? = nil fileprivate var _steamidFriend: UInt64? = nil fileprivate var _timeCreated: UInt32? = nil fileprivate var _realName: String? = nil fileprivate var _cityName: String? = nil fileprivate var _stateName: String? = nil fileprivate var _countryName: String? = nil fileprivate var _headline: String? = nil fileprivate var _summary: String? = nil } struct CMsgClientCreateFriendsGroup { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var steamid: UInt64 { get {return _steamid ?? 0} set {_steamid = newValue} } /// Returns true if `steamid` has been explicitly set. var hasSteamid: Bool {return self._steamid != nil} /// Clears the value of `steamid`. Subsequent reads from it will return its default value. mutating func clearSteamid() {self._steamid = nil} var groupname: String { get {return _groupname ?? String()} set {_groupname = newValue} } /// Returns true if `groupname` has been explicitly set. var hasGroupname: Bool {return self._groupname != nil} /// Clears the value of `groupname`. Subsequent reads from it will return its default value. mutating func clearGroupname() {self._groupname = nil} var steamidFriends: [UInt64] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _steamid: UInt64? = nil fileprivate var _groupname: String? = nil } struct CMsgClientCreateFriendsGroupResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var eresult: UInt32 { get {return _eresult ?? 0} set {_eresult = newValue} } /// Returns true if `eresult` has been explicitly set. var hasEresult: Bool {return self._eresult != nil} /// Clears the value of `eresult`. Subsequent reads from it will return its default value. mutating func clearEresult() {self._eresult = nil} var groupid: Int32 { get {return _groupid ?? 0} set {_groupid = newValue} } /// Returns true if `groupid` has been explicitly set. var hasGroupid: Bool {return self._groupid != nil} /// Clears the value of `groupid`. Subsequent reads from it will return its default value. mutating func clearGroupid() {self._groupid = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _eresult: UInt32? = nil fileprivate var _groupid: Int32? = nil } struct CMsgClientDeleteFriendsGroup { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var steamid: UInt64 { get {return _steamid ?? 0} set {_steamid = newValue} } /// Returns true if `steamid` has been explicitly set. var hasSteamid: Bool {return self._steamid != nil} /// Clears the value of `steamid`. Subsequent reads from it will return its default value. mutating func clearSteamid() {self._steamid = nil} var groupid: Int32 { get {return _groupid ?? 0} set {_groupid = newValue} } /// Returns true if `groupid` has been explicitly set. var hasGroupid: Bool {return self._groupid != nil} /// Clears the value of `groupid`. Subsequent reads from it will return its default value. mutating func clearGroupid() {self._groupid = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _steamid: UInt64? = nil fileprivate var _groupid: Int32? = nil } struct CMsgClientDeleteFriendsGroupResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var eresult: UInt32 { get {return _eresult ?? 0} set {_eresult = newValue} } /// Returns true if `eresult` has been explicitly set. var hasEresult: Bool {return self._eresult != nil} /// Clears the value of `eresult`. Subsequent reads from it will return its default value. mutating func clearEresult() {self._eresult = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _eresult: UInt32? = nil } struct CMsgClientManageFriendsGroup { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var groupid: Int32 { get {return _groupid ?? 0} set {_groupid = newValue} } /// Returns true if `groupid` has been explicitly set. var hasGroupid: Bool {return self._groupid != nil} /// Clears the value of `groupid`. Subsequent reads from it will return its default value. mutating func clearGroupid() {self._groupid = nil} var groupname: String { get {return _groupname ?? String()} set {_groupname = newValue} } /// Returns true if `groupname` has been explicitly set. var hasGroupname: Bool {return self._groupname != nil} /// Clears the value of `groupname`. Subsequent reads from it will return its default value. mutating func clearGroupname() {self._groupname = nil} var steamidFriendsAdded: [UInt64] = [] var steamidFriendsRemoved: [UInt64] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _groupid: Int32? = nil fileprivate var _groupname: String? = nil } struct CMsgClientManageFriendsGroupResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var eresult: UInt32 { get {return _eresult ?? 0} set {_eresult = newValue} } /// Returns true if `eresult` has been explicitly set. var hasEresult: Bool {return self._eresult != nil} /// Clears the value of `eresult`. Subsequent reads from it will return its default value. mutating func clearEresult() {self._eresult = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _eresult: UInt32? = nil } struct CMsgClientAddFriendToGroup { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var groupid: Int32 { get {return _groupid ?? 0} set {_groupid = newValue} } /// Returns true if `groupid` has been explicitly set. var hasGroupid: Bool {return self._groupid != nil} /// Clears the value of `groupid`. Subsequent reads from it will return its default value. mutating func clearGroupid() {self._groupid = nil} var steamiduser: UInt64 { get {return _steamiduser ?? 0} set {_steamiduser = newValue} } /// Returns true if `steamiduser` has been explicitly set. var hasSteamiduser: Bool {return self._steamiduser != nil} /// Clears the value of `steamiduser`. Subsequent reads from it will return its default value. mutating func clearSteamiduser() {self._steamiduser = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _groupid: Int32? = nil fileprivate var _steamiduser: UInt64? = nil } struct CMsgClientAddFriendToGroupResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var eresult: UInt32 { get {return _eresult ?? 0} set {_eresult = newValue} } /// Returns true if `eresult` has been explicitly set. var hasEresult: Bool {return self._eresult != nil} /// Clears the value of `eresult`. Subsequent reads from it will return its default value. mutating func clearEresult() {self._eresult = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _eresult: UInt32? = nil } struct CMsgClientRemoveFriendFromGroup { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var groupid: Int32 { get {return _groupid ?? 0} set {_groupid = newValue} } /// Returns true if `groupid` has been explicitly set. var hasGroupid: Bool {return self._groupid != nil} /// Clears the value of `groupid`. Subsequent reads from it will return its default value. mutating func clearGroupid() {self._groupid = nil} var steamiduser: UInt64 { get {return _steamiduser ?? 0} set {_steamiduser = newValue} } /// Returns true if `steamiduser` has been explicitly set. var hasSteamiduser: Bool {return self._steamiduser != nil} /// Clears the value of `steamiduser`. Subsequent reads from it will return its default value. mutating func clearSteamiduser() {self._steamiduser = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _groupid: Int32? = nil fileprivate var _steamiduser: UInt64? = nil } struct CMsgClientRemoveFriendFromGroupResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var eresult: UInt32 { get {return _eresult ?? 0} set {_eresult = newValue} } /// Returns true if `eresult` has been explicitly set. var hasEresult: Bool {return self._eresult != nil} /// Clears the value of `eresult`. Subsequent reads from it will return its default value. mutating func clearEresult() {self._eresult = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _eresult: UInt32? = nil } struct CMsgClientGetEmoticonList { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct CMsgClientEmoticonList { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var emoticons: [CMsgClientEmoticonList.Emoticon] = [] var stickers: [CMsgClientEmoticonList.Sticker] = [] var effects: [CMsgClientEmoticonList.Effect] = [] var unknownFields = SwiftProtobuf.UnknownStorage() struct Emoticon { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var name: String { get {return _name ?? String()} set {_name = newValue} } /// Returns true if `name` has been explicitly set. var hasName: Bool {return self._name != nil} /// Clears the value of `name`. Subsequent reads from it will return its default value. mutating func clearName() {self._name = nil} var count: Int32 { get {return _count ?? 0} set {_count = newValue} } /// Returns true if `count` has been explicitly set. var hasCount: Bool {return self._count != nil} /// Clears the value of `count`. Subsequent reads from it will return its default value. mutating func clearCount() {self._count = nil} var timeLastUsed: UInt32 { get {return _timeLastUsed ?? 0} set {_timeLastUsed = newValue} } /// Returns true if `timeLastUsed` has been explicitly set. var hasTimeLastUsed: Bool {return self._timeLastUsed != nil} /// Clears the value of `timeLastUsed`. Subsequent reads from it will return its default value. mutating func clearTimeLastUsed() {self._timeLastUsed = nil} var useCount: UInt32 { get {return _useCount ?? 0} set {_useCount = newValue} } /// Returns true if `useCount` has been explicitly set. var hasUseCount: Bool {return self._useCount != nil} /// Clears the value of `useCount`. Subsequent reads from it will return its default value. mutating func clearUseCount() {self._useCount = nil} var timeReceived: UInt32 { get {return _timeReceived ?? 0} set {_timeReceived = newValue} } /// Returns true if `timeReceived` has been explicitly set. var hasTimeReceived: Bool {return self._timeReceived != nil} /// Clears the value of `timeReceived`. Subsequent reads from it will return its default value. mutating func clearTimeReceived() {self._timeReceived = nil} var appid: UInt32 { get {return _appid ?? 0} set {_appid = newValue} } /// Returns true if `appid` has been explicitly set. var hasAppid: Bool {return self._appid != nil} /// Clears the value of `appid`. Subsequent reads from it will return its default value. mutating func clearAppid() {self._appid = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _name: String? = nil fileprivate var _count: Int32? = nil fileprivate var _timeLastUsed: UInt32? = nil fileprivate var _useCount: UInt32? = nil fileprivate var _timeReceived: UInt32? = nil fileprivate var _appid: UInt32? = nil } struct Sticker { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var name: String { get {return _name ?? String()} set {_name = newValue} } /// Returns true if `name` has been explicitly set. var hasName: Bool {return self._name != nil} /// Clears the value of `name`. Subsequent reads from it will return its default value. mutating func clearName() {self._name = nil} var count: Int32 { get {return _count ?? 0} set {_count = newValue} } /// Returns true if `count` has been explicitly set. var hasCount: Bool {return self._count != nil} /// Clears the value of `count`. Subsequent reads from it will return its default value. mutating func clearCount() {self._count = nil} var timeReceived: UInt32 { get {return _timeReceived ?? 0} set {_timeReceived = newValue} } /// Returns true if `timeReceived` has been explicitly set. var hasTimeReceived: Bool {return self._timeReceived != nil} /// Clears the value of `timeReceived`. Subsequent reads from it will return its default value. mutating func clearTimeReceived() {self._timeReceived = nil} var appid: UInt32 { get {return _appid ?? 0} set {_appid = newValue} } /// Returns true if `appid` has been explicitly set. var hasAppid: Bool {return self._appid != nil} /// Clears the value of `appid`. Subsequent reads from it will return its default value. mutating func clearAppid() {self._appid = nil} var timeLastUsed: UInt32 { get {return _timeLastUsed ?? 0} set {_timeLastUsed = newValue} } /// Returns true if `timeLastUsed` has been explicitly set. var hasTimeLastUsed: Bool {return self._timeLastUsed != nil} /// Clears the value of `timeLastUsed`. Subsequent reads from it will return its default value. mutating func clearTimeLastUsed() {self._timeLastUsed = nil} var useCount: UInt32 { get {return _useCount ?? 0} set {_useCount = newValue} } /// Returns true if `useCount` has been explicitly set. var hasUseCount: Bool {return self._useCount != nil} /// Clears the value of `useCount`. Subsequent reads from it will return its default value. mutating func clearUseCount() {self._useCount = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _name: String? = nil fileprivate var _count: Int32? = nil fileprivate var _timeReceived: UInt32? = nil fileprivate var _appid: UInt32? = nil fileprivate var _timeLastUsed: UInt32? = nil fileprivate var _useCount: UInt32? = nil } struct Effect { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var name: String { get {return _name ?? String()} set {_name = newValue} } /// Returns true if `name` has been explicitly set. var hasName: Bool {return self._name != nil} /// Clears the value of `name`. Subsequent reads from it will return its default value. mutating func clearName() {self._name = nil} var count: Int32 { get {return _count ?? 0} set {_count = newValue} } /// Returns true if `count` has been explicitly set. var hasCount: Bool {return self._count != nil} /// Clears the value of `count`. Subsequent reads from it will return its default value. mutating func clearCount() {self._count = nil} var timeReceived: UInt32 { get {return _timeReceived ?? 0} set {_timeReceived = newValue} } /// Returns true if `timeReceived` has been explicitly set. var hasTimeReceived: Bool {return self._timeReceived != nil} /// Clears the value of `timeReceived`. Subsequent reads from it will return its default value. mutating func clearTimeReceived() {self._timeReceived = nil} var infiniteUse: Bool { get {return _infiniteUse ?? false} set {_infiniteUse = newValue} } /// Returns true if `infiniteUse` has been explicitly set. var hasInfiniteUse: Bool {return self._infiniteUse != nil} /// Clears the value of `infiniteUse`. Subsequent reads from it will return its default value. mutating func clearInfiniteUse() {self._infiniteUse = nil} var appid: UInt32 { get {return _appid ?? 0} set {_appid = newValue} } /// Returns true if `appid` has been explicitly set. var hasAppid: Bool {return self._appid != nil} /// Clears the value of `appid`. Subsequent reads from it will return its default value. mutating func clearAppid() {self._appid = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _name: String? = nil fileprivate var _count: Int32? = nil fileprivate var _timeReceived: UInt32? = nil fileprivate var _infiniteUse: Bool? = nil fileprivate var _appid: UInt32? = nil } init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. extension CMsgClientFriendMsg: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientFriendMsg" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "steamid"), 2: .standard(proto: "chat_entry_type"), 3: .same(proto: "message"), 4: .standard(proto: "rtime32_server_timestamp"), 5: .standard(proto: "echo_to_sender"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._steamid) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self._chatEntryType) }() case 3: try { try decoder.decodeSingularBytesField(value: &self._message) }() case 4: try { try decoder.decodeSingularFixed32Field(value: &self._rtime32ServerTimestamp) }() case 5: try { try decoder.decodeSingularBoolField(value: &self._echoToSender) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._steamid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._chatEntryType { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } }() try { if let v = self._message { try visitor.visitSingularBytesField(value: v, fieldNumber: 3) } }() try { if let v = self._rtime32ServerTimestamp { try visitor.visitSingularFixed32Field(value: v, fieldNumber: 4) } }() try { if let v = self._echoToSender { try visitor.visitSingularBoolField(value: v, fieldNumber: 5) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendMsg, rhs: CMsgClientFriendMsg) -> Bool { if lhs._steamid != rhs._steamid {return false} if lhs._chatEntryType != rhs._chatEntryType {return false} if lhs._message != rhs._message {return false} if lhs._rtime32ServerTimestamp != rhs._rtime32ServerTimestamp {return false} if lhs._echoToSender != rhs._echoToSender {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientFriendMsgIncoming: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientFriendMsgIncoming" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "steamid_from"), 2: .standard(proto: "chat_entry_type"), 3: .standard(proto: "from_limited_account"), 4: .same(proto: "message"), 5: .standard(proto: "rtime32_server_timestamp"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._steamidFrom) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self._chatEntryType) }() case 3: try { try decoder.decodeSingularBoolField(value: &self._fromLimitedAccount) }() case 4: try { try decoder.decodeSingularBytesField(value: &self._message) }() case 5: try { try decoder.decodeSingularFixed32Field(value: &self._rtime32ServerTimestamp) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._steamidFrom { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._chatEntryType { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } }() try { if let v = self._fromLimitedAccount { try visitor.visitSingularBoolField(value: v, fieldNumber: 3) } }() try { if let v = self._message { try visitor.visitSingularBytesField(value: v, fieldNumber: 4) } }() try { if let v = self._rtime32ServerTimestamp { try visitor.visitSingularFixed32Field(value: v, fieldNumber: 5) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendMsgIncoming, rhs: CMsgClientFriendMsgIncoming) -> Bool { if lhs._steamidFrom != rhs._steamidFrom {return false} if lhs._chatEntryType != rhs._chatEntryType {return false} if lhs._fromLimitedAccount != rhs._fromLimitedAccount {return false} if lhs._message != rhs._message {return false} if lhs._rtime32ServerTimestamp != rhs._rtime32ServerTimestamp {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientAddFriend: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientAddFriend" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "steamid_to_add"), 2: .standard(proto: "accountname_or_email_to_add"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._steamidToAdd) }() case 2: try { try decoder.decodeSingularStringField(value: &self._accountnameOrEmailToAdd) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._steamidToAdd { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._accountnameOrEmailToAdd { try visitor.visitSingularStringField(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientAddFriend, rhs: CMsgClientAddFriend) -> Bool { if lhs._steamidToAdd != rhs._steamidToAdd {return false} if lhs._accountnameOrEmailToAdd != rhs._accountnameOrEmailToAdd {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientAddFriendResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientAddFriendResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "eresult"), 2: .standard(proto: "steam_id_added"), 3: .standard(proto: "persona_name_added"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt32Field(value: &self._eresult) }() case 2: try { try decoder.decodeSingularFixed64Field(value: &self._steamIDAdded) }() case 3: try { try decoder.decodeSingularStringField(value: &self._personaNameAdded) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._eresult { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._steamIDAdded { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 2) } }() try { if let v = self._personaNameAdded { try visitor.visitSingularStringField(value: v, fieldNumber: 3) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientAddFriendResponse, rhs: CMsgClientAddFriendResponse) -> Bool { if lhs._eresult != rhs._eresult {return false} if lhs._steamIDAdded != rhs._steamIDAdded {return false} if lhs._personaNameAdded != rhs._personaNameAdded {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientRemoveFriend: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientRemoveFriend" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "friendid"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._friendid) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._friendid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientRemoveFriend, rhs: CMsgClientRemoveFriend) -> Bool { if lhs._friendid != rhs._friendid {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientHideFriend: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientHideFriend" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "friendid"), 2: .same(proto: "hide"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._friendid) }() case 2: try { try decoder.decodeSingularBoolField(value: &self._hide) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._friendid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._hide { try visitor.visitSingularBoolField(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientHideFriend, rhs: CMsgClientHideFriend) -> Bool { if lhs._friendid != rhs._friendid {return false} if lhs._hide != rhs._hide {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientFriendsList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientFriendsList" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "bincremental"), 2: .same(proto: "friends"), 3: .standard(proto: "max_friend_count"), 4: .standard(proto: "active_friend_count"), 5: .standard(proto: "friends_limit_hit"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBoolField(value: &self._bincremental) }() case 2: try { try decoder.decodeRepeatedMessageField(value: &self.friends) }() case 3: try { try decoder.decodeSingularUInt32Field(value: &self._maxFriendCount) }() case 4: try { try decoder.decodeSingularUInt32Field(value: &self._activeFriendCount) }() case 5: try { try decoder.decodeSingularBoolField(value: &self._friendsLimitHit) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._bincremental { try visitor.visitSingularBoolField(value: v, fieldNumber: 1) } }() if !self.friends.isEmpty { try visitor.visitRepeatedMessageField(value: self.friends, fieldNumber: 2) } try { if let v = self._maxFriendCount { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3) } }() try { if let v = self._activeFriendCount { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4) } }() try { if let v = self._friendsLimitHit { try visitor.visitSingularBoolField(value: v, fieldNumber: 5) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendsList, rhs: CMsgClientFriendsList) -> Bool { if lhs._bincremental != rhs._bincremental {return false} if lhs.friends != rhs.friends {return false} if lhs._maxFriendCount != rhs._maxFriendCount {return false} if lhs._activeFriendCount != rhs._activeFriendCount {return false} if lhs._friendsLimitHit != rhs._friendsLimitHit {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientFriendsList.Friend: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientFriendsList.protoMessageName + ".Friend" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "ulfriendid"), 2: .same(proto: "efriendrelationship"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._ulfriendid) }() case 2: try { try decoder.decodeSingularUInt32Field(value: &self._efriendrelationship) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._ulfriendid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._efriendrelationship { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendsList.Friend, rhs: CMsgClientFriendsList.Friend) -> Bool { if lhs._ulfriendid != rhs._ulfriendid {return false} if lhs._efriendrelationship != rhs._efriendrelationship {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientFriendsGroupsList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientFriendsGroupsList" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "bremoval"), 2: .same(proto: "bincremental"), 3: .same(proto: "friendGroups"), 4: .same(proto: "memberships"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBoolField(value: &self._bremoval) }() case 2: try { try decoder.decodeSingularBoolField(value: &self._bincremental) }() case 3: try { try decoder.decodeRepeatedMessageField(value: &self.friendGroups) }() case 4: try { try decoder.decodeRepeatedMessageField(value: &self.memberships) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._bremoval { try visitor.visitSingularBoolField(value: v, fieldNumber: 1) } }() try { if let v = self._bincremental { try visitor.visitSingularBoolField(value: v, fieldNumber: 2) } }() if !self.friendGroups.isEmpty { try visitor.visitRepeatedMessageField(value: self.friendGroups, fieldNumber: 3) } if !self.memberships.isEmpty { try visitor.visitRepeatedMessageField(value: self.memberships, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendsGroupsList, rhs: CMsgClientFriendsGroupsList) -> Bool { if lhs._bremoval != rhs._bremoval {return false} if lhs._bincremental != rhs._bincremental {return false} if lhs.friendGroups != rhs.friendGroups {return false} if lhs.memberships != rhs.memberships {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientFriendsGroupsList.FriendGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientFriendsGroupsList.protoMessageName + ".FriendGroup" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "nGroupID"), 2: .same(proto: "strGroupName"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt32Field(value: &self._nGroupID) }() case 2: try { try decoder.decodeSingularStringField(value: &self._strGroupName) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._nGroupID { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._strGroupName { try visitor.visitSingularStringField(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendsGroupsList.FriendGroup, rhs: CMsgClientFriendsGroupsList.FriendGroup) -> Bool { if lhs._nGroupID != rhs._nGroupID {return false} if lhs._strGroupName != rhs._strGroupName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientFriendsGroupsList.FriendGroupsMembership: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientFriendsGroupsList.protoMessageName + ".FriendGroupsMembership" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "ulSteamID"), 2: .same(proto: "nGroupID"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._ulSteamID) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self._nGroupID) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._ulSteamID { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._nGroupID { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendsGroupsList.FriendGroupsMembership, rhs: CMsgClientFriendsGroupsList.FriendGroupsMembership) -> Bool { if lhs._ulSteamID != rhs._ulSteamID {return false} if lhs._nGroupID != rhs._nGroupID {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientPlayerNicknameList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientPlayerNicknameList" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "removal"), 2: .same(proto: "incremental"), 3: .same(proto: "nicknames"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBoolField(value: &self._removal) }() case 2: try { try decoder.decodeSingularBoolField(value: &self._incremental) }() case 3: try { try decoder.decodeRepeatedMessageField(value: &self.nicknames) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._removal { try visitor.visitSingularBoolField(value: v, fieldNumber: 1) } }() try { if let v = self._incremental { try visitor.visitSingularBoolField(value: v, fieldNumber: 2) } }() if !self.nicknames.isEmpty { try visitor.visitRepeatedMessageField(value: self.nicknames, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientPlayerNicknameList, rhs: CMsgClientPlayerNicknameList) -> Bool { if lhs._removal != rhs._removal {return false} if lhs._incremental != rhs._incremental {return false} if lhs.nicknames != rhs.nicknames {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientPlayerNicknameList.PlayerNickname: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientPlayerNicknameList.protoMessageName + ".PlayerNickname" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "steamid"), 3: .same(proto: "nickname"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._steamid) }() case 3: try { try decoder.decodeSingularStringField(value: &self._nickname) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._steamid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._nickname { try visitor.visitSingularStringField(value: v, fieldNumber: 3) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientPlayerNicknameList.PlayerNickname, rhs: CMsgClientPlayerNicknameList.PlayerNickname) -> Bool { if lhs._steamid != rhs._steamid {return false} if lhs._nickname != rhs._nickname {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientSetPlayerNickname: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientSetPlayerNickname" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "steamid"), 2: .same(proto: "nickname"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._steamid) }() case 2: try { try decoder.decodeSingularStringField(value: &self._nickname) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._steamid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._nickname { try visitor.visitSingularStringField(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientSetPlayerNickname, rhs: CMsgClientSetPlayerNickname) -> Bool { if lhs._steamid != rhs._steamid {return false} if lhs._nickname != rhs._nickname {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientSetPlayerNicknameResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientSetPlayerNicknameResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "eresult"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._eresult) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._eresult { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientSetPlayerNicknameResponse, rhs: CMsgClientSetPlayerNicknameResponse) -> Bool { if lhs._eresult != rhs._eresult {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientRequestFriendData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientRequestFriendData" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "persona_state_requested"), 2: .same(proto: "friends"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._personaStateRequested) }() case 2: try { try decoder.decodeRepeatedFixed64Field(value: &self.friends) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._personaStateRequested { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() if !self.friends.isEmpty { try visitor.visitRepeatedFixed64Field(value: self.friends, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientRequestFriendData, rhs: CMsgClientRequestFriendData) -> Bool { if lhs._personaStateRequested != rhs._personaStateRequested {return false} if lhs.friends != rhs.friends {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientChangeStatus: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientChangeStatus" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "persona_state"), 2: .standard(proto: "player_name"), 3: .standard(proto: "is_auto_generated_name"), 4: .standard(proto: "high_priority"), 5: .standard(proto: "persona_set_by_user"), 6: .standard(proto: "persona_state_flags"), 7: .standard(proto: "need_persona_response"), 8: .standard(proto: "is_client_idle"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._personaState) }() case 2: try { try decoder.decodeSingularStringField(value: &self._playerName) }() case 3: try { try decoder.decodeSingularBoolField(value: &self._isAutoGeneratedName) }() case 4: try { try decoder.decodeSingularBoolField(value: &self._highPriority) }() case 5: try { try decoder.decodeSingularBoolField(value: &self._personaSetByUser) }() case 6: try { try decoder.decodeSingularUInt32Field(value: &self._personaStateFlags) }() case 7: try { try decoder.decodeSingularBoolField(value: &self._needPersonaResponse) }() case 8: try { try decoder.decodeSingularBoolField(value: &self._isClientIdle) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._personaState { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._playerName { try visitor.visitSingularStringField(value: v, fieldNumber: 2) } }() try { if let v = self._isAutoGeneratedName { try visitor.visitSingularBoolField(value: v, fieldNumber: 3) } }() try { if let v = self._highPriority { try visitor.visitSingularBoolField(value: v, fieldNumber: 4) } }() try { if let v = self._personaSetByUser { try visitor.visitSingularBoolField(value: v, fieldNumber: 5) } }() try { if let v = self._personaStateFlags { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 6) } }() try { if let v = self._needPersonaResponse { try visitor.visitSingularBoolField(value: v, fieldNumber: 7) } }() try { if let v = self._isClientIdle { try visitor.visitSingularBoolField(value: v, fieldNumber: 8) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientChangeStatus, rhs: CMsgClientChangeStatus) -> Bool { if lhs._personaState != rhs._personaState {return false} if lhs._playerName != rhs._playerName {return false} if lhs._isAutoGeneratedName != rhs._isAutoGeneratedName {return false} if lhs._highPriority != rhs._highPriority {return false} if lhs._personaSetByUser != rhs._personaSetByUser {return false} if lhs._personaStateFlags != rhs._personaStateFlags {return false} if lhs._needPersonaResponse != rhs._needPersonaResponse {return false} if lhs._isClientIdle != rhs._isClientIdle {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgPersonaChangeResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgPersonaChangeResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "result"), 2: .standard(proto: "player_name"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._result) }() case 2: try { try decoder.decodeSingularStringField(value: &self._playerName) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._result { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._playerName { try visitor.visitSingularStringField(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgPersonaChangeResponse, rhs: CMsgPersonaChangeResponse) -> Bool { if lhs._result != rhs._result {return false} if lhs._playerName != rhs._playerName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientPersonaState: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientPersonaState" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "status_flags"), 2: .same(proto: "friends"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._statusFlags) }() case 2: try { try decoder.decodeRepeatedMessageField(value: &self.friends) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._statusFlags { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() if !self.friends.isEmpty { try visitor.visitRepeatedMessageField(value: self.friends, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientPersonaState, rhs: CMsgClientPersonaState) -> Bool { if lhs._statusFlags != rhs._statusFlags {return false} if lhs.friends != rhs.friends {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientPersonaState.Friend: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientPersonaState.protoMessageName + ".Friend" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "friendid"), 2: .standard(proto: "persona_state"), 3: .standard(proto: "game_played_app_id"), 4: .standard(proto: "game_server_ip"), 5: .standard(proto: "game_server_port"), 6: .standard(proto: "persona_state_flags"), 7: .standard(proto: "online_session_instances"), 10: .standard(proto: "persona_set_by_user"), 15: .standard(proto: "player_name"), 20: .standard(proto: "query_port"), 25: .standard(proto: "steamid_source"), 31: .standard(proto: "avatar_hash"), 45: .standard(proto: "last_logoff"), 46: .standard(proto: "last_logon"), 47: .standard(proto: "last_seen_online"), 50: .standard(proto: "clan_rank"), 55: .standard(proto: "game_name"), 56: .same(proto: "gameid"), 60: .standard(proto: "game_data_blob"), 64: .standard(proto: "clan_data"), 65: .standard(proto: "clan_tag"), 71: .standard(proto: "rich_presence"), 72: .standard(proto: "broadcast_id"), 73: .standard(proto: "game_lobby_id"), 74: .standard(proto: "watching_broadcast_accountid"), 75: .standard(proto: "watching_broadcast_appid"), 76: .standard(proto: "watching_broadcast_viewers"), 77: .standard(proto: "watching_broadcast_title"), 78: .standard(proto: "is_community_banned"), 79: .standard(proto: "player_name_pending_review"), 80: .standard(proto: "avatar_pending_review"), ] fileprivate class _StorageClass { var _friendid: UInt64? = nil var _personaState: UInt32? = nil var _gamePlayedAppID: UInt32? = nil var _gameServerIp: UInt32? = nil var _gameServerPort: UInt32? = nil var _personaStateFlags: UInt32? = nil var _onlineSessionInstances: UInt32? = nil var _personaSetByUser: Bool? = nil var _playerName: String? = nil var _queryPort: UInt32? = nil var _steamidSource: UInt64? = nil var _avatarHash: Data? = nil var _lastLogoff: UInt32? = nil var _lastLogon: UInt32? = nil var _lastSeenOnline: UInt32? = nil var _clanRank: UInt32? = nil var _gameName: String? = nil var _gameid: UInt64? = nil var _gameDataBlob: Data? = nil var _clanData: CMsgClientPersonaState.Friend.ClanData? = nil var _clanTag: String? = nil var _richPresence: [CMsgClientPersonaState.Friend.KV] = [] var _broadcastID: UInt64? = nil var _gameLobbyID: UInt64? = nil var _watchingBroadcastAccountid: UInt32? = nil var _watchingBroadcastAppid: UInt32? = nil var _watchingBroadcastViewers: UInt32? = nil var _watchingBroadcastTitle: String? = nil var _isCommunityBanned: Bool? = nil var _playerNamePendingReview: Bool? = nil var _avatarPendingReview: Bool? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _friendid = source._friendid _personaState = source._personaState _gamePlayedAppID = source._gamePlayedAppID _gameServerIp = source._gameServerIp _gameServerPort = source._gameServerPort _personaStateFlags = source._personaStateFlags _onlineSessionInstances = source._onlineSessionInstances _personaSetByUser = source._personaSetByUser _playerName = source._playerName _queryPort = source._queryPort _steamidSource = source._steamidSource _avatarHash = source._avatarHash _lastLogoff = source._lastLogoff _lastLogon = source._lastLogon _lastSeenOnline = source._lastSeenOnline _clanRank = source._clanRank _gameName = source._gameName _gameid = source._gameid _gameDataBlob = source._gameDataBlob _clanData = source._clanData _clanTag = source._clanTag _richPresence = source._richPresence _broadcastID = source._broadcastID _gameLobbyID = source._gameLobbyID _watchingBroadcastAccountid = source._watchingBroadcastAccountid _watchingBroadcastAppid = source._watchingBroadcastAppid _watchingBroadcastViewers = source._watchingBroadcastViewers _watchingBroadcastTitle = source._watchingBroadcastTitle _isCommunityBanned = source._isCommunityBanned _playerNamePendingReview = source._playerNamePendingReview _avatarPendingReview = source._avatarPendingReview } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &_storage._friendid) }() case 2: try { try decoder.decodeSingularUInt32Field(value: &_storage._personaState) }() case 3: try { try decoder.decodeSingularUInt32Field(value: &_storage._gamePlayedAppID) }() case 4: try { try decoder.decodeSingularUInt32Field(value: &_storage._gameServerIp) }() case 5: try { try decoder.decodeSingularUInt32Field(value: &_storage._gameServerPort) }() case 6: try { try decoder.decodeSingularUInt32Field(value: &_storage._personaStateFlags) }() case 7: try { try decoder.decodeSingularUInt32Field(value: &_storage._onlineSessionInstances) }() case 10: try { try decoder.decodeSingularBoolField(value: &_storage._personaSetByUser) }() case 15: try { try decoder.decodeSingularStringField(value: &_storage._playerName) }() case 20: try { try decoder.decodeSingularUInt32Field(value: &_storage._queryPort) }() case 25: try { try decoder.decodeSingularFixed64Field(value: &_storage._steamidSource) }() case 31: try { try decoder.decodeSingularBytesField(value: &_storage._avatarHash) }() case 45: try { try decoder.decodeSingularUInt32Field(value: &_storage._lastLogoff) }() case 46: try { try decoder.decodeSingularUInt32Field(value: &_storage._lastLogon) }() case 47: try { try decoder.decodeSingularUInt32Field(value: &_storage._lastSeenOnline) }() case 50: try { try decoder.decodeSingularUInt32Field(value: &_storage._clanRank) }() case 55: try { try decoder.decodeSingularStringField(value: &_storage._gameName) }() case 56: try { try decoder.decodeSingularFixed64Field(value: &_storage._gameid) }() case 60: try { try decoder.decodeSingularBytesField(value: &_storage._gameDataBlob) }() case 64: try { try decoder.decodeSingularMessageField(value: &_storage._clanData) }() case 65: try { try decoder.decodeSingularStringField(value: &_storage._clanTag) }() case 71: try { try decoder.decodeRepeatedMessageField(value: &_storage._richPresence) }() case 72: try { try decoder.decodeSingularFixed64Field(value: &_storage._broadcastID) }() case 73: try { try decoder.decodeSingularFixed64Field(value: &_storage._gameLobbyID) }() case 74: try { try decoder.decodeSingularUInt32Field(value: &_storage._watchingBroadcastAccountid) }() case 75: try { try decoder.decodeSingularUInt32Field(value: &_storage._watchingBroadcastAppid) }() case 76: try { try decoder.decodeSingularUInt32Field(value: &_storage._watchingBroadcastViewers) }() case 77: try { try decoder.decodeSingularStringField(value: &_storage._watchingBroadcastTitle) }() case 78: try { try decoder.decodeSingularBoolField(value: &_storage._isCommunityBanned) }() case 79: try { try decoder.decodeSingularBoolField(value: &_storage._playerNamePendingReview) }() case 80: try { try decoder.decodeSingularBoolField(value: &_storage._avatarPendingReview) }() default: break } } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = _storage._friendid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = _storage._personaState { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2) } }() try { if let v = _storage._gamePlayedAppID { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3) } }() try { if let v = _storage._gameServerIp { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4) } }() try { if let v = _storage._gameServerPort { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5) } }() try { if let v = _storage._personaStateFlags { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 6) } }() try { if let v = _storage._onlineSessionInstances { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 7) } }() try { if let v = _storage._personaSetByUser { try visitor.visitSingularBoolField(value: v, fieldNumber: 10) } }() try { if let v = _storage._playerName { try visitor.visitSingularStringField(value: v, fieldNumber: 15) } }() try { if let v = _storage._queryPort { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 20) } }() try { if let v = _storage._steamidSource { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 25) } }() try { if let v = _storage._avatarHash { try visitor.visitSingularBytesField(value: v, fieldNumber: 31) } }() try { if let v = _storage._lastLogoff { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 45) } }() try { if let v = _storage._lastLogon { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 46) } }() try { if let v = _storage._lastSeenOnline { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 47) } }() try { if let v = _storage._clanRank { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 50) } }() try { if let v = _storage._gameName { try visitor.visitSingularStringField(value: v, fieldNumber: 55) } }() try { if let v = _storage._gameid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 56) } }() try { if let v = _storage._gameDataBlob { try visitor.visitSingularBytesField(value: v, fieldNumber: 60) } }() try { if let v = _storage._clanData { try visitor.visitSingularMessageField(value: v, fieldNumber: 64) } }() try { if let v = _storage._clanTag { try visitor.visitSingularStringField(value: v, fieldNumber: 65) } }() if !_storage._richPresence.isEmpty { try visitor.visitRepeatedMessageField(value: _storage._richPresence, fieldNumber: 71) } try { if let v = _storage._broadcastID { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 72) } }() try { if let v = _storage._gameLobbyID { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 73) } }() try { if let v = _storage._watchingBroadcastAccountid { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 74) } }() try { if let v = _storage._watchingBroadcastAppid { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 75) } }() try { if let v = _storage._watchingBroadcastViewers { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 76) } }() try { if let v = _storage._watchingBroadcastTitle { try visitor.visitSingularStringField(value: v, fieldNumber: 77) } }() try { if let v = _storage._isCommunityBanned { try visitor.visitSingularBoolField(value: v, fieldNumber: 78) } }() try { if let v = _storage._playerNamePendingReview { try visitor.visitSingularBoolField(value: v, fieldNumber: 79) } }() try { if let v = _storage._avatarPendingReview { try visitor.visitSingularBoolField(value: v, fieldNumber: 80) } }() } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientPersonaState.Friend, rhs: CMsgClientPersonaState.Friend) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._friendid != rhs_storage._friendid {return false} if _storage._personaState != rhs_storage._personaState {return false} if _storage._gamePlayedAppID != rhs_storage._gamePlayedAppID {return false} if _storage._gameServerIp != rhs_storage._gameServerIp {return false} if _storage._gameServerPort != rhs_storage._gameServerPort {return false} if _storage._personaStateFlags != rhs_storage._personaStateFlags {return false} if _storage._onlineSessionInstances != rhs_storage._onlineSessionInstances {return false} if _storage._personaSetByUser != rhs_storage._personaSetByUser {return false} if _storage._playerName != rhs_storage._playerName {return false} if _storage._queryPort != rhs_storage._queryPort {return false} if _storage._steamidSource != rhs_storage._steamidSource {return false} if _storage._avatarHash != rhs_storage._avatarHash {return false} if _storage._lastLogoff != rhs_storage._lastLogoff {return false} if _storage._lastLogon != rhs_storage._lastLogon {return false} if _storage._lastSeenOnline != rhs_storage._lastSeenOnline {return false} if _storage._clanRank != rhs_storage._clanRank {return false} if _storage._gameName != rhs_storage._gameName {return false} if _storage._gameid != rhs_storage._gameid {return false} if _storage._gameDataBlob != rhs_storage._gameDataBlob {return false} if _storage._clanData != rhs_storage._clanData {return false} if _storage._clanTag != rhs_storage._clanTag {return false} if _storage._richPresence != rhs_storage._richPresence {return false} if _storage._broadcastID != rhs_storage._broadcastID {return false} if _storage._gameLobbyID != rhs_storage._gameLobbyID {return false} if _storage._watchingBroadcastAccountid != rhs_storage._watchingBroadcastAccountid {return false} if _storage._watchingBroadcastAppid != rhs_storage._watchingBroadcastAppid {return false} if _storage._watchingBroadcastViewers != rhs_storage._watchingBroadcastViewers {return false} if _storage._watchingBroadcastTitle != rhs_storage._watchingBroadcastTitle {return false} if _storage._isCommunityBanned != rhs_storage._isCommunityBanned {return false} if _storage._playerNamePendingReview != rhs_storage._playerNamePendingReview {return false} if _storage._avatarPendingReview != rhs_storage._avatarPendingReview {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientPersonaState.Friend.ClanData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientPersonaState.Friend.protoMessageName + ".ClanData" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "ogg_app_id"), 2: .standard(proto: "chat_group_id"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._oggAppID) }() case 2: try { try decoder.decodeSingularUInt64Field(value: &self._chatGroupID) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._oggAppID { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._chatGroupID { try visitor.visitSingularUInt64Field(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientPersonaState.Friend.ClanData, rhs: CMsgClientPersonaState.Friend.ClanData) -> Bool { if lhs._oggAppID != rhs._oggAppID {return false} if lhs._chatGroupID != rhs._chatGroupID {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientPersonaState.Friend.KV: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientPersonaState.Friend.protoMessageName + ".KV" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "key"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self._key) }() case 2: try { try decoder.decodeSingularStringField(value: &self._value) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._key { try visitor.visitSingularStringField(value: v, fieldNumber: 1) } }() try { if let v = self._value { try visitor.visitSingularStringField(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientPersonaState.Friend.KV, rhs: CMsgClientPersonaState.Friend.KV) -> Bool { if lhs._key != rhs._key {return false} if lhs._value != rhs._value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientFriendProfileInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientFriendProfileInfo" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "steamid_friend"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._steamidFriend) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._steamidFriend { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendProfileInfo, rhs: CMsgClientFriendProfileInfo) -> Bool { if lhs._steamidFriend != rhs._steamidFriend {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientFriendProfileInfoResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientFriendProfileInfoResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "eresult"), 2: .standard(proto: "steamid_friend"), 3: .standard(proto: "time_created"), 4: .standard(proto: "real_name"), 5: .standard(proto: "city_name"), 6: .standard(proto: "state_name"), 7: .standard(proto: "country_name"), 8: .same(proto: "headline"), 9: .same(proto: "summary"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt32Field(value: &self._eresult) }() case 2: try { try decoder.decodeSingularFixed64Field(value: &self._steamidFriend) }() case 3: try { try decoder.decodeSingularUInt32Field(value: &self._timeCreated) }() case 4: try { try decoder.decodeSingularStringField(value: &self._realName) }() case 5: try { try decoder.decodeSingularStringField(value: &self._cityName) }() case 6: try { try decoder.decodeSingularStringField(value: &self._stateName) }() case 7: try { try decoder.decodeSingularStringField(value: &self._countryName) }() case 8: try { try decoder.decodeSingularStringField(value: &self._headline) }() case 9: try { try decoder.decodeSingularStringField(value: &self._summary) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._eresult { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._steamidFriend { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 2) } }() try { if let v = self._timeCreated { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3) } }() try { if let v = self._realName { try visitor.visitSingularStringField(value: v, fieldNumber: 4) } }() try { if let v = self._cityName { try visitor.visitSingularStringField(value: v, fieldNumber: 5) } }() try { if let v = self._stateName { try visitor.visitSingularStringField(value: v, fieldNumber: 6) } }() try { if let v = self._countryName { try visitor.visitSingularStringField(value: v, fieldNumber: 7) } }() try { if let v = self._headline { try visitor.visitSingularStringField(value: v, fieldNumber: 8) } }() try { if let v = self._summary { try visitor.visitSingularStringField(value: v, fieldNumber: 9) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientFriendProfileInfoResponse, rhs: CMsgClientFriendProfileInfoResponse) -> Bool { if lhs._eresult != rhs._eresult {return false} if lhs._steamidFriend != rhs._steamidFriend {return false} if lhs._timeCreated != rhs._timeCreated {return false} if lhs._realName != rhs._realName {return false} if lhs._cityName != rhs._cityName {return false} if lhs._stateName != rhs._stateName {return false} if lhs._countryName != rhs._countryName {return false} if lhs._headline != rhs._headline {return false} if lhs._summary != rhs._summary {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientCreateFriendsGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientCreateFriendsGroup" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "steamid"), 2: .same(proto: "groupname"), 3: .standard(proto: "steamid_friends"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._steamid) }() case 2: try { try decoder.decodeSingularStringField(value: &self._groupname) }() case 3: try { try decoder.decodeRepeatedFixed64Field(value: &self.steamidFriends) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._steamid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._groupname { try visitor.visitSingularStringField(value: v, fieldNumber: 2) } }() if !self.steamidFriends.isEmpty { try visitor.visitRepeatedFixed64Field(value: self.steamidFriends, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientCreateFriendsGroup, rhs: CMsgClientCreateFriendsGroup) -> Bool { if lhs._steamid != rhs._steamid {return false} if lhs._groupname != rhs._groupname {return false} if lhs.steamidFriends != rhs.steamidFriends {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientCreateFriendsGroupResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientCreateFriendsGroupResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "eresult"), 2: .same(proto: "groupid"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._eresult) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self._groupid) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._eresult { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._groupid { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientCreateFriendsGroupResponse, rhs: CMsgClientCreateFriendsGroupResponse) -> Bool { if lhs._eresult != rhs._eresult {return false} if lhs._groupid != rhs._groupid {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientDeleteFriendsGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientDeleteFriendsGroup" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "steamid"), 2: .same(proto: "groupid"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularFixed64Field(value: &self._steamid) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self._groupid) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._steamid { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 1) } }() try { if let v = self._groupid { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientDeleteFriendsGroup, rhs: CMsgClientDeleteFriendsGroup) -> Bool { if lhs._steamid != rhs._steamid {return false} if lhs._groupid != rhs._groupid {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientDeleteFriendsGroupResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientDeleteFriendsGroupResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "eresult"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._eresult) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._eresult { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientDeleteFriendsGroupResponse, rhs: CMsgClientDeleteFriendsGroupResponse) -> Bool { if lhs._eresult != rhs._eresult {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientManageFriendsGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientManageFriendsGroup" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "groupid"), 2: .same(proto: "groupname"), 3: .standard(proto: "steamid_friends_added"), 4: .standard(proto: "steamid_friends_removed"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt32Field(value: &self._groupid) }() case 2: try { try decoder.decodeSingularStringField(value: &self._groupname) }() case 3: try { try decoder.decodeRepeatedFixed64Field(value: &self.steamidFriendsAdded) }() case 4: try { try decoder.decodeRepeatedFixed64Field(value: &self.steamidFriendsRemoved) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._groupid { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._groupname { try visitor.visitSingularStringField(value: v, fieldNumber: 2) } }() if !self.steamidFriendsAdded.isEmpty { try visitor.visitRepeatedFixed64Field(value: self.steamidFriendsAdded, fieldNumber: 3) } if !self.steamidFriendsRemoved.isEmpty { try visitor.visitRepeatedFixed64Field(value: self.steamidFriendsRemoved, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientManageFriendsGroup, rhs: CMsgClientManageFriendsGroup) -> Bool { if lhs._groupid != rhs._groupid {return false} if lhs._groupname != rhs._groupname {return false} if lhs.steamidFriendsAdded != rhs.steamidFriendsAdded {return false} if lhs.steamidFriendsRemoved != rhs.steamidFriendsRemoved {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientManageFriendsGroupResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientManageFriendsGroupResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "eresult"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._eresult) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._eresult { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientManageFriendsGroupResponse, rhs: CMsgClientManageFriendsGroupResponse) -> Bool { if lhs._eresult != rhs._eresult {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientAddFriendToGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientAddFriendToGroup" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "groupid"), 2: .same(proto: "steamiduser"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt32Field(value: &self._groupid) }() case 2: try { try decoder.decodeSingularFixed64Field(value: &self._steamiduser) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._groupid { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._steamiduser { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientAddFriendToGroup, rhs: CMsgClientAddFriendToGroup) -> Bool { if lhs._groupid != rhs._groupid {return false} if lhs._steamiduser != rhs._steamiduser {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientAddFriendToGroupResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientAddFriendToGroupResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "eresult"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._eresult) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._eresult { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientAddFriendToGroupResponse, rhs: CMsgClientAddFriendToGroupResponse) -> Bool { if lhs._eresult != rhs._eresult {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientRemoveFriendFromGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientRemoveFriendFromGroup" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "groupid"), 2: .same(proto: "steamiduser"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt32Field(value: &self._groupid) }() case 2: try { try decoder.decodeSingularFixed64Field(value: &self._steamiduser) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._groupid { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } }() try { if let v = self._steamiduser { try visitor.visitSingularFixed64Field(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientRemoveFriendFromGroup, rhs: CMsgClientRemoveFriendFromGroup) -> Bool { if lhs._groupid != rhs._groupid {return false} if lhs._steamiduser != rhs._steamiduser {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientRemoveFriendFromGroupResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientRemoveFriendFromGroupResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "eresult"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self._eresult) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._eresult { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientRemoveFriendFromGroupResponse, rhs: CMsgClientRemoveFriendFromGroupResponse) -> Bool { if lhs._eresult != rhs._eresult {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientGetEmoticonList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientGetEmoticonList" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientGetEmoticonList, rhs: CMsgClientGetEmoticonList) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientEmoticonList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "CMsgClientEmoticonList" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "emoticons"), 2: .same(proto: "stickers"), 3: .same(proto: "effects"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.emoticons) }() case 2: try { try decoder.decodeRepeatedMessageField(value: &self.stickers) }() case 3: try { try decoder.decodeRepeatedMessageField(value: &self.effects) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.emoticons.isEmpty { try visitor.visitRepeatedMessageField(value: self.emoticons, fieldNumber: 1) } if !self.stickers.isEmpty { try visitor.visitRepeatedMessageField(value: self.stickers, fieldNumber: 2) } if !self.effects.isEmpty { try visitor.visitRepeatedMessageField(value: self.effects, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientEmoticonList, rhs: CMsgClientEmoticonList) -> Bool { if lhs.emoticons != rhs.emoticons {return false} if lhs.stickers != rhs.stickers {return false} if lhs.effects != rhs.effects {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientEmoticonList.Emoticon: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientEmoticonList.protoMessageName + ".Emoticon" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .same(proto: "count"), 3: .standard(proto: "time_last_used"), 4: .standard(proto: "use_count"), 5: .standard(proto: "time_received"), 6: .same(proto: "appid"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self._name) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self._count) }() case 3: try { try decoder.decodeSingularUInt32Field(value: &self._timeLastUsed) }() case 4: try { try decoder.decodeSingularUInt32Field(value: &self._useCount) }() case 5: try { try decoder.decodeSingularUInt32Field(value: &self._timeReceived) }() case 6: try { try decoder.decodeSingularUInt32Field(value: &self._appid) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._name { try visitor.visitSingularStringField(value: v, fieldNumber: 1) } }() try { if let v = self._count { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } }() try { if let v = self._timeLastUsed { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3) } }() try { if let v = self._useCount { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4) } }() try { if let v = self._timeReceived { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5) } }() try { if let v = self._appid { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 6) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientEmoticonList.Emoticon, rhs: CMsgClientEmoticonList.Emoticon) -> Bool { if lhs._name != rhs._name {return false} if lhs._count != rhs._count {return false} if lhs._timeLastUsed != rhs._timeLastUsed {return false} if lhs._useCount != rhs._useCount {return false} if lhs._timeReceived != rhs._timeReceived {return false} if lhs._appid != rhs._appid {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientEmoticonList.Sticker: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientEmoticonList.protoMessageName + ".Sticker" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .same(proto: "count"), 3: .standard(proto: "time_received"), 4: .same(proto: "appid"), 5: .standard(proto: "time_last_used"), 6: .standard(proto: "use_count"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self._name) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self._count) }() case 3: try { try decoder.decodeSingularUInt32Field(value: &self._timeReceived) }() case 4: try { try decoder.decodeSingularUInt32Field(value: &self._appid) }() case 5: try { try decoder.decodeSingularUInt32Field(value: &self._timeLastUsed) }() case 6: try { try decoder.decodeSingularUInt32Field(value: &self._useCount) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._name { try visitor.visitSingularStringField(value: v, fieldNumber: 1) } }() try { if let v = self._count { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } }() try { if let v = self._timeReceived { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3) } }() try { if let v = self._appid { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4) } }() try { if let v = self._timeLastUsed { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5) } }() try { if let v = self._useCount { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 6) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientEmoticonList.Sticker, rhs: CMsgClientEmoticonList.Sticker) -> Bool { if lhs._name != rhs._name {return false} if lhs._count != rhs._count {return false} if lhs._timeReceived != rhs._timeReceived {return false} if lhs._appid != rhs._appid {return false} if lhs._timeLastUsed != rhs._timeLastUsed {return false} if lhs._useCount != rhs._useCount {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CMsgClientEmoticonList.Effect: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = CMsgClientEmoticonList.protoMessageName + ".Effect" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .same(proto: "count"), 3: .standard(proto: "time_received"), 4: .standard(proto: "infinite_use"), 5: .same(proto: "appid"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self._name) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self._count) }() case 3: try { try decoder.decodeSingularUInt32Field(value: &self._timeReceived) }() case 4: try { try decoder.decodeSingularBoolField(value: &self._infiniteUse) }() case 5: try { try decoder.decodeSingularUInt32Field(value: &self._appid) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._name { try visitor.visitSingularStringField(value: v, fieldNumber: 1) } }() try { if let v = self._count { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } }() try { if let v = self._timeReceived { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3) } }() try { if let v = self._infiniteUse { try visitor.visitSingularBoolField(value: v, fieldNumber: 4) } }() try { if let v = self._appid { try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CMsgClientEmoticonList.Effect, rhs: CMsgClientEmoticonList.Effect) -> Bool { if lhs._name != rhs._name {return false} if lhs._count != rhs._count {return false} if lhs._timeReceived != rhs._timeReceived {return false} if lhs._infiniteUse != rhs._infiniteUse {return false} if lhs._appid != rhs._appid {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
43.989715
162
0.715273
e9d7d2e3d6510aa67519770236748384c0c13faf
3,057
public struct Stepper<Label>: View where Label: View { internal var label: Label public var onIncrement: (() -> Void)? public var onDecrement: (() -> Void)? public var onEditingChanged: (Bool) -> Void public init(onIncrement: (() -> Void)?, onDecrement: (() -> Void)?, onEditingChanged: @escaping (Bool) -> Void = { _ in }, @ViewBuilder label: () -> Label) { self.label = label() self.onIncrement = onIncrement self.onDecrement = onDecrement self.onEditingChanged = onEditingChanged } public var body: some View { return label } } extension Stepper { public init<V>(value: Binding<V>, step: V.Stride = 1, onEditingChanged: @escaping (Bool) -> Void = { _ in }, @ViewBuilder label: () -> Label) where V: Strideable { self.label = label() self.onEditingChanged = onEditingChanged } public init<V>(value: Binding<V>, in bounds: ClosedRange<V>, step: V.Stride = 1, onEditingChanged: @escaping (Bool) -> Void = { _ in }, @ViewBuilder label: () -> Label) where V: Strideable { self.label = label() self.onEditingChanged = onEditingChanged } } extension Stepper where Label == Text { public init(_ titleKey: LocalizedStringKey, onIncrement: (() -> Void)?, onDecrement: (() -> Void)?, onEditingChanged: @escaping (Bool) -> Void = { _ in }) { self.label = Text(titleKey) self.onIncrement = onIncrement self.onDecrement = onDecrement self.onEditingChanged = onEditingChanged } @_disfavoredOverload public init<S>(_ title: S, onIncrement: (() -> Void)?, onDecrement: (() -> Void)?, onEditingChanged: @escaping (Bool) -> Void = { _ in }) where S: StringProtocol { self.label = Text(title) self.onIncrement = onIncrement self.onDecrement = onDecrement self.onEditingChanged = onEditingChanged } public init<V>(_ titleKey: LocalizedStringKey, value: Binding<V>, step: V.Stride = 1, onEditingChanged: @escaping (Bool) -> Void = { _ in }) where V: Strideable { self.label = Text(titleKey) self.onEditingChanged = onEditingChanged } @_disfavoredOverload public init<S, V>(_ title: S, value: Binding<V>, step: V.Stride = 1, onEditingChanged: @escaping (Bool) -> Void = { _ in }) where S: StringProtocol, V: Strideable { self.label = Text(title) self.onEditingChanged = onEditingChanged } public init<V>(_ titleKey: LocalizedStringKey, value: Binding<V>, in bounds: ClosedRange<V>, step: V.Stride = 1, onEditingChanged: @escaping (Bool) -> Void = { _ in }) where V: Strideable { self.label = Text(titleKey) self.onEditingChanged = onEditingChanged } @_disfavoredOverload public init<S, V>(_ title: S, value: Binding<V>, in bounds: ClosedRange<V>, step: V.Stride = 1, onEditingChanged: @escaping (Bool) -> Void = { _ in }) where S: StringProtocol, V: Strideable { self.label = Text(title) self.onEditingChanged = onEditingChanged } }
44.955882
216
0.63559
615407f378eb4141926f2296c3f37aae99035e28
8,390
// // Tagsnapshots.swift // RsyncOSX // // Created by Thomas Evensen on 09/12/2018. // Copyright © 2018 Thomas Evensen. All rights reserved. // // swiftlint:disable line_length import Foundation final class TagSnapshots { var day: NumDayofweek? var nameofday: StringDayofweek? var daylocalized = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] var logrecordssnapshot: [Logrecordsschedules]? private var numberoflogs: Int? private var keepallselcteddayofweek: Bool = true var now: String? var selecteduuids = Set<UUID>() private func datefromstring(datestringlocalized: String) -> Date { guard datestringlocalized != "no log" else { return Date() } return datestringlocalized.localized_date_from_string() } private func datecomponentsfromstring(datestringlocalized: String?) -> DateComponents { var date: Date? if datestringlocalized != nil { date = datefromstring(datestringlocalized: datestringlocalized!) } let calendar = Calendar.current return calendar.dateComponents([.calendar, .timeZone, .year, .month, .day, .hour, .minute, .weekday, .weekOfYear, .year], from: date ?? Date()) } private func markfordelete() { for i in 0 ..< (logrecordssnapshot?.count ?? 0) { let index = (logrecordssnapshot?.count ?? 0) - 1 - i if currentweek(index: index) { // logrecordssnapshot?[index].selectsnap = 0 } else if currentdaymonth(index: index) { // Select the record if let id = logrecordssnapshot?[index].id { selecteduuids.insert(id) } } else { if keepallorlastdayinperiod(index: index) { // Select the record if let id = logrecordssnapshot?[index].id { selecteduuids.insert(id) } } } } } // Keep all snapshots current week. private func currentweek(index: Int) -> Bool { let datesnapshotstring = logrecordssnapshot?[index].dateExecuted if datecomponentsfromstring(datestringlocalized: datesnapshotstring).weekOfYear == datecomponentsfromstring(datestringlocalized: now).weekOfYear, datecomponentsfromstring(datestringlocalized: datesnapshotstring).year == datecomponentsfromstring(datestringlocalized: now).year { let tag = "Keep" + " " + "this week" logrecordssnapshot?[index].period = tag return true } return false } // Keep snapshots every choosen day this month ex current week private func currentdaymonth(index: Int) -> Bool { if let datesnapshotstring = logrecordssnapshot?[index].dateExecuted { let month = datefromstring(datestringlocalized: datesnapshotstring).monthNameShort() let day = datefromstring(datestringlocalized: datesnapshotstring).dayNameShort() if datecomponentsfromstring(datestringlocalized: datesnapshotstring).month == datecomponentsfromstring(datestringlocalized: now).month, datecomponentsfromstring(datestringlocalized: datesnapshotstring).year == datecomponentsfromstring(datestringlocalized: now).year { if datefromstring(datestringlocalized: datesnapshotstring).isSelectedDayofWeek(day: self.day!) == false { let tag = "Delete" + " " + day + ", " + month + " " + "this month" logrecordssnapshot?[index].period = tag return true } else { let tag = "Keep" + " " + month + " " + daylocalized[self.day!.rawValue - 1] + " " + "this month" logrecordssnapshot?[index].period = tag return false } } return false } return false } typealias Keepallorlastdayinperiodfunc = (Date) -> Bool func keepallorlastdayinperiod(index: Int) -> Bool { var check: Keepallorlastdayinperiodfunc? if keepallselcteddayofweek { check = isselectedDayinWeek } else { check = islastSelectedDayinMonth } if let datesnapshotstring = logrecordssnapshot?[index].dateExecuted { let month = datefromstring(datestringlocalized: datesnapshotstring).monthNameShort() let day = datefromstring(datestringlocalized: datesnapshotstring).dayNameShort() if datecomponentsfromstring(datestringlocalized: datesnapshotstring).month != datecomponentsfromstring(datestringlocalized: now).month || datecomponentsfromstring(datestringlocalized: datesnapshotstring).year! < datecomponentsfromstring(datestringlocalized: now).year! { if check!(datefromstring(datestringlocalized: datesnapshotstring)) == true { if datecomponentsfromstring(datestringlocalized: datesnapshotstring).month == datecomponentsfromstring(datestringlocalized: now).month! - 1 { let tag = "Keep" + " " + day + ", " + month + " " + "previous month" logrecordssnapshot?[index].period = tag } else { let tag = "Keep" + " " + day + ", " + month + " " + "earlier months" logrecordssnapshot?[index].period = tag } return false } else { let date = datefromstring(datestringlocalized: datesnapshotstring) if date.ispreviousmont { let tag = "Delete" + " " + day + ", " + month + " " + "previous month" logrecordssnapshot?[index].period = tag } else { let tag = "Delete" + " " + day + ", " + month + " " + "earlier months" logrecordssnapshot?[index].period = tag } return true } } return false } return false } func islastSelectedDayinMonth(_ date: Date) -> Bool { if date.isSelectedDayofWeek(day: day!), date.daymonth() > 24 { return true } else { return false } } func isselectedDayinWeek(_ date: Date) -> Bool { return day?.rawValue == date.getWeekday() } private func setweekdaytokeep(snapdayoffweek: String) { switch snapdayoffweek { case StringDayofweek.Monday.rawValue: day = .Monday nameofday = .Monday case StringDayofweek.Tuesday.rawValue: day = .Tuesday nameofday = .Tuesday case StringDayofweek.Wednesday.rawValue: day = .Wednesday nameofday = .Wednesday case StringDayofweek.Thursday.rawValue: day = .Thursday nameofday = .Thursday case StringDayofweek.Friday.rawValue: day = .Friday nameofday = .Friday case StringDayofweek.Saturday.rawValue: day = .Saturday nameofday = .Saturday case StringDayofweek.Sunday.rawValue: day = .Sunday nameofday = .Sunday default: day = .Sunday nameofday = .Sunday } } init(plan: Int, snapdayoffweek: String, data: [Logrecordsschedules]?) { // which plan to apply if plan == 1 { keepallselcteddayofweek = true } else { keepallselcteddayofweek = false } setweekdaytokeep(snapdayoffweek: snapdayoffweek) logrecordssnapshot = data guard logrecordssnapshot != nil else { return } numberoflogs = logrecordssnapshot?.count ?? 0 now = Date().localized_string_from_date() markfordelete() } deinit { // print("deinit TagSnapshots") } }
39.763033
161
0.559714
e53c11acb40eb9b703fb61f5a11e35864f31ed68
32
import Foundation enum Menu {}
8
17
0.75
deea90bbfd25faf2319f3ffa1a5cea7aea4fedbe
1,286
// // MalvonTests.swift // MalvonTests // // Created by Ashwin Paudel on 2021-12-29. // Copyright © 2021-2022 Ashwin Paudel. All rights reserved. // @testable import Malvon import XCTest class MalvonTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
35.722222
130
0.679627
09122d370f3d47c380a831f5f95c508e9e2d54f5
526
// // ViewController.swift // YAssistive // // Created by NSObject-Y on 05/26/2018. // Copyright (c) 2018 NSObject-Y. All rights reserved. // import UIKit import YAssistive 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. } }
20.230769
80
0.676806
f5eb6a03331d5e04b75a47adbcf60ba00bc05221
923
// // JSONError.swift // OnTheMap // // Created by Luke Van In on 2017/01/15. // Copyright © 2017 Luke Van In. All rights reserved. // // Errors which occur during parseing JSON. // import Foundation enum JSONError: Error { // // The data is in an unexpected format. E.g. The app expects a dictionary but the API returned an array. // case format(String) // // A required field is missing, or a field is formatted incorrectly. E.g. The latitude is returned from the API as // a string, but the app expects a number. // case field(String) } extension JSONError: LocalizedError { var errorDescription: String? { switch self { case .format(let type): return "Unexpected data format. Expected \(type)." case .field(let name): return "Field '\(name)' is missing or invalid" } } }
23.666667
120
0.602384
383d6d1ad4ee410007e8633c55f6770729234fd8
757
// // Stitch+Token.swift // // // Created by Elizabeth Siemer on 6/23/19. // import Foundation import CloudKit extension StitchStore { func token() -> CKServerChangeToken? { guard let data = metadata[Metadata.SyncTokenKey] as? Data else { return nil } return NSKeyedUnarchiver.unarchiveObject(with: data) as? CKServerChangeToken } func saveToken(_ serverChangeToken: CKServerChangeToken?) { newToken = serverChangeToken } func commitToken() { if let token = self.newToken { let data = NSKeyedArchiver.archivedData(withRootObject: token) setMetadata(data as AnyObject, key: Metadata.SyncTokenKey) } } func deleteToken() { setMetadata(nil, key: Metadata.SyncTokenKey) } }
23.65625
83
0.682959
e2746da71172fd35a6b4ffc7c59993a8197b4f43
10,641
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation open class NSLocale: NSObject, NSCopying, NSSecureCoding { typealias CFType = CFLocale private var _base = _CFInfo(typeID: CFLocaleGetTypeID()) private var _identifier: UnsafeMutableRawPointer? = nil private var _cache: UnsafeMutableRawPointer? = nil private var _prefs: UnsafeMutableRawPointer? = nil #if os(OSX) || os(iOS) private var _lock = pthread_mutex_t() #elseif os(Linux) || os(Android) || CYGWIN private var _lock = Int32(0) #endif private var _nullLocale = false internal var _cfObject: CFType { return unsafeBitCast(self, to: CFType.self) } open func object(forKey key: NSLocale.Key) -> AnyObject? { return CFLocaleGetValue(_cfObject, key.rawValue._cfObject) } open func displayName(forKey key: Key, value: String) -> String? { return CFLocaleCopyDisplayNameForPropertyValue(_cfObject, key.rawValue._cfObject, value._cfObject)?._swiftObject } public init(localeIdentifier string: String) { super.init() _CFLocaleInit(_cfObject, string._cfObject) } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let identifier = aDecoder.decodeObject(of: NSString.self, forKey: "NS.identifier") else { return nil } self.init(localeIdentifier: String._unconditionallyBridgeFromObjectiveC(identifier)) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } override open func isEqual(_ object: Any?) -> Bool { guard let locale = object as? NSLocale else { return false } return locale.localeIdentifier == localeIdentifier } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let identifier = CFLocaleGetIdentifier(self._cfObject)._nsObject aCoder.encode(identifier, forKey: "NS.identifier") } public static var supportsSecureCoding: Bool { return true } } extension NSLocale { open class var current: Locale { return CFLocaleCopyCurrent()._swiftObject } open class func systemLocale() -> Locale { return CFLocaleGetSystem()._swiftObject } } extension NSLocale { public var localeIdentifier: String { return (object(forKey: .identifier) as! NSString)._swiftObject } open class var availableLocaleIdentifiers: [String] { var identifiers = Array<String>() for obj in CFLocaleCopyAvailableLocaleIdentifiers()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } open class var isoLanguageCodes: [String] { var identifiers = Array<String>() for obj in CFLocaleCopyISOLanguageCodes()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } open class var isoCountryCodes: [String] { var identifiers = Array<String>() for obj in CFLocaleCopyISOCountryCodes()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } open class var isoCurrencyCodes: [String] { var identifiers = Array<String>() for obj in CFLocaleCopyISOCurrencyCodes()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } open class var commonISOCurrencyCodes: [String] { var identifiers = Array<String>() for obj in CFLocaleCopyCommonISOCurrencyCodes()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } open class var preferredLanguages: [String] { var identifiers = Array<String>() for obj in CFLocaleCopyPreferredLanguages()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } open class func components(fromLocaleIdentifier string: String) -> [String : String] { var comps = Dictionary<String, String>() let values = CFLocaleCreateComponentsFromLocaleIdentifier(kCFAllocatorSystemDefault, string._cfObject)._nsObject values.enumerateKeysAndObjects(options: []) { (k, v, stop) in let key = (k as! NSString)._swiftObject let value = (v as! NSString)._swiftObject comps[key] = value } return comps } open class func localeIdentifier(fromComponents dict: [String : String]) -> String { return CFLocaleCreateLocaleIdentifierFromComponents(kCFAllocatorSystemDefault, dict._cfObject)._swiftObject } open class func canonicalLocaleIdentifier(from string: String) -> String { return CFLocaleCreateCanonicalLocaleIdentifierFromString(kCFAllocatorSystemDefault, string._cfObject)._swiftObject } open class func canonicalLanguageIdentifier(from string: String) -> String { return CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorSystemDefault, string._cfObject)._swiftObject } open class func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { return CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode(kCFAllocatorSystemDefault, lcid)._swiftObject } open class func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { return CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier(localeIdentifier._cfObject) } open class func characterDirection(forLanguage isoLangCode: String) -> NSLocale.LanguageDirection { let dir = CFLocaleGetLanguageCharacterDirection(isoLangCode._cfObject) #if os(OSX) || os(iOS) return NSLocale.LanguageDirection(rawValue: UInt(dir.rawValue))! #else return NSLocale.LanguageDirection(rawValue: UInt(dir))! #endif } open class func lineDirection(forLanguage isoLangCode: String) -> NSLocale.LanguageDirection { let dir = CFLocaleGetLanguageLineDirection(isoLangCode._cfObject) #if os(OSX) || os(iOS) return NSLocale.LanguageDirection(rawValue: UInt(dir.rawValue))! #else return NSLocale.LanguageDirection(rawValue: UInt(dir))! #endif } } extension NSLocale { public struct Key : RawRepresentable, Equatable, Hashable, Comparable { public private(set) var rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return rawValue.hashValue } public static let identifier = NSLocale.Key(rawValue: "kCFLocaleIdentifierKey") public static let languageCode = NSLocale.Key(rawValue: "kCFLocaleLanguageCodeKey") public static let countryCode = NSLocale.Key(rawValue: "kCFLocaleCountryCodeKey") public static let scriptCode = NSLocale.Key(rawValue: "kCFLocaleScriptCodeKey") public static let variantCode = NSLocale.Key(rawValue: "kCFLocaleVariantCodeKey") public static let exemplarCharacterSet = NSLocale.Key(rawValue: "kCFLocaleExemplarCharacterSetKey") public static let calendar = NSLocale.Key(rawValue: "kCFLocaleCalendarKey") public static let collationIdentifier = NSLocale.Key(rawValue: "collation") public static let usesMetricSystem = NSLocale.Key(rawValue: "kCFLocaleUsesMetricSystemKey") public static let measurementSystem = NSLocale.Key(rawValue: "kCFLocaleMeasurementSystemKey") public static let decimalSeparator = NSLocale.Key(rawValue: "kCFLocaleDecimalSeparatorKey") public static let groupingSeparator = NSLocale.Key(rawValue: "kCFLocaleGroupingSeparatorKey") public static let currencySymbol = NSLocale.Key(rawValue: "kCFLocaleCurrencySymbolKey") public static let currencyCode = NSLocale.Key(rawValue: "currency") public static let collatorIdentifier = NSLocale.Key(rawValue: "kCFLocaleCollatorIdentifierKey") public static let quotationBeginDelimiterKey = NSLocale.Key(rawValue: "kCFLocaleQuotationBeginDelimiterKey") public static let quotationEndDelimiterKey = NSLocale.Key(rawValue: "kCFLocaleQuotationEndDelimiterKey") public static let calendarIdentifier = NSLocale.Key(rawValue: "kCFLocaleCalendarIdentifierKey") public static let alternateQuotationBeginDelimiterKey = NSLocale.Key(rawValue: "kCFLocaleAlternateQuotationBeginDelimiterKey") public static let alternateQuotationEndDelimiterKey = NSLocale.Key(rawValue: "kCFLocaleAlternateQuotationEndDelimiterKey") } public enum LanguageDirection : UInt { case unknown case leftToRight case rightToLeft case topToBottom case bottomToTop } } public func ==(_ lhs: NSLocale.Key, _ rhs: NSLocale.Key) -> Bool { return lhs.rawValue == rhs.rawValue } public func <(_ lhs: NSLocale.Key, _ rhs: NSLocale.Key) -> Bool { return lhs.rawValue < rhs.rawValue } public let NSCurrentLocaleDidChangeNotification: String = "kCFLocaleCurrentLocaleDidChangeNotification" extension CFLocale : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSLocale typealias SwiftType = Locale internal var _nsObject: NSLocale { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: Locale { return _nsObject._swiftObject } } extension NSLocale : _SwiftBridgeable { typealias SwiftType = Locale internal var _swiftObject: Locale { return Locale(reference: self) } } extension Locale : _CFBridgeable { typealias CFType = CFLocale internal var _cfObject: CFLocale { return _bridgeToObjectiveC()._cfObject } } extension NSLocale : _StructTypeBridgeable { public typealias _StructType = Locale public func _bridgeToSwift() -> Locale { return Locale._unconditionallyBridgeFromObjectiveC(self) } }
37.46831
134
0.696175
e21aa4213c0100660b7ba0687097b09ab12bbbd6
969
// // SettingsRouter.swift // PixPic // // Created by AndrewPetrov on 3/1/16. // Copyright © 2016 Yalantis. All rights reserved. // import Foundation class SettingsRouter: AlertManagerDelegate, FeedPresenter, AuthorizationPresenter { private(set) weak var currentViewController: UIViewController! private(set) weak var locator: ServiceLocator! init(locator: ServiceLocator) { self.locator = locator } } extension SettingsRouter: Router { func execute(context: AppearanceNavigationController) { execute(context, userInfo: nil) } func execute(context: AppearanceNavigationController, userInfo: AnyObject?) { let settingsController = SettingsViewController.create() settingsController.router = self settingsController.setLocator(locator) currentViewController = settingsController context.showViewController(settingsController, sender: self) } }
26.189189
83
0.707946
61684fb4f8c5c8286285888714c8ed2293c3abb8
2,589
/* * Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved. * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? weak var windowScene: UIWindowScene? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } SigninCoordinator.shared.windowScene = windowScene } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { guard let windowScene = scene as? UIWindowScene, UserManager.shared.current == nil else { return } SigninCoordinator.shared.show(in: windowScene) } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
39.830769
140
0.702202
c1f2ba3d226d1aebaf22db6b524b9f8a6abf6c8b
1,941
// MIT License // // Copyright (c) 2020 Declarative Hub // // 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 Mockingbird public protocol AnyUIKitNode: LayoutNode { var hierarchyIdentifier: String { get } var isSpacer: Bool { get } var layoutPriority: Double { get } func update(view: SomeView, context: Context) func layoutSize(fitting targetSize: CGSize, pass: LayoutPass) -> CGSize func layout(in container: Container, bounds: Bounds, pass: LayoutPass) } public protocol UIKitNode: AnyUIKitNode { associatedtype View: SomeView func update(view: View, context: Context) } extension AnyUIKitNode { public var isSpacer: Bool { false } public var layoutPriority: Double { 0 } } extension UIKitNode { public func update(view: SomeView, context: Context) { update(view: view as! View, context: context) } }
29.861538
81
0.729521
f9969c9aa4b9d2be72c78bb42a8d77db7a265e5a
324
// // ViewController.swift // NavigationItem // // Created by TRA on 7.03.2020. // Copyright © 2020 panda. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
15.428571
58
0.657407
28af9f5b4f4b07f2de5f974f7a575affbc928ce6
11,407
// // GameScene.swift // Ping Pong // // Created by Berk Çohadar on 10/13/21. // import SpriteKit import GameplayKit import AVFoundation class GameScene: SKScene, SKPhysicsContactDelegate{ var player1: SKShapeNode! var player2: SKShapeNode! var gameBall: SKShapeNode! var player1Label: SKLabelNode! var player2Label: SKLabelNode! var upgrade: SKShapeNode! var initLocationBall = CGPoint(x: 0, y: 0) var initLocationP1 = CGPoint(x: 0, y: 0) var initLocationP2 = CGPoint(x: 0, y: 0) var player1ScoreInt: Int = 0; // player1Score score value as int var player2ScoreInt: Int = 0; // player2Score score value as int var timer = Timer() var time = 2 var timer2 = Timer() var time2 = 6 var targetScore = 3 var winnerLabel: SKLabelNode! var ballHitSound : AVAudioPlayer? var paddleHitSound : AVAudioPlayer? var scoreSound : AVAudioPlayer? var ballHitSoundDir = Bundle.main.path(forResource: "ballHit", ofType: "wav") var paddleHitSoundDir = Bundle.main.path(forResource: "paddleHit", ofType: "wav") var scoreSoundDir = Bundle.main.path(forResource: "score", ofType: "wav") var ballSpeed = 275 override func didMove(to view: SKView) { player1Label = (self.childNode(withName: "player1ScoreLabel") as! SKLabelNode) player2Label = (self.childNode(withName: "player2ScoreLabel") as! SKLabelNode) winnerLabel = (self.childNode(withName: "winnerLabel") as! SKLabelNode) initLocationP1 = CGPoint(x: (self.size.width/2)/3 * -2.5, y: 0) initLocationP2 = CGPoint(x: (self.size.width/2)/3 * 2.5, y: 0) player1 = SKShapeNode(circleOfRadius: CGFloat(120)) player1.position = initLocationP1 player1.fillColor = .systemGreen player1.physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(120)) player1.physicsBody!.affectedByGravity = false player1.physicsBody?.isDynamic = false player1.physicsBody?.collisionBitMask = 2 player1.physicsBody?.categoryBitMask = 1 player1.physicsBody?.angularDamping = 0 player1.physicsBody?.linearDamping = 0 player1.physicsBody?.friction = 0 player1.physicsBody?.restitution = 0 player1.physicsBody?.contactTestBitMask = 2 player1.name = "player1" player2 = SKShapeNode(circleOfRadius: CGFloat(120)) player2.position = initLocationP2 player2.fillColor = .systemPink player2.physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(120)) player2.physicsBody!.affectedByGravity = false player2.physicsBody?.isDynamic = false player2.physicsBody?.collisionBitMask = 2 player2.physicsBody?.categoryBitMask = 1 player2.physicsBody?.angularDamping = 0 player2.physicsBody?.linearDamping = 0 player2.physicsBody?.friction = 0 player2.physicsBody?.restitution = 0 player2.physicsBody?.contactTestBitMask = 2 player2.name = "player2" gameBall = SKShapeNode(circleOfRadius: CGFloat(35)) gameBall.fillColor = .red gameBall.position = initLocationBall gameBall.physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(35)) gameBall.physicsBody!.affectedByGravity = false gameBall.physicsBody?.collisionBitMask = 1 gameBall.physicsBody?.categoryBitMask = 2 gameBall.physicsBody?.angularDamping = 0 gameBall.physicsBody?.linearDamping = 0 gameBall.physicsBody?.friction = 0 gameBall.physicsBody?.restitution = 1 gameBall.physicsBody?.allowsRotation = false gameBall.physicsBody?.isDynamic = true gameBall.zRotation = CGFloat.pi / 2 gameBall.name = "gameBall" let border = SKPhysicsBody(edgeLoopFrom: (view.scene?.frame)!) border.friction = 0 self.physicsBody = border self.physicsBody?.contactTestBitMask = 2 self.physicsWorld.contactDelegate = self self.name = "gameArea" self.addChild(player1) self.addChild(player2) if ((childNode(withName: "gameball")) == nil){ self.addChild(gameBall) } gameBall.physicsBody?.applyImpulse(CGVector(dx: ballSpeed, dy: 0)) timer2 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameScene.generateUpgrade), userInfo: nil, repeats: true) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let loc = touch.location(in: self) let radius = (self.size.width/2)/3 if (loc.x < 0) { player1.position.y = loc.y if(loc.x <= radius * -1) { player1.position.x = loc.x } } else { player2.position.y = loc.y if(loc.x >= radius) { player2.position.x = loc.x } } } } func didBegin(_ contact: SKPhysicsContact) { let firstContact = contact.bodyA.node?.name let secondContact = contact.bodyB.node?.name if ((firstContact == "gameBall" && (secondContact == "player1" || secondContact == "player2")) || ((firstContact == "player1" || firstContact == "player2") && secondContact == "gameBall")) { soundEffect(type: "paddleHit") } else if (firstContact == "gameBall" && secondContact == "gameArea" || firstContact == "gameArea" && secondContact == "gameBall") { if (gameBall.position.x < initLocationP1.x) { gameBall.removeFromParent() soundEffect(type: "scoreSound") player2ScoreInt += 1 player2Label.text = String(player2ScoreInt) if (player2ScoreInt == targetScore){ endGame(player: "player2") } else { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameScene.resetBall), userInfo: ["player":"player2"], repeats: true) } } else if (gameBall.position.x > initLocationP2.x) { gameBall.removeFromParent() soundEffect(type: "scoreSound") player1ScoreInt += 1 player1Label.text = String(player1ScoreInt) if (player1ScoreInt == targetScore){ endGame(player: "player1") } else { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameScene.resetBall), userInfo: ["player":"player1"], repeats: true) } } else { soundEffect(type: "ballHit") } } else if (firstContact == "gameBall" && secondContact == "upgrade" || firstContact == "upgrade" && secondContact == "gameBall") { upgrade.removeFromParent() gameBall.fillColor = .black ballSpeed = 450 } } @objc func resetBall(sender:Timer){ guard let players = sender.userInfo as? [String: String] else { return } let player = players["player", default: "Anonymous"] time = time - 1 if (time == 0){ gameBall.position = initLocationBall if ((childNode(withName: "gameball")) == nil){ self.addChild(gameBall) } if (player == "player1") { gameBall.physicsBody?.applyImpulse(CGVector(dx: ballSpeed, dy: 0)) } else { gameBall.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed, dy: 0)) } player1.position = initLocationP1 player2.position = initLocationP2 timer.invalidate() time = 2 ballSpeed = 275 } } @objc func endGame(player:String){ player1.position = initLocationP1 player2.position = initLocationP2 player1ScoreInt = 0 player1Label.text = String(player1ScoreInt) player2ScoreInt = 0 player2Label.text = String(player2ScoreInt) if (player == "player1"){ winnerLabel.position = CGPoint(x: 0, y: 0) winnerLabel.text = "player1 won" } else if (player == "player2"){ winnerLabel.position = CGPoint(x: 0, y: 0) winnerLabel.text = "player2 won" } } @objc func soundEffect(type:String) { switch type { case "ballHit": do { // SOUND ANIMATION PLAY ballHitSound = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: self.ballHitSoundDir!)) guard let ballHitSound = ballHitSound else { return } ballHitSound.play() } catch { print("Error while playing the ball hit sound.") } case "paddleHit": do { paddleHitSound = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: self.paddleHitSoundDir!)) guard let paddleHitSound = paddleHitSound else { return } paddleHitSound.play() } catch { print("Error while playing the paddle hit sound.") } case "scoreSound": do { scoreSound = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: self.scoreSoundDir!)) guard let scoreSound = scoreSound else { return } scoreSound.play() } catch { print("Error while playing the paddle hit sound.") } default: print("Sound has no type") break } } @objc func generateUpgrade(sender:Timer){ time2 = time2 - 1 if (time2 == 0){ if ((childNode(withName: "upgrade")) == nil){ upgrade = SKShapeNode(circleOfRadius: CGFloat(100)) upgrade.name = "upgrade" upgrade.fillColor = .white upgrade.fillTexture = SKTexture(imageNamed: "bingball") let randomLocX = Int.random(in: Int(self.frame.minX + 300)...Int(self.frame.maxX - 300)) let randomLocY = Int.random(in: Int(self.frame.minY + 160)...Int(self.frame.maxY - 160)) upgrade.position = CGPoint(x: CGFloat(randomLocX), y: CGFloat(randomLocY)) upgrade.physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(10)) upgrade.physicsBody?.linearDamping = 0 upgrade.physicsBody?.angularDamping = 0 upgrade.physicsBody?.affectedByGravity = false upgrade.physicsBody?.restitution = 0 upgrade.physicsBody?.categoryBitMask = 1 upgrade.physicsBody?.collisionBitMask = 2 upgrade.physicsBody?.contactTestBitMask = 2 self.addChild(upgrade) } time2 = 10 } } }
37.89701
198
0.568072
290981e35285bf7e5c0c683568a9112249843050
7,931
// // Created by Concordium on 18/05/2020. // Copyright (c) 2020 concordium. All rights reserved. // import Foundation enum ImportError: Error { case corruptDataError(reason: String) case unsupportedVersion(inputVersion: Int) case unsupportedWalletType(type: String) case unsupportedEnvironemt(environment: String) case missingIdentitiesError } struct ExportService { let storageManager: StorageManagerProtocol init(storageManager: StorageManagerProtocol) { self.storageManager = storageManager } func urlForFile() -> URL { let documentDirectory = FileManager.default.urls(for: .documentationDirectory, in: .userDomainMask).first! // it appears that the documentation directory does not necessarily exist in advance - create it if it doesn't try? FileManager.default.createDirectory(at: documentDirectory, withIntermediateDirectories: true) return documentDirectory.appendingPathComponent("export.concordiumwallet") } func deleteExportFile() throws { try FileManager.default.removeItem(at: urlForFile()) } func export(pwHash: String, exportPassword: String) throws -> URL { let exportObject = exportAll(pwHash: pwHash) let exportObjectData = try exportObject.jsonData() // let json = try? exportObject.jsonString() // Logger.debug("json: \(json)") let exportDataWithEncryption = try encryptExport(exportObjectData, exportPassword: exportPassword) let url = urlForFile() Logger.trace("write export to file \(url)") try exportDataWithEncryption.write(to: url, options: .completeFileProtection) return url } private func encryptExport(_ exportObjectData: Data, exportPassword: String) throws -> Data { let iterations = 100_000 let salt = AES256Crypter.randomSalt() let iv = AES256Crypter.randomIv() let encryptionMetadata = EncryptionMetadata(iterations: iterations, salt: salt.base64EncodedString(), initializationVector: iv.base64EncodedString()) let key = try AES256Crypter.createKey(password: exportPassword, salt: salt, rounds: iterations) let cipher = try AES256Crypter(key: key, iv: iv).encrypt(exportObjectData) let exportContainer = ExportContainer(metadata: encryptionMetadata, cipherText: cipher.base64EncodedString()) return try exportContainer.jsonData() } private func exportAll(pwHash: String) -> ExportVersionContainer { let recipients = getRecipients() let identities: [ExportIdentityData] = getIdentities(pwHash: pwHash) let exportContainer = ExportValues(identities: identities, recipients: recipients) return ExportVersionContainer(value: exportContainer) } private func getRecipients() -> [ExportRecipient] { // exclude unfinished accounts from recipients let unfinishedAccounts: [AccountDataType] = storageManager.getAccounts().filter { $0.transactionStatus != SubmissionStatusEnum.finalized } return storageManager.getRecipients().filter({ (recipient) -> Bool in !unfinishedAccounts.contains { (account) -> Bool in account.address == recipient.address } }).map { ExportRecipient(name: $0.name, address: $0.address) } } private func getIdentities(pwHash: String) -> [ExportIdentityData] { storageManager.getConfirmedIdentities().compactMap { identity in guard let privateIdObjectDataKey = identity.encryptedPrivateIdObjectData, let privateIDObjectData = try? storageManager.getPrivateIdObjectData(key: privateIdObjectDataKey, pwHash: pwHash).get() else { return nil } let accounts = getAccounts(for: identity, pwHash: pwHash) return ExportIdentityData(identity: identity, accounts: accounts, privateIdObjectData: privateIDObjectData) } } private func getAccounts(for identity: IdentityDataType, pwHash: String) -> [ExportAccount] { let accounts: [AccountDataType] = storageManager.getAccounts(for: identity).filter { $0.transactionStatus == SubmissionStatusEnum.finalized } let exportAccounts: [ExportAccount] = accounts.compactMap { account in guard let encryptedAccountDataKey = account.encryptedAccountData, let encryptionKeyKey = account.encryptedPrivateKey, let accountKeys = try? storageManager.getPrivateAccountKeys(key: encryptedAccountDataKey, pwHash: pwHash).get(), let encryptionSecretKey = try? storageManager.getPrivateEncryptionKey(key: encryptionKeyKey, pwHash: pwHash).get() else { return nil } guard let commitmentsRandomnessKey = account.encryptedCommitmentsRandomness, let commitmentsRandomness = try? storageManager.getCommitmentsRandomness(key: commitmentsRandomnessKey, pwHash: pwHash).get() else { return ExportAccount( account: account, encryptedAccountKeys: accountKeys, encryptionSecretKey: encryptionSecretKey ) } return ExportAccount( account: account, encryptedAccountKeys: accountKeys, commitmentsRandomness: commitmentsRandomness, encryptionSecretKey: encryptionSecretKey ) } return exportAccounts } public func getUnfinalizedAccounts() -> [AccountDataType] { let accounts = storageManager.getAccounts().filter { (account) -> Bool in account.transactionStatus != SubmissionStatusEnum.finalized } return accounts } } extension ExportIdentityData { init?(identity: IdentityDataType, accounts: [ExportAccount], privateIdObjectData: PrivateIDObjectData?) { guard let identityProvider = identity.identityProvider, let ipInfo = identityProvider.ipInfo, let arsInfo = identityProvider.arsInfos, let identityObject = identity.identityObject, let privateIdObjectData = privateIdObjectData else { return nil } let ipMetaData = Metadata(support: identityProvider.support, issuanceStart: identityProvider.issuanceStartURL, icon: identityProvider.icon) let identityProviderElm = IPInfoResponseElement(ipInfo: ipInfo, arsInfos: arsInfo, metadata: ipMetaData) self.init(nextAccountNumber: identity.accountsCreated, identityProvider: identityProviderElm, identityObject: identityObject, privateIdObjectData: privateIdObjectData, name: identity.nickname, accounts: accounts) } } extension ExportAccount { init?( account: AccountDataType, encryptedAccountKeys: AccountKeys, commitmentsRandomness: CommitmentsRandomness? = nil, encryptionSecretKey: String ) { guard let submissionId = account.submissionId, let credential = account.credential, let name = account.name else { return nil } self.init( name: name, address: account.address, submissionId: submissionId, accountKeys: encryptedAccountKeys, commitmentsRandomness: commitmentsRandomness, revealedAttributes: account.revealedAttributes, credential: credential, encryptionSecretKey: encryptionSecretKey ) } }
43.103261
149
0.649855
eb314dfbe8df53351e567df296087aca92a37aad
11,019
// // SwipeExpansionStyle.swift // // Created by Jeremy Koch // Copyright © 2017 Jeremy Koch. All rights reserved. // import UIKit /// Describes the expansion style. Expansion is the behavior when the cell is swiped past a defined threshold. public struct SwipeExpansionStyle { /// The default action performs a selection-type behavior. The cell bounces back to its unopened state upon selection and the row remains in the table view. public static var selection: SwipeExpansionStyle { return SwipeExpansionStyle(target: .percentage(0.5), elasticOverscroll: true, completionAnimation: .bounce) } /// The default action performs a destructive behavior. The cell is removed from the table view in an animated fashion. public static var destructive: SwipeExpansionStyle { return .destructive(automaticallyDelete: true, timing: .with) } /// The default action performs a destructive behavior after the fill animation completes. The cell is removed from the table view in an animated fashion. public static var destructiveAfterFill: SwipeExpansionStyle { return .destructive(automaticallyDelete: true, timing: .after) } /// The default action performs a fill behavior. /// /// - note: The action handle must call `SwipeAction.fulfill(style:)` to resolve the fill expansion. public static var fill: SwipeExpansionStyle { return SwipeExpansionStyle(target: .edgeInset(30), additionalTriggers: [.overscroll(30)], completionAnimation: .fill(.manual(timing: .after))) } /** Returns a `SwipeExpansionStyle` instance for the default action which peforms destructive behavior with the specified options. - parameter automaticallyDelete: Specifies if row/item deletion should be peformed automatically. If `false`, you must call `SwipeAction.fulfill(with style:)` at some point while/after your action handler is invoked to trigger deletion. - parameter timing: The timing which specifies when the action handler will be invoked with respect to the fill animation. - returns: The new `SwipeExpansionStyle` instance. */ public static func destructive(automaticallyDelete: Bool, timing: FillOptions.HandlerInvocationTiming = .with) -> SwipeExpansionStyle { return SwipeExpansionStyle(target: .edgeInset(30), additionalTriggers: [.touchThreshold(0.8)], completionAnimation: .fill(automaticallyDelete ? .automatic(.delete, timing: timing) : .manual(timing: timing))) } /// The relative target expansion threshold. Expansion will occur at the specified value. public let target: Target /// Additional triggers to useful for determining if expansion should occur. public let additionalTriggers: [Trigger] /// Specifies if buttons should expand to fully fill overscroll, or expand at a percentage relative to the overscroll. public let elasticOverscroll: Bool /// Specifies the expansion animation completion style. public let completionAnimation: CompletionAnimation /// Specifies the minimum amount of overscroll required if the configured target is less than the fully exposed action view. public var minimumTargetOverscroll: CGFloat = 20 /// The amount of elasticity applied when dragging past the expansion target. /// /// - note: Default value is 0.2. Valid range is from 0.0 for no movement past the expansion target, to 1.0 for unrestricted movement with dragging. public var targetOverscrollElasticity: CGFloat = 0.2 /** Contructs a new `SwipeExpansionStyle` instance. - parameter target: The relative target expansion threshold. Expansion will occur at the specified value. - parameter additionalTriggers: Additional triggers to useful for determining if expansion should occur. - parameter elasticOverscroll: Specifies if buttons should expand to fully fill overscroll, or expand at a percentage relative to the overscroll. - parameter completionAnimation: Specifies the expansion animation completion style. - returns: The new `SwipeExpansionStyle` instance. */ public init(target: Target, additionalTriggers: [Trigger] = [], elasticOverscroll: Bool = false, completionAnimation: CompletionAnimation = .bounce) { self.target = target self.additionalTriggers = additionalTriggers self.elasticOverscroll = elasticOverscroll self.completionAnimation = completionAnimation } func shouldExpand(view: Swipeable, gesture: UIPanGestureRecognizer, in superview: UIView) -> Bool { guard let actionsView = view.actionsView, let gestureView = gesture.view else { return false } guard abs(gesture.translation(in: gestureView).x) > 5.0 else { return false } guard abs(view.frame.minX) >= actionsView.preferredWidth else { return false } if abs(view.frame.minX) >= target.offset(for: view, in: superview, minimumOverscroll: minimumTargetOverscroll) { return true } for trigger in additionalTriggers { if trigger.isTriggered(view: view, gesture: gesture, in: superview) { return true } } return false } func targetOffset(for view: Swipeable, in superview: UIView) -> CGFloat { return target.offset(for: view, in: superview, minimumOverscroll: minimumTargetOverscroll) } } extension SwipeExpansionStyle { /// Describes the relative target expansion threshold. Expansion will occur at the specified value. public enum Target { /// The target is specified by a percentage. case percentage(CGFloat) /// The target is specified by a edge inset. case edgeInset(CGFloat) func offset(for view: Swipeable, in superview: UIView, minimumOverscroll: CGFloat) -> CGFloat { guard let actionsView = view.actionsView else { return .greatestFiniteMagnitude } let offset: CGFloat = { switch self { case .percentage(let value): return superview.bounds.width * value case .edgeInset(let value): return superview.bounds.width - value } }() return max(actionsView.preferredWidth + minimumOverscroll, offset) } } /// Describes additional triggers to useful for determining if expansion should occur. public enum Trigger { /// The trigger is specified by a touch occuring past the supplied percentage in the superview. case touchThreshold(CGFloat) /// The trigger is specified by the distance in points past the fully exposed action view. case overscroll(CGFloat) func isTriggered(view: Swipeable, gesture: UIPanGestureRecognizer, in superview: UIView) -> Bool { guard let actionsView = view.actionsView else { return false } switch self { case .touchThreshold(let value): let location = gesture.location(in: superview).x let locationRatio = (actionsView.orientation == .left ? location : superview.bounds.width - location) / superview.bounds.width return locationRatio > value case .overscroll(let value): return abs(view.frame.minX) > actionsView.preferredWidth + value } } } /// Describes the expansion animation completion style. public enum CompletionAnimation { /// The expansion will completely fill the item. case fill(FillOptions) /// The expansion will bounce back from the trigger point and hide the action view, resetting the item. case bounce } /// Specifies the options for the fill completion animation. public struct FillOptions { /// Describes when the action handler will be invoked with respect to the fill animation. public enum HandlerInvocationTiming { /// The action handler is invoked with the fill animation. case with /// The action handler is invoked after the fill animation completes. case after } /** Returns a `FillOptions` instance with automatic fulfillemnt. - parameter style: The fulfillment style describing how expansion should be resolved once the action has been fulfilled. - parameter timing: The timing which specifies when the action handler will be invoked with respect to the fill animation. - returns: The new `FillOptions` instance. */ public static func automatic(_ style: ExpansionFulfillmentStyle, timing: HandlerInvocationTiming) -> FillOptions { return FillOptions(autoFulFillmentStyle: style, timing: timing) } /** Returns a `FillOptions` instance with manual fulfillemnt. - parameter timing: The timing which specifies when the action handler will be invoked with respect to the fill animation. - returns: The new `FillOptions` instance. */ public static func manual(timing: HandlerInvocationTiming) -> FillOptions { return FillOptions(autoFulFillmentStyle: nil, timing: timing) } /// The fulfillment style describing how expansion should be resolved once the action has been fulfilled. public let autoFulFillmentStyle: ExpansionFulfillmentStyle? /// The timing which specifies when the action handler will be invoked with respect to the fill animation. public let timing: HandlerInvocationTiming } } extension SwipeExpansionStyle.Target: Equatable { /// :nodoc: public static func ==(lhs: SwipeExpansionStyle.Target, rhs: SwipeExpansionStyle.Target) -> Bool { switch (lhs, rhs) { case (.percentage(let lhs), .percentage(let rhs)): return lhs == rhs case (.edgeInset(let lhs), .edgeInset(let rhs)): return lhs == rhs default: return false } } } extension SwipeExpansionStyle.CompletionAnimation: Equatable { /// :nodoc: public static func ==(lhs: SwipeExpansionStyle.CompletionAnimation, rhs: SwipeExpansionStyle.CompletionAnimation) -> Bool { switch (lhs, rhs) { case (.fill, .fill): return true case (.bounce, .bounce): return true default: return false } } }
46.889362
241
0.650876
48e2f5dea8511c2ce07649fa5f21b4ee3b328413
462
import Domain import Vapor import Fluent import FluentMySQL extension InvitationCode: MySQLType { public static var mysqlDataType: MySQLDataType { return .varchar(32) } public func convertToMySQLData() -> MySQLData { return String(self).convertToMySQLData() } public static func convertFromMySQLData(_ data: MySQLData) throws -> InvitationCode { return try self.init(string: .convertFromMySQLData(data)) } }
21
89
0.709957
76c3ec2a0b108bd2dcecc1758bcccccac74b655b
7,282
// // Extension.swift // PrivateRoom // // Created by JoSoJeong on 2021/07/04. // import Foundation import UIKit extension UIImageView { func circle(){ self.layer.cornerRadius = self.frame.height/2 self.layer.borderWidth = 1 self.layer.borderColor = UIColor.clear.cgColor self.clipsToBounds = true } } extension UIButton { func circle(){ self.layer.cornerRadius = 0.5 * self.bounds.size.width self.clipsToBounds = true } } extension UITextField { func circle(){ self.layer.cornerRadius = 15 self.clipsToBounds = true } func updatePhoneNumber(_ replacementString: String?, _ textString: String?) -> Bool { guard let textCount = textString?.count else {return true} guard let currentString = self.text else {return true} if replacementString == "" { return true } else if textCount == 3 { self.text = currentString + "-" } else if textCount == 8 { self.text = currentString + "-" } else if textCount > 12 || replacementString == " " { return false } return true } } extension UIViewController{ func alertViewController(title: String, message: String, completion: @escaping (String) -> Void){ let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "확인", style: .default, handler: { _ in completion("OK") }) alertVC.addAction(OKAction) self.present(alertVC, animated: true, completion: nil) } func alertWithNoViewController(title: String, message: String, completion: @escaping (String) -> Void){ let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "확인", style: .default, handler: { _ in completion("OK") }) let CANCELAction = UIAlertAction(title: "취소", style: .default, handler: nil) alertVC.addAction(OKAction) alertVC.addAction(CANCELAction) self.present(alertVC, animated: true, completion: nil) } } extension String { func isNumeric() -> Bool { let set = CharacterSet.decimalDigits var string = self string.remove(at: string.index(string.startIndex, offsetBy: 3)) string.remove(at: string.index(string.startIndex, offsetBy: 7)) print(string) for us in string.unicodeScalars where (!set.contains(us)) { return false } return true } func phoneMake() -> String { var string = self string.remove(at: string.index(string.startIndex, offsetBy: 3)) string.remove(at: string.index(string.startIndex, offsetBy: 7)) return string } func isValid() -> Bool { var string = self if(self == ""){ return false } if(string.count != 13){ print("not 11 count") return false } string = string.phoneMake() let start = string.index(string.startIndex, offsetBy: 0) let end = string.index(string.startIndex, offsetBy: 3) let range = start ..< end if(string[range] != "010"){ print("not 010") return false } return true } } extension UIViewController { func showToast(message : String) { let toastLabel = UILabel(frame: CGRect(x: 50, y: self.view.frame.size.height - 100, width: self.view.frame.width - 100, height: 35)) toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6) toastLabel.textColor = UIColor.white toastLabel.font = UIFont(name: message, size: 8) toastLabel.textAlignment = .center; toastLabel.text = message toastLabel.alpha = 1.0 toastLabel.layer.cornerRadius = 10; toastLabel.clipsToBounds = true self.view.addSubview(toastLabel) UIView.animate(withDuration: 4.0, delay: 0.5, options: .curveEaseOut, animations: { toastLabel.alpha = 0.0 }, completion: {(isCompleted) in toastLabel.removeFromSuperview() }) } } extension Date { public var year: Int { return Calendar.current.component(.year, from: self) } public var month: Int { return Calendar.current.component(.month, from: self) } public var day: Int { return Calendar.current.component(.day, from: self) } public var hour: Int { return Calendar.current.component(.hour, from: self) } public var minute: Int { return Calendar.current.component(.minute, from: self) } public var monthName: String { let nameFormatter = DateFormatter() nameFormatter.dateFormat = "MMMM" // format January, February, March, ... return nameFormatter.string(from: self) } } extension UITextView { func circle(){ self.layer.cornerRadius = 15 self.clipsToBounds = true } } extension UIView { class func getAllSubviews<T: UIView>(from parentView: UIView) -> [T] { return parentView.subviews.flatMap { subView -> [T] in var result = getAllSubviews(from: subView) as [T] if let view = subView as? T { result.append(view) } return result } } class func getAllSubviews(from parentView: UIView, types: [UIView.Type]) -> [UIView] { return parentView.subviews.flatMap { subView -> [UIView] in var result = getAllSubviews(from: subView) as [UIView] for type in types { if subView.classForCoder == type { result.append(subView) return result } } return result } } func getAllSubviews<T: UIView>() -> [T] { return UIView.getAllSubviews(from: self) as [T] } func get<T: UIView>(all type: T.Type) -> [T] { return UIView.getAllSubviews(from: self) as [T] } func get(all type: UIView.Type) -> [UIView] { return UIView.getAllSubviews(from: self) } } extension UIPageViewController { var scrollView: UIScrollView? { return view.subviews.first { $0 is UIScrollView } as? UIScrollView } } extension UIImage { enum JPEGQuality: CGFloat { case lowest = 0 case low = 0.25 case medium = 0.5 case high = 0.75 case highest = 1 } func jpeg(_ jpegQuality: JPEGQuality) -> Data? { return jpegData(compressionQuality: jpegQuality.rawValue) } } //var version: String? { // guard let dictionary = Bundle.main.infoDictionary, let version = dictionary["CFBundleShortVersionString"] as? String, let build = dictionary["CFBundleVersion"] as? String else {return nil} // let versionAndBuild: String = "vserion: \(version), build: \(build)" // print(versionAndBuild) // return version //}
29.967078
194
0.583768
71b7783ac230c072fe08dcf7b5d1dfeaa67c344a
3,563
// // ESTimeAgoFormatParser.swift // SwiftyChrono // // Created by Jerry Chen on 2/6/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation private let PATTERN = "(\\W|^)hace\\s*([0-9]+|medi[oa]|una?)\\s*(minutos?|horas?|semanas?|d[ií]as?|mes(es)?|años?)(?=(?:\\W|$))" public class ESTimeAgoFormatParser: Parser { override var pattern: String { return PATTERN } override var language: Language { return .spanish } override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? { let idx = match.range(at: 0).location if idx > 0 && NSRegularExpression.isMatch(forPattern: "\\w", in: text.substring(from: idx - 1, to: idx)) { return nil } let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match) var result = ParsedResult(ref: ref, index: index, text: matchText) let number: Int let numberText = match.string(from: text, atRangeIndex: 2).lowercased() let parsedNumber = Int(numberText) if parsedNumber == nil { if NSRegularExpression.isMatch(forPattern: "medi", in: numberText) { number = HALF } else { number = 1 } } else { number = parsedNumber! } var date = ref let matchText3 = match.string(from: text, atRangeIndex: 3) func ymdResult() -> ParsedResult { result.start.imply(.day, to: date.day) result.start.imply(.month, to: date.month) result.start.imply(.year, to: date.year) result.start.assign(.hour, value: date.hour) result.start.assign(.minute, value: date.minute) result.tags[.esTimeAgoFormatParser] = true return result } if NSRegularExpression.isMatch(forPattern: "hora", in: matchText3) { date = number != HALF ? date.added(-number, .hour) : date.added(-30, .minute) return ymdResult() } else if NSRegularExpression.isMatch(forPattern: "minuto", in: matchText3) { date = number != HALF ? date.added(-number, .minute) : date.added(-30, .second) return ymdResult() } if NSRegularExpression.isMatch(forPattern: "semana", in: matchText3) { date = number != HALF ? date.added(-number * 7, .day) : date.added(-3, .day).added(-12, .hour) result.start.imply(.day, to: date.day) result.start.imply(.month, to: date.month) result.start.imply(.year, to: date.year) result.start.imply(.weekday, to: date.weekday) result.tags[.esTimeAgoFormatParser] = true return result } else if NSRegularExpression.isMatch(forPattern: "d[ií]a", in: matchText3) { date = number != HALF ? date.added(-number, .day) : date.added(-12, .hour) } else if NSRegularExpression.isMatch(forPattern: "mes", in: matchText3) { date = number != HALF ? date.added(-number, .month) : date.added(-(date.numberOf(.day, inA: .month) ?? 30)/2, .day) } else if NSRegularExpression.isMatch(forPattern: "año", in: matchText3) { date = number != HALF ? date.added(-number, .year) : date.added(-6, .month) } result.start.assign(.day, value: date.day) result.start.assign(.month, value: date.month) result.start.assign(.year, value: date.year) result.tags[.esTimeAgoFormatParser] = true return result } }
42.927711
129
0.59725
5636f5376947166576575cc30452638df102e669
2,374
// // GaiaVotesController.swift // Cosmos Client // // Created by kytzu on 28/03/2019. // Copyright © 2019 Calin Chitu. All rights reserved. // import UIKit import CosmosRestApi //class GaiaVotesController: UIViewController { class GaiaVotesController: UIViewController, ToastAlertViewPresentable, GaiaKeysManagementCapable { var toast: ToastAlertView? @IBOutlet weak var loadingView: CustomLoadingView! @IBOutlet weak var toastHolderUnderView: UIView! @IBOutlet weak var toastHolderTopConstraint: NSLayoutConstraint! @IBOutlet weak var topNavBarView: UIView! var dataSource: [ProposalVote] = [] override func viewDidLoad() { super.viewDidLoad() toast = createToastAlert(creatorView: view, holderUnderView: toastHolderUnderView, holderTopDistanceConstraint: toastHolderTopConstraint, coveringView: topNavBarView) let _ = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: OperationQueue.main) { [weak self] note in AppContext.shared.node?.getStatus { if AppContext.shared.node?.state == .unknown { self?.performSegue(withIdentifier: "UnwindToNodes", sender: self) } } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @IBAction func closeAction(_ sender: Any) { self.dismiss(animated: true) } } extension GaiaVotesController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "GaiaVoteCellID", for: indexPath) as? GaiaVoteCell let delegation = dataSource[indexPath.item] cell?.leftLabel.text = delegation.option cell?.leftSubLabel.text = delegation.voter return cell ?? UITableViewCell() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } } class GaiaVoteCell: UITableViewCell { @IBOutlet weak var leftLabel: UILabel! @IBOutlet weak var leftSubLabel: UILabel! }
32.520548
174
0.690396
3306ace1aa460e2bd4ff109b3885e35e2a052510
200
import Combine extension Publisher { func extractUnderlyingError() -> Publishers.MapError<Self, Failure> { mapError { ($0.underlyingError as? Failure) ?? $0 } } }
20
73
0.6
9161cf54b478f5d97ebacad7bbc6e22f3adc4f9a
664
// // FeedImage+CoreDataProperties.swift // FeedStoreChallenge // // Created by Oliver Jordy Pérez Escamilla on 27/01/21. // Copyright © 2021 Essential Developer. All rights reserved. // // import Foundation import CoreData extension FeedImage { @nonobjc public class func fetchRequest() -> NSFetchRequest<FeedImage> { return NSFetchRequest<FeedImage>(entityName: "FeedImage") } @NSManaged public var id: UUID? @NSManaged public var imageDescription: String? @NSManaged public var location: String? @NSManaged public var url: URL? @NSManaged public var feedCache: FeedCache? } extension FeedImage : Identifiable { }
21.419355
76
0.721386
1a7790f5eb9a9db02d0d9bb737cb94d8f707f738
1,610
import Foundation /// This is a reverse-engineered, undocumented API that's used for /// the 4chan Mobile API. /// Not sure how stable it is... public struct FourChanSearchResults: Codable { public let body: FourChanSearchResultsBody? } public struct FourChanSearchResultsBody: Codable { public let board: String? public let nhits: Int? public let offset: String? // Encoding a decimal integer public let query: String? public let threads: [FourChanSearchResultsThread]? } public struct FourChanSearchResultsThread: Codable, Identifiable { public let board: String? public let posts: [Post]? public let thread: String // "tNNNN" threadID public var id: String { return thread } } func search( query: String, offset: Int? = nil, length: Int? = nil, board: String? ) -> URL? { var params = ["q": query] if let offset = offset { params["o"] = "\(offset)" } if let length = length { params["l"] = "\(length)" } if let board = board { params["b"] = board } return FourChanAPIEndpoint.search.url(params: params) } extension FourChanSearchResults { public func filter(_ isIncluded: (FourChanSearchResultsThread) -> Bool) -> FourChanSearchResults { FourChanSearchResults( body: self.body?.filter(isIncluded)) } } extension FourChanSearchResultsBody { public func filter(_ isIncluded: (FourChanSearchResultsThread) -> Bool) -> FourChanSearchResultsBody { FourChanSearchResultsBody( board: board, nhits: nhits, offset: offset, query: query, threads: threads?.filter(isIncluded) ) } }
24.029851
100
0.688199
1eb334bf65683fc4e00868875641598168cfc9fd
3,301
// // CGDetailVC.swift // CgExercise // // Created by Test User 1 on 11/04/18. // Copyright © 2018 Capgemini. All rights reserved. // import UIKit class CGDetailVC: UIViewController { @IBOutlet weak var mStackView: UIStackView! @IBOutlet weak var mImageView: UIImageView! @IBOutlet weak var mDescriptionLabel: UILabel! var selectedIndex = 0 var model: FactModel? override func viewDidLoad() { super.viewDidLoad() self.title = "Beavers" addSubviews() setData() } func addSubviews() { let subviews = (0..<2).map { (_) -> CustomView in return UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomView } subviews[0].backgroundColor = UIColor.clear subviews[0].label.isHidden = true subviews[1].backgroundColor = UIColor.clear subviews[1].imageView.isHidden = true subviews.forEach { (view) in mStackView.addArrangedSubview(view) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: {[weak self] (_) in let orientation:UIInterfaceOrientation = UIApplication.shared.statusBarOrientation; if orientation == UIInterfaceOrientation.landscapeLeft || orientation == UIInterfaceOrientation.landscapeRight { // orientation is landscape self?.mStackView.axis = .horizontal if let view = self?.mStackView.subviews[0] as? CustomView { view.width = 3 } if let view = self?.mStackView.subviews[1] as? CustomView { view.width = 7 } } else { // orientation is portrait self?.mStackView.axis = .vertical if let view = self?.mStackView.subviews[0] as? CustomView { view.width = 3 } if let view = self?.mStackView.subviews[1] as? CustomView { view.width = 7 } } }, completion: nil) super.viewWillTransition(to: size, with: coordinator) } func setData() { if let factModel = model { if let name = factModel.title { self.title = name }else { self.title = "Detail" } if let imageUrlString = factModel.imageHref { ImageLoader.sharedInstance.obtainImageWithPath(imagePath: imageUrlString) { (image,fromCache) in if let view = self.mStackView.subviews[0] as? CustomView { view.imageView.image = image } if let textStr = factModel.descrip { if let view = self.mStackView.subviews[1] as? CustomView { view.label.text = textStr } } } } } } }
32.683168
124
0.517419
e5d766a73859553cfe9db433b45143972f0a74b4
287
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let end = 0 protocol A : A.e : A"\() { } protocol A { func b<T where T : e) { protocol c : A"\(e == 0 typealias e : e
26.090909
87
0.679443
4bf23c302dffa6a3d9c265a51be12aafda098268
57,624
// // HXPHPickerViewController.swift // 照片选择器-Swift // // Created by Silence on 2019/6/29. // Copyright © 2019年 Silence. All rights reserved. // import UIKit import MobileCoreServices import AVFoundation class HXPHPickerViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, HXPHPickerViewCellDelegate, HXPHPickerBottomViewDelegate, HXPHPreviewViewControllerDelegate, HXAlbumViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { init() { super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } var config: HXPHPhotoListConfiguration! var assetCollection: HXPHAssetCollection! var assets: [HXPHAsset] = [] lazy var collectionViewLayout: UICollectionViewFlowLayout = { let collectionViewLayout = UICollectionViewFlowLayout.init() let space = config.spacing collectionViewLayout.minimumLineSpacing = space collectionViewLayout.minimumInteritemSpacing = space return collectionViewLayout }() lazy var collectionView: UICollectionView = { let collectionView = UICollectionView.init(frame: view.bounds, collectionViewLayout: collectionViewLayout) collectionView.dataSource = self collectionView.delegate = self if let customSingleCellClass = config.cell.customSingleCellClass { collectionView.register(customSingleCellClass, forCellWithReuseIdentifier: NSStringFromClass(HXPHPickerViewCell.classForCoder())) }else { collectionView.register(HXPHPickerViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(HXPHPickerViewCell.classForCoder())) } if let customMultipleCellClass = config.cell.customMultipleCellClass { collectionView.register(customMultipleCellClass, forCellWithReuseIdentifier: NSStringFromClass(HXPHPickerMultiSelectViewCell.classForCoder())) }else { collectionView.register(HXPHPickerMultiSelectViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(HXPHPickerMultiSelectViewCell.classForCoder())) } if config.allowAddCamera { collectionView.register(HXPHPickerCamerViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(HXPHPickerCamerViewCell.classForCoder())) } if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } else { // Fallback on earlier versions self.automaticallyAdjustsScrollViewInsets = false } return collectionView }() var cameraCell: HXPHPickerCamerViewCell { get { var indexPath: IndexPath if !hx_pickerController!.config.reverseOrder { indexPath = IndexPath(item: assets.count, section: 0) }else { indexPath = IndexPath(item: 0, section: 0) } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(HXPHPickerCamerViewCell.classForCoder()), for: indexPath) as! HXPHPickerCamerViewCell cell.config = config.cameraCell return cell } } private lazy var emptyView: HXPHEmptyView = { let emptyView = HXPHEmptyView.init(frame: CGRect(x: 0, y: 0, width: view.hx_width, height: 0)) emptyView.config = config.emptyView emptyView.layoutSubviews() return emptyView }() var canAddCamera: Bool = false var orientationDidChange : Bool = false var beforeOrientationIndexPath: IndexPath? var showLoading : Bool = false var isMultipleSelect : Bool = false var videoLoadSingleCell = false var needOffset: Bool { get { return hx_pickerController != nil && hx_pickerController!.config.reverseOrder && config.allowAddCamera && canAddCamera } } lazy var titleLabel: UILabel = { let titleLabel = UILabel.init() titleLabel.font = UIFont.boldSystemFont(ofSize: 18) titleLabel.textAlignment = .center return titleLabel }() lazy var titleView: HXAlbumTitleView = { let titleView = HXAlbumTitleView.init(config: config.titleViewConfig) titleView.addTarget(self, action: #selector(didTitleViewClick(control:)), for: .touchUpInside) return titleView }() @objc func didTitleViewClick(control: HXAlbumTitleView) { control.isSelected = !control.isSelected if control.isSelected { // 展开 if albumView.assetCollectionsArray.isEmpty { // HXPHProgressHUD.showLoadingHUD(addedTo: view, animated: true) // HXPHProgressHUD.hideHUD(forView: weakSelf?.navigationController?.view, animated: true) control.isSelected = false return } openAlbumView() }else { // 收起 closeAlbumView() } } lazy var albumBackgroudView: UIView = { let albumBackgroudView = UIView.init() albumBackgroudView.isHidden = true albumBackgroudView.backgroundColor = UIColor.black.withAlphaComponent(0.6) albumBackgroudView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(didAlbumBackgroudViewClick))) return albumBackgroudView }() @objc func didAlbumBackgroudViewClick() { titleView.isSelected = false closeAlbumView() } lazy var albumView: HXAlbumView = { let albumView = HXAlbumView.init(config: hx_pickerController!.config.albumList) albumView.delegate = self return albumView }() func openAlbumView() { albumBackgroudView.alpha = 0 albumBackgroudView.isHidden = false albumView.scrollToMiddle() UIView.animate(withDuration: 0.25) { self.albumBackgroudView.alpha = 1 self.configAlbumViewFrame() self.titleView.arrowView.transform = CGAffineTransform.init(rotationAngle: .pi) } } func closeAlbumView() { UIView.animate(withDuration: 0.25) { self.albumBackgroudView.alpha = 0 self.configAlbumViewFrame() self.titleView.arrowView.transform = CGAffineTransform.init(rotationAngle: 2 * .pi) } completion: { (isFinish) in if isFinish { self.albumBackgroudView.isHidden = true } } } func configAlbumViewFrame() { self.albumView.hx_size = CGSize(width: view.hx_width, height: getAlbumViewHeight()) if titleView.isSelected { if self.navigationController?.modalPresentationStyle == UIModalPresentationStyle.fullScreen && UIDevice.current.hx_isPortrait { self.albumView.hx_y = UIDevice.current.hx_navigationBarHeight }else { self.albumView.hx_y = self.navigationController?.navigationBar.hx_height ?? 0 } }else { self.albumView.hx_y = -self.albumView.hx_height } } func getAlbumViewHeight() -> CGFloat { var albumViewHeight = CGFloat(albumView.assetCollectionsArray.count) * albumView.config.cellHeight if HXPHAssetManager.authorizationStatusIsLimited() && hx_pickerController!.config.allowLoadPhotoLibrary { albumViewHeight += 40 } if albumViewHeight > view.hx_height * 0.75 { albumViewHeight = view.hx_height * 0.75 } return albumViewHeight } lazy var bottomView : HXPHPickerBottomView = { let bottomView = HXPHPickerBottomView.init(config: config.bottomView, allowLoadPhotoLibrary: allowLoadPhotoLibrary) bottomView.hx_delegate = self bottomView.boxControl.isSelected = hx_pickerController!.isOriginal return bottomView }() var allowLoadPhotoLibrary: Bool = true override func viewDidLoad() { super.viewDidLoad() allowLoadPhotoLibrary = hx_pickerController?.config.allowLoadPhotoLibrary ?? true if HXPHAssetManager.authorizationStatus() == .notDetermined { canAddCamera = true } configData() initView() configColor() fetchData() guard #available(iOS 13.0, *) else { NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationChanged(notify:)), name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) return } } @objc func deviceOrientationChanged(notify: Notification) { beforeOrientationIndexPath = collectionView.indexPathsForVisibleItems.first orientationDidChange = true } func configData() { isMultipleSelect = hx_pickerController!.config.selectMode == .multiple if !hx_pickerController!.config.allowSelectedTogether && hx_pickerController!.config.maximumSelectedVideoCount == 1 && hx_pickerController!.config.selectType == .any && isMultipleSelect { videoLoadSingleCell = true } config = hx_pickerController!.config.photoList updateTitle() } func configColor() { let isDark = HXPHManager.shared.isDark view.backgroundColor = isDark ? config.backgroundDarkColor : config.backgroundColor collectionView.backgroundColor = isDark ? config.backgroundDarkColor : config.backgroundColor let titleColor = isDark ? hx_pickerController?.config.navigationTitleDarkColor : hx_pickerController?.config.navigationTitleColor if hx_pickerController!.config.albumShowMode == .popup { titleView.titleColor = titleColor }else { titleLabel.textColor = titleColor } } @objc func didCancelItemClick() { hx_pickerController?.cancelCallback() } func initView() { extendedLayoutIncludesOpaqueBars = true edgesForExtendedLayout = .all view.addSubview(collectionView) if isMultipleSelect { view.addSubview(bottomView) bottomView.updateFinishButtonTitle() } if hx_pickerController!.config.albumShowMode == .popup { var cancelItem: UIBarButtonItem if config.cancelType == .text { cancelItem = UIBarButtonItem.init(title: "取消".hx_localized, style: .done, target: self, action: #selector(didCancelItemClick)) }else { cancelItem = UIBarButtonItem.init(image: UIImage.hx_named(named: HXPHManager.shared.isDark ? config.cancelDarkImageName : config.cancelImageName), style: .done, target: self, action: #selector(didCancelItemClick)) } if config.cancelPosition == .left { navigationItem.leftBarButtonItem = cancelItem }else { navigationItem.rightBarButtonItem = cancelItem } view.addSubview(albumBackgroudView) view.addSubview(albumView) }else { navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "取消".hx_localized, style: .done, target: self, action: #selector(didCancelItemClick)) } } func updateTitle() { if hx_pickerController!.config.albumShowMode == .popup { titleView.title = assetCollection?.albumName }else { titleLabel.text = assetCollection?.albumName // title = assetCollection.albumName } } func fetchData() { if hx_pickerController!.config.albumShowMode == .popup { fetchAssetCollections() title = "" navigationItem.titleView = titleView if hx_pickerController?.cameraAssetCollection != nil { assetCollection = hx_pickerController?.cameraAssetCollection assetCollection.isSelected = true titleView.title = assetCollection.albumName fetchPhotoAssets() }else { weak var weakSelf = self hx_pickerController?.fetchCameraAssetCollectionCompletion = { (assetCollection) in var cameraAssetCollection = assetCollection if cameraAssetCollection == nil { cameraAssetCollection = HXPHAssetCollection.init(albumName: self.hx_pickerController!.config.albumList.emptyAlbumName.hx_localized, coverImage: self.hx_pickerController!.config.albumList.emptyCoverImageName.hx_image) } weakSelf?.assetCollection = cameraAssetCollection weakSelf?.assetCollection.isSelected = true weakSelf?.titleView.title = weakSelf?.assetCollection.albumName weakSelf?.fetchPhotoAssets() } } }else { title = "" navigationItem.titleView = titleLabel if showLoading { _ = HXPHProgressHUD.showLoadingHUD(addedTo: view, afterDelay: 0.15, animated: true) } fetchPhotoAssets() } } func fetchAssetCollections() { if !hx_pickerController!.assetCollectionsArray.isEmpty { albumView.assetCollectionsArray = hx_pickerController!.assetCollectionsArray albumView.currentSelectedAssetCollection = assetCollection configAlbumViewFrame() } fetchAssetCollectionsClosure() if !hx_pickerController!.config.allowLoadPhotoLibrary { hx_pickerController?.fetchAssetCollections() } } private func fetchAssetCollectionsClosure() { weak var weakSelf = self hx_pickerController?.fetchAssetCollectionsCompletion = { (assetCollectionsArray) in weakSelf?.albumView.assetCollectionsArray = assetCollectionsArray weakSelf?.albumView.currentSelectedAssetCollection = weakSelf?.assetCollection weakSelf?.configAlbumViewFrame() } } func fetchPhotoAssets() { weak var weakSelf = self hx_pickerController!.fetchPhotoAssets(assetCollection: assetCollection) { (photoAssets, photoAsset) in weakSelf?.canAddCamera = true weakSelf?.assets = photoAssets weakSelf?.setupEmptyView() // if weakSelf != nil { // UIView.transition(with: weakSelf!.collectionView, duration: 0.05, options: .transitionCrossDissolve) { weakSelf?.collectionView.reloadData() // } completion: { (isFinished) in } // } weakSelf?.scrollToAppropriatePlace(photoAsset: photoAsset) if weakSelf != nil && weakSelf!.showLoading { HXPHProgressHUD.hideHUD(forView: weakSelf?.view, animated: true) weakSelf?.showLoading = false }else { HXPHProgressHUD.hideHUD(forView: weakSelf?.navigationController?.view, animated: false) } } } func setupEmptyView() { if assets.isEmpty { collectionView.addSubview(emptyView) }else { emptyView.removeFromSuperview() } } func scrollToCenter(for photoAsset: HXPHAsset?) { if assets.isEmpty || photoAsset == nil { return } var item = assets.firstIndex(of: photoAsset!) if item != nil { if needOffset { item! += 1 } collectionView.scrollToItem(at: IndexPath(item: item!, section: 0), at: .centeredVertically, animated: false) } } func scrollCellToVisibleArea(_ cell: HXPHPickerViewCell) { if assets.isEmpty { return } let rect = cell.imageView.convert(cell.imageView.bounds, to: view) if rect.minY - collectionView.contentInset.top < 0 { if let indexPath = collectionView.indexPath(for: cell) { collectionView.scrollToItem(at: indexPath, at: .top, animated: false) } }else if rect.maxY > view.hx_height - collectionView.contentInset.bottom { if let indexPath = collectionView.indexPath(for: cell) { collectionView.scrollToItem(at: indexPath, at: .bottom, animated: false) } } } func scrollToAppropriatePlace(photoAsset: HXPHAsset?) { if assets.isEmpty { return } var item = !hx_pickerController!.config.reverseOrder ? assets.count - 1 : 0 if photoAsset != nil { item = assets.firstIndex(of: photoAsset!) ?? item if needOffset { item += 1 } } collectionView.scrollToItem(at: IndexPath(item: item, section: 0), at: .centeredVertically, animated: false) } func getCell(for item: Int) -> HXPHPickerViewCell? { if assets.isEmpty { return nil } let cell = collectionView.cellForItem(at: IndexPath.init(item: item, section: 0)) as? HXPHPickerViewCell return cell } func getCell(for photoAsset: HXPHAsset) -> HXPHPickerViewCell? { if assets.isEmpty { return nil } var item = assets.firstIndex(of: photoAsset) if item == nil { return nil } if needOffset { item! += 1 } return getCell(for: item!) } func reloadCell(for photoAsset: HXPHAsset) { var item = assets.firstIndex(of: photoAsset) if item != nil { if needOffset { item! += 1 } collectionView.reloadItems(at: [IndexPath.init(item: item!, section: 0)]) } } func getPhotoAsset(for index: Int) -> HXPHAsset { var photoAsset: HXPHAsset if needOffset { photoAsset = assets[index - 1] }else { photoAsset = assets[index] } return photoAsset } func addedPhotoAsset(for photoAsset: HXPHAsset) { if hx_pickerController!.config.reverseOrder { assets.insert(photoAsset, at: 0) collectionView.insertItems(at: [IndexPath(item: needOffset ? 1 : 0, section: 0)]) }else { assets.append(photoAsset) collectionView.insertItems(at: [IndexPath(item: needOffset ? assets.count : assets.count - 1, section: 0)]) } } func changedAssetCollection(collection: HXPHAssetCollection?) { _ = HXPHProgressHUD.showLoadingHUD(addedTo: navigationController?.view, animated: true) if collection == nil { updateTitle() fetchPhotoAssets() reloadAlbumData() return } if hx_pickerController!.config.albumShowMode == .popup { assetCollection.isSelected = false collection?.isSelected = true } assetCollection = collection updateTitle() fetchPhotoAssets() reloadAlbumData() } func reloadAlbumData() { if hx_pickerController!.config.albumShowMode == .popup { albumView.tableView.reloadData() albumView.updatePrompt() } } func updateBottomPromptView() { if isMultipleSelect { bottomView.updatePromptView() } } // MARK: UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return config.allowAddCamera && canAddCamera && hx_pickerController != nil ? assets.count + 1 : assets.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if config.allowAddCamera && canAddCamera && hx_pickerController != nil { if !hx_pickerController!.config.reverseOrder { if indexPath.item == assets.count { return self.cameraCell } }else { if indexPath.item == 0 { return self.cameraCell } } } let cell: HXPHPickerViewCell let photoAsset = getPhotoAsset(for: indexPath.item) if hx_pickerController?.config.selectMode == .single || (photoAsset.mediaType == .video && videoLoadSingleCell) { cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(HXPHPickerViewCell.classForCoder()), for: indexPath) as! HXPHPickerViewCell }else { let multiSelectCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(HXPHPickerMultiSelectViewCell.classForCoder()), for: indexPath) as! HXPHPickerMultiSelectViewCell multiSelectCell.delegate = self cell = multiSelectCell } cell.config = config.cell cell.photoAsset = photoAsset return cell } // MARK: UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let pickerController = hx_pickerController, cell is HXPHPickerViewCell { let myCell: HXPHPickerViewCell = cell as! HXPHPickerViewCell let photoAsset = getPhotoAsset(for: indexPath.item) if !photoAsset.isSelected && config.cell.showDisableMask { myCell.canSelect = pickerController.canSelectAsset(for: photoAsset, showHUD: false) }else { myCell.canSelect = true } } } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let myCell: HXPHPickerViewCell? = cell as? HXPHPickerViewCell myCell?.cancelRequest() } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if navigationController?.topViewController != self { return } collectionView.deselectItem(at: indexPath, animated: false) let cell = collectionView.cellForItem(at: indexPath) if cell == nil { return } if cell is HXPHPickerCamerViewCell { if !UIImagePickerController.isSourceTypeAvailable(.camera) { HXPHProgressHUD.showWarningHUD(addedTo: self.navigationController?.view, text: "相机不可用!".hx_localized, animated: true, delay: 1.5) return } HXPHAssetManager.requestCameraAccess { (granted) in if granted { self.presentCameraViewController() }else { HXPHTools.showNotCameraAuthorizedAlert(viewController: self) } } }else if cell is HXPHPickerViewCell { let myCell = cell as! HXPHPickerViewCell if !myCell.canSelect { return } if let pickerController = hx_pickerController { if !pickerController.shouldClickCell(photoAsset: myCell.photoAsset!, index: indexPath.item) { return } } pushPreviewViewController(previewAssets: assets, currentPreviewIndex: needOffset ? indexPath.item - 1 : indexPath.item) } } func pushPreviewViewController(previewAssets: [HXPHAsset], currentPreviewIndex: Int) { let vc = HXPHPreviewViewController.init() vc.previewAssets = previewAssets vc.currentPreviewIndex = currentPreviewIndex vc.delegate = self navigationController?.delegate = vc navigationController?.pushViewController(vc, animated: true) } func presentCameraViewController() { if let pickerController = hx_pickerController { if !pickerController.shouldPresentCamera() { return } } let imagePickerController = HXPHImagePickerController.init() imagePickerController.sourceType = .camera imagePickerController.delegate = self imagePickerController.videoMaximumDuration = config.camera.videoMaximumDuration imagePickerController.videoQuality = config.camera.videoQuality imagePickerController.allowsEditing = config.camera.allowsEditing imagePickerController.cameraDevice = config.camera.cameraDevice var mediaTypes: [String] if !config.camera.mediaTypes.isEmpty { mediaTypes = config.camera.mediaTypes }else { switch hx_pickerController!.config.selectType { case .photo: mediaTypes = [kUTTypeImage as String] break case .video: mediaTypes = [kUTTypeMovie as String] break default: mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String] } } imagePickerController.mediaTypes = mediaTypes present(imagePickerController, animated: true, completion: nil) } // MARK: UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { _ = HXPHProgressHUD.showLoadingHUD(addedTo: self.navigationController?.view, animated: true) picker.dismiss(animated: true, completion: nil) DispatchQueue.global().async { let mediaType = info[.mediaType] as! String var photoAsset: HXPHAsset if mediaType == kUTTypeImage as String { var image: UIImage? = (info[.editedImage] ?? info[.originalImage]) as? UIImage image = image?.hx_scaleSuitableSize() if let image = image, self.config.camera.saveSystemAlbum { self.saveSystemAlbum(for: image, mediaType: .photo) return } photoAsset = HXPHAsset.init(image: image, localIdentifier: String(Date.init().timeIntervalSince1970)) }else { let startTime = info[UIImagePickerController.InfoKey.init(rawValue: "_UIImagePickerControllerVideoEditingStart")] as? TimeInterval let endTime = info[UIImagePickerController.InfoKey.init(rawValue: "_UIImagePickerControllerVideoEditingEnd")] as? TimeInterval let videoURL: URL? = info[.mediaURL] as? URL if startTime != nil && endTime != nil && videoURL != nil { let avAsset = AVAsset.init(url: videoURL!) HXPHTools.exportEditVideo(for: avAsset, startTime: startTime!, endTime: endTime!, presentName: self.config.camera.videoEditExportQuality) { (url, error) in if let url = url, error == nil { if self.config.camera.saveSystemAlbum { self.saveSystemAlbum(for: url, mediaType: .video) return } let phAsset: HXPHAsset = HXPHAsset.init(videoURL: url, localIdentifier: String(Date.init().timeIntervalSince1970)) self.addedCameraPhotoAsset(phAsset) }else { HXPHProgressHUD.hideHUD(forView: self.navigationController?.view, animated: false) HXPHProgressHUD.showWarningHUD(addedTo: self.navigationController?.view, text: "视频导出失败".hx_localized, animated: true, delay: 1.5) } } return }else { if let videoURL = videoURL, self.config.camera.saveSystemAlbum { self.saveSystemAlbum(for: videoURL, mediaType: .video) return } photoAsset = HXPHAsset.init(videoURL: videoURL, localIdentifier: String(Date.init().timeIntervalSince1970)) } } self.addedCameraPhotoAsset(photoAsset) } } func saveSystemAlbum(for asset: Any, mediaType: HXPHPicker.Asset.MediaType) { HXPHAssetManager.saveSystemAlbum(forAsset: asset, mediaType: mediaType, customAlbumName: config.camera.customAlbumName, creationDate: nil, location: nil) { (phAsset) in if let phAsset = phAsset { self.addedCameraPhotoAsset(HXPHAsset.init(asset: phAsset)) }else { DispatchQueue.main.async { HXPHProgressHUD.hideHUD(forView: self.navigationController?.view, animated: true) HXPHProgressHUD.showWarningHUD(addedTo: self.navigationController?.view, text: "保存失败", animated: true, delay: 1.5) } } } } func addedCameraPhotoAsset(_ photoAsset: HXPHAsset) { DispatchQueue.main.async { HXPHProgressHUD.hideHUD(forView: self.navigationController?.view, animated: true) if self.config.camera.takePictureCompletionToSelected { if self.hx_pickerController!.addedPhotoAsset(photoAsset: photoAsset) { self.updateCellSelectedTitle() } } self.hx_pickerController?.updateAlbums(coverImage: photoAsset.originalImage, count: 1) if photoAsset.mediaSubType == .localImage || photoAsset.mediaSubType == .localVideo { self.hx_pickerController?.addedLocalCameraAsset(photoAsset: photoAsset) } if self.hx_pickerController!.config.albumShowMode == .popup { self.albumView.tableView.reloadData() } self.addedPhotoAsset(for: photoAsset) self.bottomView.updateFinishButtonTitle() self.setupEmptyView() } } // MARK: HXAlbumViewDelegate func albumView(_ albumView: HXAlbumView, didSelectRowAt assetCollection: HXPHAssetCollection) { didAlbumBackgroudViewClick() if self.assetCollection == assetCollection { return } titleView.title = assetCollection.albumName assetCollection.isSelected = true self.assetCollection.isSelected = false self.assetCollection = assetCollection _ = HXPHProgressHUD.showLoadingHUD(addedTo: navigationController?.view, animated: true) fetchPhotoAssets() } // MARK: HXPHPickerViewCellDelegate func cell(didSelectControl cell: HXPHPickerMultiSelectViewCell, isSelected: Bool) { if isSelected { // 取消选中 _ = hx_pickerController?.removePhotoAsset(photoAsset: cell.photoAsset!) cell.updateSelectedState(isSelected: false, animated: true) updateCellSelectedTitle() }else { // 选中 if hx_pickerController!.addedPhotoAsset(photoAsset: cell.photoAsset!) { cell.updateSelectedState(isSelected: true, animated: true) updateCellSelectedTitle() } } bottomView.updateFinishButtonTitle() } func updateCellSelectedTitle() { for visibleCell in collectionView.visibleCells { if visibleCell is HXPHPickerViewCell { let cell = visibleCell as! HXPHPickerViewCell if !cell.photoAsset!.isSelected && config.cell.showDisableMask { cell.canSelect = hx_pickerController!.canSelectAsset(for: cell.photoAsset!, showHUD: false) } if visibleCell is HXPHPickerMultiSelectViewCell { let cell = visibleCell as! HXPHPickerMultiSelectViewCell if cell.photoAsset!.isSelected { if Int(cell.selectControl.text) != (cell.photoAsset!.selectIndex + 1) || !cell.selectControl.isSelected { cell.updateSelectedState(isSelected: true, animated: false) } }else if cell.selectControl.isSelected { cell.updateSelectedState(isSelected: false, animated: false) } } } } } // MARK: HXPHPickerBottomViewDelegate func bottomView(didPreviewButtonClick view: HXPHPickerBottomView) { pushPreviewViewController(previewAssets: hx_pickerController!.selectedAssetArray, currentPreviewIndex: 0) } func bottomView(didFinishButtonClick view: HXPHPickerBottomView) { hx_pickerController?.finishCallback() } func bottomView(didOriginalButtonClick view: HXPHPickerBottomView, with isOriginal: Bool) { hx_pickerController?.originalButtonCallback() } // MARK: HXPHPreviewViewControllerDelegate func previewViewController(_ previewController: HXPHPreviewViewController, didOriginalButton isOriginal: Bool) { if isMultipleSelect { bottomView.boxControl.isSelected = isOriginal bottomView.requestAssetBytes() } } func previewViewController(_ previewController: HXPHPreviewViewController, didSelectBox photoAsset: HXPHAsset, isSelected: Bool) { updateCellSelectedTitle() bottomView.updateFinishButtonTitle() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let margin: CGFloat = UIDevice.current.hx_leftMargin collectionView.frame = CGRect(x: margin, y: 0, width: view.hx_width - 2 * margin, height: view.hx_height) var collectionTop: CGFloat if navigationController?.modalPresentationStyle == .fullScreen && UIDevice.current.hx_isPortrait { collectionTop = UIDevice.current.hx_navigationBarHeight }else { collectionTop = navigationController!.navigationBar.hx_height } if let pickerController = hx_pickerController { if pickerController.config.albumShowMode == .popup { albumBackgroudView.frame = view.bounds configAlbumViewFrame() }else { var titleWidth = titleLabel.text?.hx_stringWidth(ofFont: titleLabel.font, maxHeight: 30) ?? 0 if titleWidth > view.hx_width * 0.6 { titleWidth = view.hx_width * 0.6 } titleLabel.hx_size = CGSize(width: titleWidth, height: 30) } } if isMultipleSelect { let promptHeight: CGFloat = (HXPHAssetManager.authorizationStatusIsLimited() && config.bottomView.showPrompt && allowLoadPhotoLibrary) ? 70 : 0 let bottomHeight: CGFloat = 50 + UIDevice.current.hx_bottomMargin + promptHeight bottomView.frame = CGRect(x: 0, y: view.hx_height - bottomHeight, width: view.hx_width, height: bottomHeight) collectionView.contentInset = UIEdgeInsets(top: collectionTop, left: 0, bottom: bottomView.hx_height + 0.5, right: 0) collectionView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: bottomHeight - UIDevice.current.hx_bottomMargin, right: 0) }else { collectionView.contentInset = UIEdgeInsets(top: collectionTop, left: 0, bottom: UIDevice.current.hx_bottomMargin, right: 0) } let space = config.spacing let count : CGFloat if UIDevice.current.hx_isPortrait == true { count = CGFloat(config.rowNumber) }else { count = CGFloat(config.landscapeRowNumber) } let itemWidth = (collectionView.hx_width - space * (count - CGFloat(1))) / count collectionViewLayout.itemSize = CGSize.init(width: itemWidth, height: itemWidth) if orientationDidChange { if hx_pickerController != nil && hx_pickerController!.config.albumShowMode == .popup { titleView.updateViewFrame() } collectionView.reloadData() DispatchQueue.main.async { if self.beforeOrientationIndexPath != nil { self.collectionView.scrollToItem(at: self.beforeOrientationIndexPath!, at: .top, animated: false) } } orientationDidChange = false } emptyView.hx_width = collectionView.hx_width emptyView.center = CGPoint(x: collectionView.hx_width * 0.5, y: (collectionView.hx_height - collectionView.contentInset.top - collectionView.contentInset.bottom) * 0.5) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if #available(iOS 13.0, *) { beforeOrientationIndexPath = collectionView.indexPathsForVisibleItems.first orientationDidChange = true } super.viewWillTransition(to: size, with: coordinator) } override var prefersStatusBarHidden: Bool { return false } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) { configColor() } } } deinit { NotificationCenter.default.removeObserver(self) } } @objc protocol HXPHPickerBottomViewDelegate: NSObjectProtocol { @objc optional func bottomView(didPreviewButtonClick view: HXPHPickerBottomView) @objc optional func bottomView(didEditButtonClick view: HXPHPickerBottomView) @objc optional func bottomView(didFinishButtonClick view: HXPHPickerBottomView) @objc optional func bottomView(didOriginalButtonClick view: HXPHPickerBottomView, with isOriginal: Bool) @objc optional func bottomView(_ bottomView: HXPHPickerBottomView, didSelectedItemAt photoAsset: HXPHAsset) } class HXPHPickerBottomView: UIToolbar, HXPHPreviewSelectedViewDelegate { weak var hx_delegate: HXPHPickerBottomViewDelegate? var config: HXPHPickerBottomViewConfiguration lazy var selectedView: HXPHPreviewSelectedView = { let selectedView = HXPHPreviewSelectedView.init(frame: CGRect(x: 0, y: 0, width: hx_width, height: 70)) if let customSelectedViewCellClass = config.customSelectedViewCellClass { selectedView.collectionView.register(customSelectedViewCellClass, forCellWithReuseIdentifier: NSStringFromClass(HXPHPreviewSelectedViewCell.self)) }else { selectedView.collectionView.register(HXPHPreviewSelectedViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(HXPHPreviewSelectedViewCell.self)) } selectedView.delegate = self selectedView.tickColor = config.selectedViewTickColor return selectedView }() lazy var promptView: UIView = { let promptView = UIView.init(frame: CGRect(x: 0, y: 0, width: hx_width, height: 70)) promptView.addSubview(promptIcon) promptView.addSubview(promptLb) promptView.addSubview(promptArrow) promptView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(didPromptViewClick))) return promptView }() @objc func didPromptViewClick() { HXPHTools.openSettingsURL() } lazy var promptLb: UILabel = { let promptLb = UILabel.init(frame: CGRect(x: 0, y: 0, width: 0, height: 60)) promptLb.text = "无法访问相册中所有照片,\n请允许访问「照片」中的「所有照片」".hx_localized promptLb.font = UIFont.systemFont(ofSize: 15) promptLb.numberOfLines = 0 promptLb.adjustsFontSizeToFitWidth = true return promptLb }() lazy var promptIcon: UIImageView = { let image = UIImage.hx_named(named: "hx_picker_photolist_bottom_prompt")?.withRenderingMode(.alwaysTemplate) let promptIcon = UIImageView.init(image: image) promptIcon.hx_size = promptIcon.image?.size ?? CGSize.zero return promptIcon }() lazy var promptArrow: UIImageView = { let image = UIImage.hx_named(named: "hx_picker_photolist_bottom_prompt_arrow")?.withRenderingMode(.alwaysTemplate) let promptArrow = UIImageView.init(image: image) promptArrow.hx_size = promptArrow.image?.size ?? CGSize.zero return promptArrow }() lazy var contentView: UIView = { let contentView = UIView.init(frame: CGRect(x: 0, y: 0, width: hx_width, height: 50 + UIDevice.current.hx_bottomMargin)) contentView.addSubview(previewBtn) contentView.addSubview(editBtn) contentView.addSubview(originalBtn) contentView.addSubview(finishBtn) return contentView }() lazy var previewBtn: UIButton = { let previewBtn = UIButton.init(type: .custom) previewBtn.setTitle("预览".hx_localized, for: .normal) previewBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17) previewBtn.isEnabled = false previewBtn.addTarget(self, action: #selector(didPreviewButtonClick(button:)), for: .touchUpInside) previewBtn.isHidden = config.previewButtonHidden previewBtn.hx_height = 50 let previewWidth : CGFloat = previewBtn.currentTitle!.hx_localized.hx_stringWidth(ofFont: previewBtn.titleLabel!.font, maxHeight: 50) previewBtn.hx_width = previewWidth return previewBtn }() @objc func didPreviewButtonClick(button: UIButton) { hx_delegate?.bottomView?(didPreviewButtonClick: self) } lazy var editBtn: UIButton = { let editBtn = UIButton.init(type: .custom) editBtn.setTitle("编辑".hx_localized, for: .normal) editBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17) editBtn.addTarget(self, action: #selector(didEditBtnButtonClick(button:)), for: .touchUpInside) editBtn.isHidden = config.editButtonHidden editBtn.hx_height = 50 let editWidth : CGFloat = editBtn.currentTitle!.hx_localized.hx_stringWidth(ofFont: editBtn.titleLabel!.font, maxHeight: 50) editBtn.hx_width = editWidth return editBtn }() @objc func didEditBtnButtonClick(button: UIButton) { hx_delegate?.bottomView?(didEditButtonClick: self) } lazy var originalBtn: UIView = { let originalBtn = UIView.init() originalBtn.addSubview(originalTitleLb) originalBtn.addSubview(boxControl) originalBtn.addSubview(originalLoadingView) let tap = UITapGestureRecognizer.init(target: self, action: #selector(didOriginalButtonClick)) originalBtn.addGestureRecognizer(tap) originalBtn.isHidden = config.originalButtonHidden return originalBtn }() @objc func didOriginalButtonClick() { boxControl.isSelected = !boxControl.isSelected if !boxControl.isSelected { // 取消 cancelRequestAssetFileSize() }else { // 选中 requestAssetBytes() } hx_viewController()?.hx_pickerController?.isOriginal = boxControl.isSelected hx_delegate?.bottomView?(didOriginalButtonClick: self, with: boxControl.isSelected) boxControl.layer.removeAnimation(forKey: "SelectControlAnimation") let keyAnimation = CAKeyframeAnimation.init(keyPath: "transform.scale") keyAnimation.duration = 0.3 keyAnimation.values = [1.2, 0.8, 1.1, 0.9, 1.0] boxControl.layer.add(keyAnimation, forKey: "SelectControlAnimation") } func requestAssetBytes() { if isExternalPreview { return } if !config.showOriginalFileSize || !isMultipleSelect { return } if !boxControl.isSelected { cancelRequestAssetFileSize() return } if let pickerController = hx_viewController()?.hx_pickerController { if pickerController.selectedAssetArray.isEmpty { cancelRequestAssetFileSize() return } originalLoadingDelayTimer?.invalidate() let timer = Timer.init(timeInterval: 0.1, target: self, selector: #selector(showOriginalLoading(timer:)), userInfo: nil, repeats: false) RunLoop.main.add(timer, forMode: .common) originalLoadingDelayTimer = timer pickerController.requestSelectedAssetFileSize(isPreview: isPreview) { (bytes, bytesString) in self.originalLoadingDelayTimer?.invalidate() self.originalLoadingDelayTimer = nil self.originalLoadingView.stopAnimating() self.showOriginalLoadingView = false self.originalTitleLb.text = "原图".hx_localized + " (" + bytesString + ")" self.updateOriginalButtonFrame() } } } @objc func showOriginalLoading(timer: Timer) { originalTitleLb.text = "原图".hx_localized showOriginalLoadingView = true originalLoadingView.startAnimating() updateOriginalButtonFrame() originalLoadingDelayTimer = nil } func cancelRequestAssetFileSize() { if isExternalPreview { return } if !config.showOriginalFileSize || !isMultipleSelect { return } originalLoadingDelayTimer?.invalidate() originalLoadingDelayTimer = nil if let pickerController = hx_viewController()?.hx_pickerController { pickerController.cancelRequestAssetFileSize(isPreview: isPreview) } showOriginalLoadingView = false originalLoadingView.stopAnimating() originalTitleLb.text = "原图".hx_localized updateOriginalButtonFrame() } lazy var originalTitleLb: UILabel = { let originalTitleLb = UILabel.init() originalTitleLb.text = "原图".hx_localized originalTitleLb.font = UIFont.systemFont(ofSize: 17) originalTitleLb.lineBreakMode = .byTruncatingHead return originalTitleLb }() lazy var boxControl: HXPHPickerSelectBoxView = { let boxControl = HXPHPickerSelectBoxView.init(frame: CGRect(x: 0, y: 0, width: 17, height: 17)) boxControl.config = config.originalSelectBox boxControl.backgroundColor = UIColor.clear return boxControl }() var showOriginalLoadingView: Bool = false var originalLoadingDelayTimer: Timer? lazy var originalLoadingView: UIActivityIndicatorView = { let originalLoadingView = UIActivityIndicatorView.init(style: .white) originalLoadingView.hidesWhenStopped = true return originalLoadingView }() lazy var finishBtn: UIButton = { let finishBtn = UIButton.init(type: .custom) finishBtn.setTitle("完成".hx_localized, for: .normal) finishBtn.titleLabel?.font = UIFont.hx_mediumPingFang(size: 16) finishBtn.layer.cornerRadius = 3 finishBtn.layer.masksToBounds = true finishBtn.isEnabled = false finishBtn.addTarget(self, action: #selector(didFinishButtonClick(button:)), for: .touchUpInside) return finishBtn }() @objc func didFinishButtonClick(button: UIButton) { hx_delegate?.bottomView?(didFinishButtonClick: self) } var allowLoadPhotoLibrary: Bool var isMultipleSelect : Bool var isExternalPreview: Bool var isPreview: Bool init(config: HXPHPickerBottomViewConfiguration, allowLoadPhotoLibrary: Bool, isMultipleSelect: Bool, isPreview: Bool, isExternalPreview: Bool) { self.isPreview = isPreview self.isExternalPreview = isExternalPreview self.allowLoadPhotoLibrary = allowLoadPhotoLibrary self.config = config self.isMultipleSelect = isMultipleSelect super.init(frame: CGRect.zero) if config.showPrompt && HXPHAssetManager.authorizationStatusIsLimited() && allowLoadPhotoLibrary && !isPreview && !isExternalPreview { addSubview(promptView) } if isExternalPreview { if config.showSelectedView { addSubview(selectedView) } if !config.editButtonHidden { addSubview(editBtn) } }else { addSubview(contentView) if config.showSelectedView && isMultipleSelect { addSubview(selectedView) } } configColor() isTranslucent = config.isTranslucent } convenience init(config: HXPHPickerBottomViewConfiguration, allowLoadPhotoLibrary: Bool) { self.init(config: config, allowLoadPhotoLibrary: allowLoadPhotoLibrary, isMultipleSelect: true, isPreview: false, isExternalPreview: false) } func updatePromptView() { if config.showPrompt && HXPHAssetManager.authorizationStatusIsLimited() && allowLoadPhotoLibrary && !isPreview && !isExternalPreview { if promptView.superview == nil { addSubview(promptView) configPromptColor() } } } func configColor() { let isDark = HXPHManager.shared.isDark backgroundColor = isDark ? config.backgroundDarkColor : config.backgroundColor barTintColor = isDark ? config.barTintDarkColor : config.barTintColor barStyle = isDark ? config.barDarkStyle : config.barStyle if !isExternalPreview { previewBtn.setTitleColor(isDark ? config.previewButtonTitleDarkColor : config.previewButtonTitleColor, for: .normal) editBtn.setTitleColor(isDark ? config.editButtonTitleDarkColor : config.editButtonTitleColor, for: .normal) if isDark { if config.previewButtonDisableTitleDarkColor != nil { previewBtn.setTitleColor(config.previewButtonDisableTitleDarkColor, for: .disabled) }else { previewBtn.setTitleColor(config.previewButtonTitleDarkColor.withAlphaComponent(0.6), for: .disabled) } if config.editButtonDisableTitleDarkColor != nil { editBtn.setTitleColor(config.editButtonDisableTitleDarkColor, for: .disabled) }else { editBtn.setTitleColor(config.editButtonTitleDarkColor.withAlphaComponent(0.6), for: .disabled) } }else { if config.previewButtonDisableTitleColor != nil { previewBtn.setTitleColor(config.previewButtonDisableTitleColor, for: .disabled) }else { previewBtn.setTitleColor(config.previewButtonTitleColor.withAlphaComponent(0.6), for: .disabled) } if config.editButtonDisableTitleColor != nil { editBtn.setTitleColor(config.editButtonDisableTitleColor, for: .disabled) }else { editBtn.setTitleColor(config.editButtonTitleColor.withAlphaComponent(0.6), for: .disabled) } } originalLoadingView.style = isDark ? config.originalLoadingDarkStyle : config.originalLoadingStyle originalTitleLb.textColor = isDark ? config.originalButtonTitleDarkColor : config.originalButtonTitleColor let finishBtnBackgroundColor = isDark ? config.finishButtonDarkBackgroundColor : config.finishButtonBackgroundColor finishBtn.setTitleColor(isDark ? config.finishButtonTitleDarkColor : config.finishButtonTitleColor, for: .normal) finishBtn.setTitleColor(isDark ? config.finishButtonDisableTitleDarkColor : config.finishButtonDisableTitleColor, for: .disabled) finishBtn.setBackgroundImage(UIImage.hx_image(for: finishBtnBackgroundColor, havingSize: CGSize.zero), for: .normal) finishBtn.setBackgroundImage(UIImage.hx_image(for: isDark ? config.finishButtonDisableDarkBackgroundColor : config.finishButtonDisableBackgroundColor, havingSize: CGSize.zero), for: .disabled) } configPromptColor() } func configPromptColor() { if config.showPrompt && HXPHAssetManager.authorizationStatusIsLimited() && allowLoadPhotoLibrary && !isPreview && !isExternalPreview { let isDark = HXPHManager.shared.isDark promptLb.textColor = isDark ? config.promptTitleDarkColor : config.promptTitleColor promptIcon.tintColor = isDark ? config.promptIconDarkColor : config.promptIconColor promptArrow.tintColor = isDark ? config.promptArrowDarkColor : config.promptArrowColor } } func updateFinishButtonTitle() { if isExternalPreview { return } requestAssetBytes() var selectCount = 0 if let pickerController = hx_viewController()?.hx_pickerController { if pickerController.config.selectMode == .multiple { selectCount = pickerController.selectedAssetArray.count } } if selectCount > 0 { finishBtn.isEnabled = true previewBtn.isEnabled = true finishBtn.setTitle("完成".hx_localized + " (" + String(format: "%d", arguments: [selectCount]) + ")", for: .normal) }else { finishBtn.isEnabled = !config.disableFinishButtonWhenNotSelected previewBtn.isEnabled = false finishBtn.setTitle("完成".hx_localized, for: .normal) } updateFinishButtonFrame() } func updateFinishButtonFrame() { if isExternalPreview { return } var finishWidth : CGFloat = finishBtn.currentTitle!.hx_localized.hx_stringWidth(ofFont: finishBtn.titleLabel!.font, maxHeight: 50) + 20 if finishWidth < 60 { finishWidth = 60 } finishBtn.frame = CGRect(x: hx_width - UIDevice.current.hx_rightMargin - finishWidth - 12, y: 0, width: finishWidth, height: 33) finishBtn.hx_centerY = 25 } func updateOriginalButtonFrame() { if isExternalPreview { return } updateOriginalSubviewFrame() if showOriginalLoadingView { originalBtn.frame = CGRect(x: 0, y: 0, width: originalLoadingView.frame.maxX, height: 50) }else { originalBtn.frame = CGRect(x: 0, y: 0, width: originalTitleLb.frame.maxX, height: 50) } originalBtn.hx_centerX = hx_width / 2 if originalBtn.frame.maxX > finishBtn.hx_x { originalBtn.hx_x = finishBtn.hx_x - originalBtn.hx_width if originalBtn.hx_x < previewBtn.frame.maxX + 2 { originalBtn.hx_x = previewBtn.frame.maxX + 2 originalTitleLb.hx_width = finishBtn.hx_x - previewBtn.frame.maxX - 2 - 5 - boxControl.hx_width } } } private func updateOriginalSubviewFrame() { if isExternalPreview { return } originalTitleLb.frame = CGRect(x: boxControl.frame.maxX + 5, y: 0, width: originalTitleLb.text!.hx_stringWidth(ofFont: originalTitleLb.font, maxHeight: 50), height: 50) boxControl.hx_centerY = originalTitleLb.hx_height * 0.5 originalLoadingView.hx_centerY = originalBtn.hx_height * 0.5 originalLoadingView.hx_x = originalTitleLb.frame.maxX + 3 } // MARK: HXPHPreviewSelectedViewDelegate func selectedView(_ selectedView: HXPHPreviewSelectedView, didSelectItemAt photoAsset: HXPHAsset) { hx_delegate?.bottomView?(self, didSelectedItemAt: photoAsset) } override func layoutSubviews() { super.layoutSubviews() if !isExternalPreview { contentView.hx_width = hx_width contentView.hx_height = 50 + UIDevice.current.hx_bottomMargin contentView.hx_y = hx_height - contentView.hx_height previewBtn.hx_x = 12 + UIDevice.current.hx_leftMargin editBtn.hx_x = previewBtn.hx_x updateFinishButtonFrame() updateOriginalButtonFrame() } if config.showPrompt && HXPHAssetManager.authorizationStatusIsLimited() && allowLoadPhotoLibrary && !isPreview && !isExternalPreview { promptView.hx_width = hx_width promptIcon.hx_x = 12 + UIDevice.current.hx_leftMargin promptIcon.hx_centerY = promptView.hx_height * 0.5 promptArrow.hx_x = hx_width - 12 - promptArrow.hx_width - UIDevice.current.hx_rightMargin promptLb.hx_x = promptIcon.frame.maxX + 12 promptLb.hx_width = promptArrow.hx_x - promptLb.hx_x - 12 promptLb.hx_centerY = promptView.hx_height * 0.5 promptArrow.hx_centerY = promptView.hx_height * 0.5 } if isExternalPreview { editBtn.hx_x = 12 + UIDevice.current.hx_leftMargin if config.showSelectedView { if !config.editButtonHidden { selectedView.hx_x = editBtn.frame.maxX + 12 selectedView.hx_width = hx_width - selectedView.hx_x selectedView.collectionViewLayout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 5, right: 12 + UIDevice.current.hx_rightMargin) }else { selectedView.hx_width = hx_width } editBtn.hx_centerY = selectedView.hx_centerY } }else { if config.showSelectedView && isMultipleSelect { selectedView.hx_width = hx_width } } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) { configColor() } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
46.321543
283
0.645269
f9bbab2655cfe3fd923156717019d27df2a71e1f
5,452
// // PopupView.swift // Ride Report // // Created by William Henderson on 1/15/15. // Copyright (c) 2015 Knock Softwae, Inc. All rights reserved. // import Foundation @IBDesignable class PopupView : UIButton { @IBInspectable var strokeWidth: CGFloat = 2 @IBInspectable var arrowHeight: CGFloat = 10 @IBInspectable var arrowBaseWidth: CGFloat = 10 @IBInspectable var cornerRadius: CGFloat = 10 @IBInspectable var arrowInset: CGFloat = 10 @IBInspectable var fontSize: CGFloat = 14 @IBInspectable var strokeColor: UIColor = UIColor.darkGray @IBInspectable var fontColor: UIColor = UIColor.darkGray @IBInspectable var fillColor: UIColor = UIColor.white var arrowOriginPercentageWidth: CGFloat? @IBInspectable var text: String = "Popupview Text" { didSet { self.reloadView() } } private var textLabel : UILabel! = nil private var widthConstraint : NSLayoutConstraint! = nil private var heightConstraint : NSLayoutConstraint! = nil required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } func commonInit() { self.textLabel = UILabel(frame: CGRect.zero) self.textLabel.numberOfLines = 0 self.textLabel.lineBreakMode = NSLineBreakMode.byWordWrapping self.textLabel.adjustsFontSizeToFitWidth = true self.textLabel.minimumScaleFactor = 0.4 self.reloadView() self.addSubview(self.textLabel) } private func reloadView() { let yOffset = self.arrowHeight self.textLabel.frame = CGRect(x: 7, y: yOffset, width: self.frame.size.width, height: self.frame.size.height - yOffset) let rightHandBefore = self.frame.origin.x + self.frame.width self.textLabel.textColor = fontColor self.textLabel.text = self.text self.textLabel.font = UIFont.systemFont(ofSize: self.fontSize) if let superview = self.superview { self.textLabel.frame.size.width = superview.frame.width - 30 } self.textLabel.sizeToFit() let newWidth = self.textLabel.frame.width + 20 let newHeight = self.textLabel.frame.height + 28 self.frame = CGRect(x: rightHandBefore - newWidth, y: self.frame.origin.y, width: newWidth, height: newHeight) if (self.widthConstraint != nil) { self.removeConstraint(self.widthConstraint) } self.widthConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1.0, constant: newWidth) self.addConstraint(self.widthConstraint) if (self.heightConstraint != nil) { self.removeConstraint(self.heightConstraint) } self.heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1.0, constant: newHeight) self.addConstraint(self.heightConstraint) self.setNeedsDisplay() } override func didMoveToSuperview() { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [weak self] in guard let strongSelf = self else { return } strongSelf.reloadView() } } override func draw(_ rect: CGRect) { let smallerPath = CGRect(x: rect.origin.x + strokeWidth, y: strokeWidth, width: rect.size.width - 2*strokeWidth, height: rect.size.height - arrowHeight - 2*strokeWidth) let path = UIBezierPath(roundedRect: smallerPath, cornerRadius: cornerRadius) fillColor.setFill() strokeColor.setStroke() path.lineWidth = strokeWidth path.stroke() var origin = smallerPath.size.width if let originPercentage = self.arrowOriginPercentageWidth { origin = origin * originPercentage + arrowBaseWidth } if arrowHeight > 0 && arrowBaseWidth > 0 { let arrowPoint = CGPoint(x: origin - arrowInset - arrowBaseWidth, y: smallerPath.size.height + strokeWidth) let arrowPath = UIBezierPath() let halfArrowWidth = arrowBaseWidth / 2.0 let tipPt = CGPoint(x: arrowPoint.x + halfArrowWidth, y: arrowPoint.y + arrowHeight) let endPt = CGPoint(x: arrowPoint.x + arrowBaseWidth, y: arrowPoint.y) // Note: we always build the arrow path in a clockwise direction. // Arrow points towards top. We're starting from the left. arrowPath.move(to: arrowPoint) arrowPath.addLine(to: tipPt) arrowPath.addLine(to: endPt) arrowPath.lineCapStyle = CGLineCap.butt arrowPath.lineWidth = strokeWidth arrowPath.stroke() arrowPath.fill(with: CGBlendMode.clear, alpha:1.0) arrowPath.fill() } path.fill(with: CGBlendMode.clear, alpha:1.0) path.fill() } }
39.79562
263
0.6438
4b216d23ab4d418c67a8fa45b5d1e8d312db99fd
1,027
// // LaunchView.swift // Shards // // Created by Rostislav Brož on 11/8/21. // import SwiftUI let screenSize: CGRect = UIScreen.main.bounds // Colors public var white = Color(red: 1, green: 1, blue: 1) public var gray = Color(red: 0.9, green: 0.9, blue: 0.9) public var red = Color(red: 1, green: 0, blue: 0) public var lightRed = Color(red: 1, green: 0, blue: 0) public var black = Color(red: 0.04, green: 0, blue: 0) struct LaunchView: View { @EnvironmentObject var model: ContentModel var body: some View { if model.authorizationState == .notDetermined { // Not determined -> onboarding view (first time view) OnBoardingView() } else if model.authorizationState == .authorizedWhenInUse || model.authorizationState == .authorizedAlways { HomeView() } else { DeniedView() } } }
20.54
115
0.539435
e66ed108b4d1e6bf1634dd3b88397873e79a4e68
2,144
// // RSA1_5.swift // JWTswift // // Created by Blended Learning Center on 24.09.18. // Copyright © 2018 Blended Learning Center. All rights reserved. // import Foundation internal struct RSA1_5{ static func encrypt(encryptKey : Key, cek: [UInt8]) -> Data? { //.rsaEncryptionPKCS1 guard SecKeyIsAlgorithmSupported(encryptKey.getKeyObject(), .encrypt, .rsaEncryptionPKCS1) else { print("Key doesn't support the encryption algorithm.") return nil } print("block size = " , SecKeyGetBlockSize(encryptKey.getKeyObject())) // Transform CEK into Data format let cekData = Data(bytes: cek) print("cekData count = " ,cekData.count) guard cekData.count < (SecKeyGetBlockSize(encryptKey.getKeyObject())-130) else { print("Cek is too big") return nil } var error: Unmanaged<CFError>? guard let cipherText = SecKeyCreateEncryptedData(encryptKey.getKeyObject(), .rsaEncryptionPKCS1, cekData as CFData, &error) as Data? else { print(error!.takeRetainedValue()) return nil } print("Cipher Text = " ,[UInt8](cipherText).count) return cipherText } static func decrypt(decryptKey: Key, cipherText: Data) -> Data? { //rsaEncryptionPKCS1 guard SecKeyIsAlgorithmSupported(decryptKey.getKeyObject(), .decrypt, .rsaEncryptionPKCS1) else { print("Key doesn't support the decryption algoritm.") return nil } print("CipherData count = \(cipherText.count)") guard cipherText.count == (SecKeyGetBlockSize(decryptKey.getKeyObject())) else { print("Cek is too big") return nil } var error : Unmanaged<CFError>? guard let plainData = SecKeyCreateDecryptedData(decryptKey.getKeyObject(), .rsaEncryptionPKCS1, cipherText as CFData, &error) else { print(error!.takeRetainedValue()) return nil } return plainData as Data } }
32.984615
147
0.604011
cc412b752e17d87a2192032a8f41b8381725fc48
4,580
// // AKMIDICallbackInstrument // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2018 AudioKit. All rights reserved. // /// MIDI Instrument that triggers functions on MIDI note on/off commands /// This is used mostly with the AppleSequencer sending to a MIDIEndpointRef /// Another callback instrument, AKCallbackInstrument /// You will need to enable "Background Modes - Audio" in your project for this to work. open class AKMIDICallbackInstrument: AKMIDIInstrument { // MARK: - Properties /// All callbacks that will get triggered by MIDI events open var callback: AKMIDICallback? // MARK: - Initialization /// Initialize the callback instrument /// /// - parameter midiInputName: Name of the instrument's MIDI input /// - parameter callback: Initial callback /// public init(midiInputName: String = "AudioKit Callback Instrument", callback: AKMIDICallback? = nil) { super.init(midiInputName: midiInputName) self.name = midiInputName self.callback = callback avAudioNode = AVAudioMixerNode() AudioKit.engine.attach(self.avAudioNode) } // MARK: - Triggering fileprivate func triggerCallbacks(_ status: AKMIDIStatus, data1: MIDIByte, data2: MIDIByte) { _ = callback.map { $0(status.byte, data1, data2) } } /// Will trigger in response to any noteOn Message /// /// - Parameters: /// - noteNumber: MIDI Note Number being started /// - velocity: MIDI Velocity (0-127) /// - channel: MIDI Channel /// override open func start(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, offset: MIDITimeStamp = 0) { triggerCallbacks(AKMIDIStatus(type: .noteOn, channel: channel), data1: noteNumber, data2: velocity) } /// Will trigger in response to any noteOff Message /// /// - Parameters: /// - noteNumber: MIDI Note Number being stopped /// - channel: MIDI Channel /// override open func stop(noteNumber: MIDINoteNumber, channel: MIDIChannel, offset: MIDITimeStamp = 0) { triggerCallbacks(AKMIDIStatus(type: .noteOff, channel: channel), data1: noteNumber, data2: 0) } // MARK: - MIDI override open func receivedMIDIController(_ controller: MIDIByte, value: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, offset: MIDITimeStamp = 0) { triggerCallbacks(AKMIDIStatus(type: .controllerChange, channel: channel), data1: controller, data2: value) } override open func receivedMIDIAftertouch(noteNumber: MIDINoteNumber, pressure: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, offset: MIDITimeStamp = 0) { triggerCallbacks(AKMIDIStatus(type: .polyphonicAftertouch, channel: channel), data1: noteNumber, data2: pressure) } override open func receivedMIDIAftertouch(_ pressure: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, offset: MIDITimeStamp = 0) { triggerCallbacks(AKMIDIStatus(type: .channelAftertouch, channel: channel), data1: pressure, data2: 0) } override open func receivedMIDIPitchWheel(_ pitchWheelValue: MIDIWord, channel: MIDIChannel, portID: MIDIUniqueID? = nil, offset: MIDITimeStamp = 0) { triggerCallbacks(AKMIDIStatus(type: .pitchWheel, channel: channel), data1: pitchWheelValue.msb, data2: pitchWheelValue.lsb) } }
40.530973
106
0.524454
1409964314c92b13e3b55139c822aa2181488851
216
// // Created by Maxim Berezhnoy on 17/01/2020. // // Copyright (c) 2020 rencevio. All rights reserved. import struct Foundation.URL struct Photo { typealias ID = String let id: ID let imageURL: URL }
15.428571
52
0.675926
118fc7c034c0bbe97b1bf5635e0eacf4d8f32bc4
8,320
/// Represents an action that will do some work when executed with a value of /// type `Input`, then return zero or more values of type `Output` and/or error /// out with an error of type `Error`. If no errors should be possible, NoError /// can be specified for the `Error` parameter. /// /// Actions enforce serial execution. Any attempt to execute an action multiple /// times concurrently will return an error. public final class Action<Input, Output, Error: ErrorType> { private let executeClosure: Input -> SignalProducer<Output, Error> private let eventsObserver: Signal<Event<Output, Error>, NoError>.Observer /// A signal of all events generated from applications of the Action. /// /// In other words, this will send every `Event` from every signal generated /// by each SignalProducer returned from apply(). public let events: Signal<Event<Output, Error>, NoError> /// A signal of all values generated from applications of the Action. /// /// In other words, this will send every value from every signal generated /// by each SignalProducer returned from apply(). public let values: Signal<Output, NoError> /// A signal of all errors generated from applications of the Action. /// /// In other words, this will send errors from every signal generated by /// each SignalProducer returned from apply(). public let errors: Signal<Error, NoError> /// Whether the action is currently executing. public var executing: PropertyOf<Bool> { return PropertyOf(_executing) } private let _executing: MutableProperty<Bool> = MutableProperty(false) /// Whether the action is currently enabled. public var enabled: PropertyOf<Bool> { return PropertyOf(_enabled) } private let _enabled: MutableProperty<Bool> = MutableProperty(false) /// Whether the instantiator of this action wants it to be enabled. private let userEnabled: PropertyOf<Bool> /// Lazy creation and storage of a UI bindable `CocoaAction`. The default behavior /// force casts the AnyObject? input to match the action's `Input` type. This makes /// it unsafe for use when the action is parameterized for something like `Void` /// input. In those cases, explicitly assign a value to this property that transforms /// the input to suit your needs. public lazy var unsafeCocoaAction: CocoaAction = { _ in CocoaAction(self) { $0 as! Input } }() /// This queue is used for read-modify-write operations on the `_executing` /// property. private let executingQueue = dispatch_queue_create("org.reactivecocoa.ReactiveCocoa.Action.executingQueue", DISPATCH_QUEUE_SERIAL) /// Whether the action should be enabled for the given combination of user /// enabledness and executing status. private static func shouldBeEnabled(#userEnabled: Bool, executing: Bool) -> Bool { return userEnabled && !executing } /// Initializes an action that will be conditionally enabled, and create a /// SignalProducer for each input. public init<P: PropertyType where P.Value == Bool>(enabledIf: P, _ execute: Input -> SignalProducer<Output, Error>) { executeClosure = execute userEnabled = PropertyOf(enabledIf) (events, eventsObserver) = Signal<Event<Output, Error>, NoError>.pipe() values = events |> map { $0.value } |> ignoreNil errors = events |> map { $0.error } |> ignoreNil _enabled <~ enabledIf.producer |> combineLatestWith(executing.producer) |> map(Action.shouldBeEnabled) } /// Initializes an action that will be enabled by default, and create a /// SignalProducer for each input. public convenience init(_ execute: Input -> SignalProducer<Output, Error>) { self.init(enabledIf: ConstantProperty(true), execute) } deinit { sendCompleted(eventsObserver) } /// Creates a SignalProducer that, when started, will execute the action /// with the given input, then forward the results upon the produced Signal. /// /// If the action is disabled when the returned SignalProducer is started, /// the produced signal will send `ActionError.NotEnabled`, and nothing will /// be sent upon `values` or `errors` for that particular signal. public func apply(input: Input) -> SignalProducer<Output, ActionError<Error>> { return SignalProducer { observer, disposable in var startedExecuting = false dispatch_sync(self.executingQueue) { if self._enabled.value { self._executing.value = true startedExecuting = true } } if !startedExecuting { sendError(observer, .NotEnabled) return } self.executeClosure(input).startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observe(Signal.Observer { event in observer.put(event.mapError { .ProducerError($0) }) sendNext(self.eventsObserver, event) }) } disposable.addDisposable { self._executing.value = false } } } } /// Wraps an Action for use by a GUI control (such as `NSControl` or /// `UIControl`), with KVO, or with Cocoa Bindings. public final class CocoaAction: NSObject { /// The selector that a caller should invoke upon a CocoaAction in order to /// execute it. public static let selector: Selector = "execute:" /// Whether the action is enabled. /// /// This property will only change on the main thread, and will generate a /// KVO notification for every change. public var enabled: Bool { return _enabled } /// Whether the action is executing. /// /// This property will only change on the main thread, and will generate a /// KVO notification for every change. public var executing: Bool { return _executing } private var _enabled = false private var _executing = false private let _execute: AnyObject? -> () private let disposable = CompositeDisposable() /// Initializes a Cocoa action that will invoke the given Action by /// transforming the object given to execute(). public init<Input, Output, Error>(_ action: Action<Input, Output, Error>, _ inputTransform: AnyObject? -> Input) { _execute = { input in let producer = action.apply(inputTransform(input)) producer.start() } super.init() disposable += action.enabled.producer |> observeOn(UIScheduler()) |> start(next: { [weak self] value in self?.willChangeValueForKey("enabled") self?._enabled = value self?.didChangeValueForKey("enabled") }) disposable += action.executing.producer |> observeOn(UIScheduler()) |> start(next: { [weak self] value in self?.willChangeValueForKey("executing") self?._executing = value self?.didChangeValueForKey("executing") }) } /// Initializes a Cocoa action that will invoke the given Action by /// always providing the given input. public convenience init<Input, Output, Error>(_ action: Action<Input, Output, Error>, input: Input) { self.init(action, { _ in input }) } deinit { disposable.dispose() } /// Attempts to execute the underlying action with the given input, subject /// to the behavior described by the initializer that was used. @IBAction public func execute(input: AnyObject?) { _execute(input) } public override class func automaticallyNotifiesObserversForKey(key: String) -> Bool { return false } } /// The type of error that can occur from Action.apply, where `E` is the type of /// error that can be generated by the specific Action instance. public enum ActionError<E: ErrorType> { /// The producer returned from apply() was started while the Action was /// disabled. case NotEnabled /// The producer returned from apply() sent the given error. case ProducerError(E) } extension ActionError: ErrorType { public var nsError: NSError { switch self { case .NotEnabled: return NSError(domain: "org.reactivecocoa.ReactiveCocoa.Action", code: 1, userInfo: [ NSLocalizedDescriptionKey: self.description ]) case let .ProducerError(error): return error.nsError } } } extension ActionError: Printable { public var description: String { switch self { case .NotEnabled: return "Action executed while disabled" case let .ProducerError(error): return toString(error) } } } public func == <E: Equatable>(lhs: ActionError<E>, rhs: ActionError<E>) -> Bool { switch (lhs, rhs) { case (.NotEnabled, .NotEnabled): return true case let (.ProducerError(left), .ProducerError(right)): return left == right default: return false } }
32.627451
131
0.72524
fedcf95520d49b208af9cfe1e401d5cdec06aea5
294
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { enum S<T.h:as b: T where g: NSObject { var d = a(v: a { func a(Any) { case c, { [k<j struct Q<T: A? { class case c, struct
18.375
87
0.690476
9cb5252de5693a9f79e9adbfd1c770e693eaa57e
1,848
// // PraseErrorType.swift // MoYu // // Created by Chris on 16/8/2. // Copyright © 2016年 Chris. All rights reserved. // import UIKit import SwiftyJSON enum NetworkActionStatus{ case success(message:String) case userNeedLogin case userFailure(message:String) case systemFailure(message:String) case networkFailure(message:String) case otherFailure(message:String) } protocol PraseErrorType : SignInType { func show(error status:NetworkActionStatus,showSuccess:Bool) func show(success status: NetworkActionStatus) } extension PraseErrorType where Self: AlertViewType, Self:UIViewController{ func show(error status: NetworkActionStatus ,showSuccess:Bool = false){ switch status { case .userFailure(let message): self.showAlert(message: message) case .systemFailure(let message): self.showAlert(message: message) case .networkFailure(let message): self.showAlert(message: message) case .otherFailure(let message): self.showAlert(message: message) case .userNeedLogin: self.showSignInView() case .success(let message): if showSuccess{ self.showAlert(message: message) } } } func show(success status: NetworkActionStatus){ switch status{ case .success(let message): self.showAlert(message: message) default: break } } //更新用户信息 func updateUser(_ status : NetworkActionStatus ,json : JSON?){ if let data = json ,case .success = status{ UserManager.sharedInstance.update(user: data, phone: UserManager.sharedInstance.user.phonenum) } self.show(error: status, showSuccess: true) } }
26.4
106
0.632576
2861b990e9057f7dd5ef54c69db4c66e5bb00558
2,766
// // Copyright (c) 2021 Related Code - https://relatedcode.com // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit //----------------------------------------------------------------------------------------------------------------------------------------------- class VoiceCall2View: UIViewController { @IBOutlet var imageProfile: UIImageView! @IBOutlet var labelName: UILabel! @IBOutlet var labelNumer: UILabel! @IBOutlet var viewRemind: UIView! @IBOutlet var viewMessage: UIView! //------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.prefersLargeTitles = false navigationItem.largeTitleDisplayMode = .never viewRemind.layer.borderWidth = 1 viewRemind.layer.borderColor = AppColor.Border.cgColor viewMessage.layer.borderWidth = 1 viewMessage.layer.borderColor = AppColor.Border.cgColor loadData() } // MARK: - Data methods //------------------------------------------------------------------------------------------------------------------------------------------- func loadData() { imageProfile.sample("Social", "Portraits", 19) labelName.text = "Dave Smith" labelNumer.text = "+1(513)616-5999" } // MARK: - User actions //------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionRemind(_ sender: UIButton) { print(#function) dismiss(animated: true) } //------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionMessage(_ sender: UIButton) { print(#function) dismiss(animated: true) } //------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionDecline(_ sender: UIButton) { print(#function) dismiss(animated: true) } //------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionCall(_ sender: UIButton) { print(#function) dismiss(animated: true) } }
35.922078
145
0.472523
563e52a785fb35e01557c445c7d531d275785bdd
9,958
// ImageRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Eureka public struct ImageRowSourceTypes : OptionSet { public let rawValue: Int public var imagePickerControllerSourceTypeRawValue: Int { return self.rawValue >> 1 } public init(rawValue: Int) { self.rawValue = rawValue } init(_ sourceType: UIImagePickerController.SourceType) { self.init(rawValue: 1 << sourceType.rawValue) } public static let PhotoLibrary = ImageRowSourceTypes(.photoLibrary) public static let Camera = ImageRowSourceTypes(.camera) public static let SavedPhotosAlbum = ImageRowSourceTypes(.savedPhotosAlbum) public static let All: ImageRowSourceTypes = [Camera, PhotoLibrary, SavedPhotosAlbum] } extension ImageRowSourceTypes { // MARK: Helpers var localizedString: String { switch self { case ImageRowSourceTypes.Camera: return "Take photo" case ImageRowSourceTypes.PhotoLibrary: return "Photo Library" case ImageRowSourceTypes.SavedPhotosAlbum: return "Saved Photos" default: return "" } } } public enum ImageClearAction { case no case yes(style: UIAlertAction.Style) } //MARK: Row open class _ImageRow<Cell: CellType>: OptionsRow<Cell>, PresenterRowType where Cell: BaseCell, Cell.Value == UIImage { public typealias PresenterRow = ImagePickerController /// Defines how the view controller will be presented, pushed, etc. open var presentationMode: PresentationMode<PresenterRow>? /// Will be called before the presentation occurs. open var onPresentCallback: ((FormViewController, PresenterRow) -> Void)? open var sourceTypes: ImageRowSourceTypes open internal(set) var imageURL: URL? open var clearAction = ImageClearAction.yes(style: .destructive) private var _sourceType = UIImagePickerController.SourceType.camera public required init(tag: String?) { sourceTypes = .All super.init(tag: tag) presentationMode = .presentModally(controllerProvider: ControllerProvider.callback { return ImagePickerController() }, onDismiss: { [weak self] vc in self?.select() vc.dismiss(animated: true) }) self.displayValueFor = nil } // copy over the existing logic from the SelectorRow func displayImagePickerController(_ sourceType: UIImagePickerController.SourceType) { if let presentationMode = presentationMode, !isDisabled { if let controller = presentationMode.makeController(){ controller.row = self controller.sourceType = sourceType onPresentCallback?(cell.formViewController()!, controller) presentationMode.present(controller, row: self, presentingController: cell.formViewController()!) } else{ _sourceType = sourceType presentationMode.present(nil, row: self, presentingController: cell.formViewController()!) } } } /// Extends `didSelect` method /// Selecting the Image Row cell will open a popup to choose where to source the photo from, /// based on the `sourceTypes` configured and the available sources. open override func customDidSelect() { guard !isDisabled else { super.customDidSelect() return } deselect() var availableSources: ImageRowSourceTypes = [] if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { let _ = availableSources.insert(.PhotoLibrary) } if UIImagePickerController.isSourceTypeAvailable(.camera) { let _ = availableSources.insert(.Camera) } if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) { let _ = availableSources.insert(.SavedPhotosAlbum) } sourceTypes.formIntersection(availableSources) if sourceTypes.isEmpty { super.customDidSelect() guard let presentationMode = presentationMode else { return } if let controller = presentationMode.makeController() { controller.row = self controller.title = selectorTitle ?? controller.title onPresentCallback?(cell.formViewController()!, controller) presentationMode.present(controller, row: self, presentingController: self.cell.formViewController()!) } else { presentationMode.present(nil, row: self, presentingController: self.cell.formViewController()!) } return } // Now that we know the number of sources aren't empty, let the user select the source let sourceActionSheet = UIAlertController(title: nil, message: selectorTitle, preferredStyle: .actionSheet) guard let tableView = cell.formViewController()?.tableView else { fatalError() } if let popView = sourceActionSheet.popoverPresentationController { popView.sourceView = tableView popView.sourceRect = tableView.convert(cell.accessoryView?.frame ?? cell.contentView.frame, from: cell) } createOptionsForAlertController(sourceActionSheet) if case .yes(let style) = clearAction, value != nil { let clearPhotoOption = UIAlertAction(title: NSLocalizedString("Clear Photo", comment: ""), style: style, handler: { [weak self] _ in self?.value = nil self?.imageURL = nil self?.updateCell() }) sourceActionSheet.addAction(clearPhotoOption) } if sourceActionSheet.actions.count == 1 { if let imagePickerSourceType = UIImagePickerController.SourceType(rawValue: sourceTypes.imagePickerControllerSourceTypeRawValue) { displayImagePickerController(imagePickerSourceType) } } else { let cancelOption = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler:nil) sourceActionSheet.addAction(cancelOption) if let presentingViewController = cell.formViewController() { presentingViewController.present(sourceActionSheet, animated: true) } } } /** Prepares the pushed row setting its title and completion callback. */ open override func prepare(for segue: UIStoryboardSegue) { super.prepare(for: segue) guard let rowVC = segue.destination as? PresenterRow else { return } rowVC.title = selectorTitle ?? rowVC.title rowVC.onDismissCallback = presentationMode?.onDismissCallback ?? rowVC.onDismissCallback onPresentCallback?(cell.formViewController()!, rowVC) rowVC.row = self rowVC.sourceType = _sourceType } open override func customUpdateCell() { super.customUpdateCell() cell.accessoryType = .none cell.editingAccessoryView = .none if let image = self.value { let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) imageView.contentMode = .scaleAspectFill imageView.image = image imageView.clipsToBounds = true cell.accessoryView = imageView cell.editingAccessoryView = imageView } else { cell.accessoryView = nil cell.editingAccessoryView = nil } } } extension _ImageRow { //MARK: Helpers func createOptionForAlertController(_ alertController: UIAlertController, sourceType: ImageRowSourceTypes) { guard let pickerSourceType = UIImagePickerController.SourceType(rawValue: sourceType.imagePickerControllerSourceTypeRawValue), sourceTypes.contains(sourceType) else { return } let option = UIAlertAction(title: NSLocalizedString(sourceType.localizedString, comment: ""), style: .default, handler: { [weak self] _ in self?.displayImagePickerController(pickerSourceType) }) alertController.addAction(option) } func createOptionsForAlertController(_ alertController: UIAlertController) { createOptionForAlertController(alertController, sourceType: .Camera) createOptionForAlertController(alertController, sourceType: .PhotoLibrary) createOptionForAlertController(alertController, sourceType: .SavedPhotosAlbum) } } /// A selector row where the user can pick an image public final class ImageRow : _ImageRow<PushSelectorCell<UIImage>>, RowType { public required init(tag: String?) { super.init(tag: tag) } }
41.319502
183
0.671822
9b17d0344eacaee446692f4a1b18e7cfcd2d197d
1,094
// // TotalizerView.swift // Park Observer // // Created by Regan E. Sarwas on 7/24/20. // Copyright © 2020 Alaska Region GIS Team. All rights reserved. // import SwiftUI struct TotalizerView: View { @ObservedObject var totalizer: Totalizer @EnvironmentObject var userSettings: UserSettings var body: some View { HStack { Text(totalizer.text) .padding(.vertical, 5) .padding(.leading) .font(.headline) .foregroundColor(userSettings.darkMapControls ? .black : .white) .shadow(color: userSettings.darkMapControls ? .white : .black, radius: 5.0) Spacer() Image(systemName: "xmark.circle.fill") .foregroundColor(userSettings.darkMapControls ? .black : .white) .padding(.trailing) }.background( //https://material.io/design/color/the-color-system.html#tools-for-picking-colors // Blue 50 - 500 #2196F3 Color(red: 33.0 / 255.0, green: 150.0 / 255.0, blue: 253.0 / 255.0).opacity(0.7) ) .onTapGesture { withAnimation { self.userSettings.showTotalizer = false } } } }
28.789474
87
0.649909
678752f8bd4fc278f6e6fbf14584dc532ff51049
16,228
// Copyright (c) 2017-2020 Shawn Moore and XMLCoder contributors // // This software is released under the MIT License. // https://opensource.org/licenses/MIT // // Created by Shawn Moore on 11/20/17. // import Foundation //===----------------------------------------------------------------------===// // XML Decoder //===----------------------------------------------------------------------===// /// `XMLDecoder` facilitates the decoding of XML into semantic `Decodable` types. open class XMLDecoder { // MARK: Options /// The strategy to use for decoding `Date` values. public enum DateDecodingStrategy { /// Defer to `Date` for decoding. This is the default strategy. case deferredToDate /// Decode the `Date` as a UNIX timestamp from a XML number. This is the default strategy. case secondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a XML number. case millisecondsSince1970 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decode the `Date` as a string parsed by the given formatter. case formatted(DateFormatter) /// Decode the `Date` as a custom box decoded by the given closure. case custom((_ decoder: Decoder) throws -> Date) /// Decode the `Date` as a string parsed by the given formatter for the give key. static func keyFormatted( _ formatterForKey: @escaping (CodingKey) throws -> DateFormatter? ) -> XMLDecoder.DateDecodingStrategy { return .custom { (decoder) -> Date in guard let codingKey = decoder.codingPath.last else { throw DecodingError.dataCorrupted(DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "No Coding Path Found" )) } guard let container = try? decoder.singleValueContainer(), let text = try? container.decode(String.self) else { throw DecodingError.dataCorrupted(DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Could not decode date text" )) } guard let dateFormatter = try formatterForKey(codingKey) else { throw DecodingError.dataCorruptedError( in: container, debugDescription: "No date formatter for date text" ) } if let date = dateFormatter.date(from: text) { return date } else { throw DecodingError.dataCorruptedError( in: container, debugDescription: "Cannot decode date string \(text)" ) } } } } /// The strategy to use for decoding `Data` values. public enum DataDecodingStrategy { /// Defer to `Data` for decoding. case deferredToData /// Decode the `Data` from a Base64-encoded string. This is the default strategy. case base64 /// Decode the `Data` as a custom box decoded by the given closure. case custom((_ decoder: Decoder) throws -> Data) /// Decode the `Data` as a custom box by the given closure for the give key. static func keyFormatted( _ formatterForKey: @escaping (CodingKey) throws -> Data? ) -> XMLDecoder.DataDecodingStrategy { return .custom { (decoder) -> Data in guard let codingKey = decoder.codingPath.last else { throw DecodingError.dataCorrupted(DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "No Coding Path Found" )) } guard let container = try? decoder.singleValueContainer(), let text = try? container.decode(String.self) else { throw DecodingError.dataCorrupted(DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Could not decode date text" )) } guard let data = try formatterForKey(codingKey) else { throw DecodingError.dataCorruptedError( in: container, debugDescription: "Cannot decode data string \(text)" ) } return data } } } /// The strategy to use for non-XML-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatDecodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the box of keys before decoding. public enum KeyDecodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting /// to match a key with the one specified by each type. /// /// The conversion to upper case uses `Locale.system`, also known as /// the ICU "root" locale. This means the result is consistent /// regardless of the current user's locale and language preferences. /// /// Converting from snake case to camel case: /// 1. Capitalizes the word starting after each `_` /// 2. Removes all `_` /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata). /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`. /// /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character. case convertFromSnakeCase /// Convert from "kebab-case" to "kebabCase" before attempting /// to match a key with the one specified by each type. case convertFromKebabCase /// Convert from "CodingKey" to "codingKey" case convertFromCapitalized /// Provide a custom conversion from the key in the encoded XML to the /// keys specified by the decoded types. /// The full path to the current decoding position is provided for /// context (in case you need to locate this key within the payload). /// The returned key is used in place of the last component in the /// coding path before decoding. /// If the result of the conversion is a duplicate key, then only one /// box will be present in the container for the type to decode from. case custom((_ codingPath: [CodingKey]) -> CodingKey) static func _convertFromCapitalized(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } let firstLetter = stringKey.prefix(1).lowercased() let result = firstLetter + stringKey.dropFirst() return result } static func _convertFromSnakeCase(_ stringKey: String) -> String { return _convert(stringKey, usingSeparator: "_") } static func _convertFromKebabCase(_ stringKey: String) -> String { return _convert(stringKey, usingSeparator: "-") } static func _convert(_ stringKey: String, usingSeparator separator: Character) -> String { guard !stringKey.isEmpty else { return stringKey } // Find the first non-separator character guard let firstNonSeparator = stringKey.firstIndex(where: { $0 != separator }) else { // Reached the end without finding a separator character return stringKey } // Find the last non-separator character var lastNonSeparator = stringKey.index(before: stringKey.endIndex) while lastNonSeparator > firstNonSeparator, stringKey[lastNonSeparator] == separator { stringKey.formIndex(before: &lastNonSeparator) } let keyRange = firstNonSeparator...lastNonSeparator let leadingSeparatorRange = stringKey.startIndex..<firstNonSeparator let trailingSeparatorRange = stringKey.index(after: lastNonSeparator)..<stringKey.endIndex let components = stringKey[keyRange].split(separator: separator) let joinedString: String if components.count == 1 { // No separators in key, leave the word as is - maybe it is already good joinedString = String(stringKey[keyRange]) } else { joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined() } // Do a cheap isEmpty check before creating and appending potentially empty strings let result: String if leadingSeparatorRange.isEmpty, trailingSeparatorRange.isEmpty { result = joinedString } else if !leadingSeparatorRange.isEmpty, !trailingSeparatorRange.isEmpty { // Both leading and trailing underscores result = String(stringKey[leadingSeparatorRange]) + joinedString + String(stringKey[trailingSeparatorRange]) } else if !leadingSeparatorRange.isEmpty { // Just leading result = String(stringKey[leadingSeparatorRange]) + joinedString } else { // Just trailing result = joinedString + String(stringKey[trailingSeparatorRange]) } return result } } /// The strategy to use in decoding dates. Defaults to `.secondsSince1970`. open var dateDecodingStrategy: DateDecodingStrategy = .secondsSince1970 /// The strategy to use in decoding binary data. Defaults to `.base64`. open var dataDecodingStrategy: DataDecodingStrategy = .base64 /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw /// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`. open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys /// A node's decoding type public enum NodeDecoding { case attribute case element case elementOrAttribute } /// The strategy to use in encoding encoding attributes. Defaults to `.deferredToEncoder`. open var nodeDecodingStrategy: NodeDecodingStrategy = .deferredToDecoder /// Set of strategies to use for encoding of nodes. public enum NodeDecodingStrategy { /// Defer to `Encoder` for choosing an encoding. This is the default strategy. case deferredToDecoder /// Return a closure computing the desired node encoding for the value by its coding key. case custom((Decodable.Type, Decoder) -> ((CodingKey) -> NodeDecoding)) func nodeDecodings( forType codableType: Decodable.Type, with decoder: Decoder ) -> ((CodingKey) -> NodeDecoding?) { switch self { case .deferredToDecoder: guard let dynamicType = codableType as? DynamicNodeDecoding.Type else { return { _ in nil } } return dynamicType.nodeDecoding(for:) case let .custom(closure): return closure(codableType, decoder) } } } /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey: Any] = [:] /// The error context length. Non-zero length makes an error thrown from /// the XML parser with line/column location repackaged with a context /// around that location of specified length. For example, if an error was /// thrown indicating that there's an unexpected character at line 3, column /// 15 with `errorContextLength` set to 10, a new error type is rethrown /// containing 5 characters before column 15 and 5 characters after, all on /// line 3. Line wrapping should be handled correctly too as the context can /// span more than a few lines. open var errorContextLength: UInt = 0 /** A boolean value that determines whether the parser reports the namespaces and qualified names of elements. The default value is `false`. */ open var shouldProcessNamespaces: Bool = false /** A boolean value that determines whether the parser trims whitespaces and newlines from the end and the beginning of string values. The default value is `true`. */ open var trimValueWhitespaces: Bool /// Options set on the top-level encoder to pass down the decoding hierarchy. struct Options { let dateDecodingStrategy: DateDecodingStrategy let dataDecodingStrategy: DataDecodingStrategy let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy let keyDecodingStrategy: KeyDecodingStrategy let nodeDecodingStrategy: NodeDecodingStrategy let userInfo: [CodingUserInfoKey: Any] } /// The options set on the top-level decoder. var options: Options { return Options( dateDecodingStrategy: dateDecodingStrategy, dataDecodingStrategy: dataDecodingStrategy, nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy, keyDecodingStrategy: keyDecodingStrategy, nodeDecodingStrategy: nodeDecodingStrategy, userInfo: userInfo ) } // MARK: - Constructing a XML Decoder /// Initializes `self` with default strategies. public init(trimValueWhitespaces: Bool = true) { self.trimValueWhitespaces = trimValueWhitespaces } // MARK: - Decoding Values /// Decodes a top-level box of the given type from the given XML representation. /// /// - parameter type: The type of the box to decode. /// - parameter data: The data to decode from. /// - returns: A box of the requested type. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid XML. /// - throws: An error if any box throws an error during decoding. open func decode<T: Decodable>( _ type: T.Type, from data: Data ) throws -> T { let topLevel: Box = try XMLStackParser.parse( with: data, errorContextLength: errorContextLength, shouldProcessNamespaces: shouldProcessNamespaces, trimValueWhitespaces: trimValueWhitespaces ) let decoder = XMLDecoderImplementation( referencing: topLevel, options: options, nodeDecodings: [] ) decoder.nodeDecodings = [ options.nodeDecodingStrategy.nodeDecodings( forType: T.self, with: decoder ), ] defer { _ = decoder.nodeDecodings.removeLast() } return try decoder.unbox(topLevel) } } // MARK: TopLevelDecoder #if canImport(Combine) import protocol Combine.TopLevelDecoder import protocol Combine.TopLevelEncoder #elseif canImport(OpenCombine) import protocol OpenCombine.TopLevelDecoder import protocol OpenCombine.TopLevelEncoder #endif #if canImport(Combine) || canImport(OpenCombine) extension XMLDecoder: TopLevelDecoder {} extension XMLEncoder: TopLevelEncoder {} #endif
41.717224
143
0.618992
642b8665cf13dd80d52e4fa20b1f57bea182718c
24,199
// Copyright 2019 Google LLC // // 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 Foundation import libsocket /// Module for synchronizing over the network. /// /// This module implementes a simple TCP-based protocol /// to exchange programs and statistics between fuzzer /// instances. /// /// The protocol consists of messages of the following /// format being sent between the parties. Messages are /// sent in both directions and are not answered. /// Messages are padded with zero bytes to the next /// multiple of four. The message length includes the /// size of the header but excludes any padding bytes. /// /// +----------------------+----------------------+------------------+-----------+ /// | length | type | payload | padding | /// | 4 byte little endian | 4 byte little endian | length - 8 bytes | | /// +----------------------+----------------------+------------------+-----------+ /// /// TODO: add some kind of compression, encryption, and authentication... /// Supported message types. enum MessageType: UInt32 { // A simple ping message to keep the TCP connection alive. case keepalive = 0 // Informs the other side that the sender is terminating. case shutdown = 1 // Send by workers after connecting. Identifies a worker through a UUID. case identify = 2 // A synchronization packet sent by a master to a newly connected worker. // Contains the exported state of the master so the worker can // synchronize itself with that. case sync = 3 // A FuzzIL program that is interesting and should be imported by the receiver. case program = 4 // A crashing program that is sent from a worker to a master. case crash = 5 // A statistics package send by a worker to a master. case statistics = 6 /// Log messages are forwarded from workers to masters. case log = 7 } /// Payload of an identification message. fileprivate struct Identification: Codable { // The UUID of the worker let workerId: UUID } /// Payload of a log message. fileprivate struct LogMessage: Codable { let creator: UUID let level: Int let label: String let content: String } fileprivate let messageHeaderSize = 8 fileprivate let maxMessageSize = 1024 * 1024 * 1024 /// Protocol for an object capable of receiving messages. protocol MessageHandler { func handleMessage(_ payload: Data, ofType type: MessageType, from connection: Connection) func handleError(on connection: Connection) } /// A connection to a network peer that speaks the above protocol. class Connection { /// File descriptor of the socket. let socket: Int32 /// Logger for this connection. private let logger: Logger /// Message handler to which incoming messages are delivered. private let handler: MessageHandler /// OperationQueue on which messages will be received and handlers invoked. private let queue: OperationQueue /// DispatchSource to trigger when data is available. private var readSource: OperationSource? = nil /// DispatchSource to trigger when data can be sent. private var writeSource: OperationSource? = nil /// Buffer for incoming messages. private var currentMessageData = Data() /// Buffer to receive incoming data into. private var receiveBuffer = [UInt8](repeating: 0, count: 1024 * 1024) /// Pending outgoing data. private var sendQueue: [Data] = [] init(socket: Int32, handler: MessageHandler, fuzzer: Fuzzer) { self.socket = socket self.handler = handler self.logger = fuzzer.makeLogger(withLabel: "Connection \(socket)") self.queue = fuzzer.queue self.readSource = OperationSource.forReading(from: socket, on: fuzzer.queue) { [weak self] in self?.handleDataAvailable() } } deinit { libsocket.socket_close(socket) } func close() { readSource?.cancel() writeSource?.cancel() } /// Send a message. /// /// This will either send the message immediately or queue for delivery /// once the remote peer can accept more data. func sendMessage(_ data: Data, ofType type: MessageType) { guard data.count + messageHeaderSize <= maxMessageSize else { return logger.error("Message too large to be sent (\(data.count + messageHeaderSize)B). Discarding") } var length = UInt32(data.count + messageHeaderSize).littleEndian var type = type.rawValue.littleEndian let padding = Data(repeating: 0, count: self.paddingLength(for: Int(length))) // We are careful not to copy the passed data here self.sendQueue.append(Data(bytes: &length, count: 4)) self.sendQueue.append(Data(bytes: &type, count: 4)) self.sendQueue.append(data) self.sendQueue.append(padding) self.sendPendingData() } private func sendPendingData() { var i = 0 while i < sendQueue.count { let chunk = sendQueue[i] let length = chunk.count let startIndex = chunk.startIndex let rv = chunk.withUnsafeBytes { content -> Int in return libsocket.socket_send(socket, content.bindMemory(to: UInt8.self).baseAddress, length) } if rv < 0 { // Network error. We'll notify our client through handleDataAvailable though. // That way we can deliver any data that's still pending at this point. // Note (probably) this doesn't work correctly if the remote end just closes // the socket in one direction, but that shouldn't happen in our implementation ... sendQueue.removeAll() writeSource?.cancel() return } else if rv != length { assert(rv < length) // Only managed to send part of the data. Requeue the rest. let newStart = startIndex.advanced(by: rv) sendQueue[i] = chunk[newStart...] break } i += 1 } // Remove all chunks that were successfully sent sendQueue.removeFirst(i) // If we were able to sent all chunks, remove the writer source if sendQueue.isEmpty { writeSource?.cancel() writeSource = nil } else if writeSource == nil { // Otherwise ensure we have an active write source to notify us when the next chunk can be sent self.writeSource = OperationSource.forWriting(to: socket, on: queue) { [weak self] in self?.sendPendingData() } } } private func handleDataAvailable() { // Receive all available data var receivedData = Data() while true { let bytesRead = read(socket, UnsafeMutablePointer<UInt8>(&receiveBuffer), receiveBuffer.count) guard bytesRead > 0 else { break } receivedData.append(UnsafeMutablePointer<UInt8>(&receiveBuffer), count: Int(bytesRead)) } guard receivedData.count > 0 else { // We got a read event but no data was available so the remote end must have closed the connection. return error() } currentMessageData.append(receivedData) // ... and process it while currentMessageData.count >= messageHeaderSize { let length = Int(readUint32(from: currentMessageData, atOffset: 0)) guard length <= maxMessageSize && length >= messageHeaderSize else { // For now we just close the connection if an invalid message is received. logger.warning("Received message with invalid length. Closing connection.") return error() } let totalMessageLength = length + paddingLength(for: length) guard totalMessageLength <= currentMessageData.count else { // Not enough data available right now. Wait until next packet is received. break } let message = Data(currentMessageData.prefix(length)) // Explicitely make a copy of the data here so the discarded data is also freed from memory currentMessageData = currentMessageData.subdata(in: totalMessageLength..<currentMessageData.count) let type = readUint32(from: message, atOffset: 4) if let type = MessageType(rawValue: type) { let payload = message.suffix(from: messageHeaderSize) handler.handleMessage(payload, ofType: type, from: self) } else { logger.warning("Received message with invalid type. Closing connection.") return error() } } } // Handle an error: close our connection and inform our handler. private func error() { close() handler.handleError(on: self) } // Helper function to unpack a little-endian, 32-bit unsigned integer from a data packet. private func readUint32(from data: Data, atOffset offset: Int) -> UInt32 { assert(offset >= 0 && data.count >= offset + 4) let value = data.withUnsafeBytes { $0.load(fromByteOffset: offset, as: UInt32.self) } return UInt32(littleEndian: value) } // Compute the number of padding bytes for the given message size. private func paddingLength(for messageSize: Int) -> Int { let remainder = messageSize % 4 return remainder == 0 ? 0 : 4 - remainder } } public class NetworkMaster: Module, MessageHandler { /// File descriptor of the server socket. private var serverFd: Int32 = -1 /// Associated fuzzer. private unowned let fuzzer: Fuzzer /// Logger for this module. private let logger: Logger /// Address and port on which the master listens. let address: String let port: UInt16 /// Operation source to trigger when a new client connection is available. private var connectionSource: OperationSource? = nil /// Active workers. The key is the socket filedescriptor number. private var workers = [Int32: Worker]() /// Since fuzzer state can grow quite large (> 100MB) and takes long to serialize, /// we cache the serialized state for a short time. private var cachedState = Data() private var cachedStateCreationTime = Date.distantPast public init(for fuzzer: Fuzzer, address: String, port: UInt16) { self.fuzzer = fuzzer self.logger = fuzzer.makeLogger(withLabel: "NetworkMaster") self.address = address self.port = port } public func initialize(with fuzzer: Fuzzer) { self.serverFd = libsocket.socket_listen(address, port) guard serverFd > 0 else { logger.fatal("Failed to open server socket") } connectionSource = OperationSource.forReading(from: serverFd, on: fuzzer.queue, block: handleNewConnection) logger.info("Accepting worker connections on \(address):\(port)") fuzzer.events.Shutdown.observe { for worker in self.workers.values { worker.conn.sendMessage(Data(), ofType: .shutdown) } } // Only start sending interesting programs after a short delay to not spam the workers too much. fuzzer.timers.runAfter(10 * Minutes) { fuzzer.events.InterestingProgramFound.observe { ev in let encoder = JSONEncoder() let data = try! encoder.encode(ev.program) for worker in self.workers.values { worker.conn.sendMessage(data, ofType: .program) } } } // Regularly send keepalive messages. fuzzer.timers.scheduleTask(every: 1 * Minutes) { for worker in self.workers.values { worker.conn.sendMessage(Data(), ofType: .keepalive) } } } func handleNewConnection() { let clientFd = libsocket.socket_accept(serverFd) guard clientFd > 0 else { return logger.error("Failed to accept client connection") } let worker = Worker(conn: Connection(socket: clientFd, handler: self, fuzzer: fuzzer), id: nil, connectionTime: Date()) workers[clientFd] = worker // TODO should have some address information here. logger.info("New worker connected") } func handleMessage(_ payload: Data, ofType type: MessageType, from connection: Connection) { if let worker = workers[connection.socket] { handleMessageInternal(payload, ofType: type, from: worker) } } private func handleMessageInternal(_ payload: Data, ofType type: MessageType, from worker: Worker) { let decoder = JSONDecoder() // Workers must identify themselves first. if type != .identify && worker.id == nil { logger.warning("Received message from unidentified worker. Closing connection...") return disconnect(worker) } switch type { case .keepalive: break case .shutdown: if let id = worker.id { logger.info("Worker \(id) disconnected") } disconnect(worker) case .identify: if let msg = try? decoder.decode(Identification.self, from: payload) { if worker.id != nil { logger.warning("Received multiple identification messages from client. Ignoring message") break } workers[worker.conn.socket] = Worker(conn: worker.conn, id: msg.workerId, connectionTime: worker.connectionTime) logger.info("Worker identified as \(msg.workerId)") fuzzer.events.WorkerConnected.dispatch(with: msg.workerId) // Send our fuzzing state to the worker let now = Date() if cachedState.isEmpty || now.timeIntervalSince(cachedStateCreationTime) > 15 * Minutes { // No cached state or it is too old let state = fuzzer.exportState() let encoder = JSONEncoder() let (data, duration) = measureTime { try! encoder.encode(state) } logger.info("Encoding fuzzer state took \((String(format: "%.2f", duration)))s. Data size: \(ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: .memory))") cachedState = data cachedStateCreationTime = now } worker.conn.sendMessage(cachedState, ofType: .sync) } else { logger.warning("Received malformed identification message from worker") } case .crash: if let program = try? decoder.decode(Program.self, from: payload) { fuzzer.importCrash(program) } else { logger.warning("Received malformed program from worker") } case .program: if let program = try? decoder.decode(Program.self, from: payload) { fuzzer.importProgram(program) } else { logger.warning("Received malformed program from worker") } case .statistics: let decoder = JSONDecoder() if let data = try? decoder.decode(Statistics.Data.self, from: payload) { if let stats = Statistics.instance(for: fuzzer) { stats.importData(data, from: worker.id!) } } else { logger.warning("Received malformed statistics update from worker") } case .log: let decoder = JSONDecoder() if let msg = try? decoder.decode(LogMessage.self, from: payload), let level = LogLevel(rawValue: msg.level) { fuzzer.events.Log.dispatch(with: (creator: msg.creator, level: level, label: msg.label, message: msg.content)) } else { logger.warning("Received malformed log message data from worker") } default: logger.warning("Received unexpected packet from worker") } } func handleError(on connection: Connection) { if let worker = workers[connection.socket] { if let id = worker.id { let activeSeconds = Int(-worker.connectionTime.timeIntervalSinceNow) let activeMinutes = activeSeconds / 60 let activeHours = activeMinutes / 60 logger.warning("Lost connection to worker \(id). Worker was active for \(activeHours)h \(activeMinutes % 60)m \(activeSeconds % 60)s") } disconnect(worker) } } private func disconnect(_ worker: Worker) { worker.conn.close() if let id = worker.id { // If the id is nil then the worker never registered, so no need to deregister it internally fuzzer.events.WorkerDisconnected.dispatch(with: id) } workers.removeValue(forKey: worker.conn.socket) } struct Worker { // The network connection to the worker. let conn: Connection // The id of the worker. let id: UUID? // The time the worker connected. let connectionTime: Date } } public class NetworkWorker: Module, MessageHandler { /// Associated fuzzer. private unowned let fuzzer: Fuzzer /// Logger for this module. private let logger: Logger /// Hostname of the master instance. let masterHostname: String /// Port of the master instance. let masterPort: UInt16 /// Indicates whether the corpus has been synchronized with the master yet. private var synchronized = false /// Number of programs already imported from the master. private var syncPosition = 0 /// Used when receiving a shutdown message from the master to avoid sending it further data. private var masterIsShuttingDown = false /// Connection to the master instance. private var conn: Connection! = nil public init(for fuzzer: Fuzzer, hostname: String, port: UInt16) { self.fuzzer = fuzzer self.logger = fuzzer.makeLogger(withLabel: "NetworkWorker") self.masterHostname = hostname self.masterPort = port } public func initialize(with fuzzer: Fuzzer) { connect() fuzzer.events.CrashFound.observe { ev in self.sendProgram(ev.program, type: .crash) } fuzzer.events.Shutdown.observe { if !self.masterIsShuttingDown { self.conn.sendMessage(Data(), ofType: .shutdown) } } fuzzer.events.InterestingProgramFound.observe { ev in if self.synchronized { self.sendProgram(ev.program, type: .program) } } // Regularly send local statistics to the master. if let stats = Statistics.instance(for: fuzzer) { fuzzer.timers.scheduleTask(every: 1 * Minutes) { let encoder = JSONEncoder() let data = stats.compute() if let payload = try? encoder.encode(data) { self.conn.sendMessage(payload, ofType: .statistics) } } } // Forward log events to the master. fuzzer.events.Log.observe { ev in let msg = LogMessage(creator: ev.creator, level: ev.level.rawValue, label: ev.label, content: ev.message) let encoder = JSONEncoder() let payload = try! encoder.encode(msg) self.conn.sendMessage(payload, ofType: .log) } // Set a timeout for synchronization. fuzzer.timers.runAfter(60 * Minutes) { if !self.synchronized { self.logger.error("Synchronization with master timed out. Continuing without synchronizing...") self.synchronized = true } } } func handleMessage(_ payload: Data, ofType type: MessageType, from connection: Connection) { let decoder = JSONDecoder() switch type { case .keepalive: break case .shutdown: logger.info("Master is shutting down. Stopping this worker...") masterIsShuttingDown = true self.fuzzer.stop() case .program: if let program = try? decoder.decode(Program.self, from: payload) { fuzzer.importProgram(program, withDropout: true) } else { logger.error("Received malformed program from master") } case .sync: let decoder = JSONDecoder() let (maybeState, duration) = measureTime { try? decoder.decode(Fuzzer.State.self, from: payload) } if let state = maybeState { logger.info("Decoding fuzzer state took \((String(format: "%.2f", duration)))s") do { try fuzzer.importState(state) logger.info("Synchronized with master. Corpus contains \(fuzzer.corpus.size) programs") } catch { logger.error("Failed to import state from master: \(error.localizedDescription)") } } else { logger.error("Received malformed sync packet from master") } synchronized = true default: logger.warning("Received unexpected packet from master") } } func handleError(on connection: Connection) { logger.warning("Trying to reconnect to master after connection error") connect() } private func connect() { var fd: Int32 = -1 for _ in 0..<10 { fd = libsocket.socket_connect(masterHostname, masterPort) if fd >= 0 { break } else { logger.warning("Failed to connect to master. Retrying in 30 seconds") sleep(30) } } if fd < 0 { logger.fatal("Failed to connect to master") } logger.info("Connected to master, our id: \(fuzzer.id)") conn = Connection(socket: fd, handler: self, fuzzer: fuzzer) // Identify ourselves. let encoder = JSONEncoder() let msg = Identification(workerId: fuzzer.id) let payload = try! encoder.encode(msg) conn.sendMessage(payload, ofType: .identify) } private func sendProgram(_ program: Program, type: MessageType) { assert(type == .program || type == .crash) let encoder = JSONEncoder() let payload = try! encoder.encode(program) conn.sendMessage(payload, ofType: type) } }
38.048742
196
0.586347
3ad71ef7fc640274819b818aef245a934b702979
1,749
// // ARDebugStepBoundingBoxView.swift // UserModuleFramework // // Created by fincher on 4/13/21. // import SwiftUI struct ARDebugStepRemoveBgAndRigView: View { @EnvironmentObject var environment: DataEnvironment @State var waiting: Bool = false var body: some View { ScrollView(.vertical, showsIndicators: true, content: { VStack(alignment: .leading, spacing: 8, content: { Text("Pair skeleton with scanned point cloud") .font(.subheadline) Text("Now you can ask your buddy to walk away from the original position as all information are now caputred. The next step needs a while so hang tight (ask your buddy to join you and see what you have scanned)!") .font(.caption) Text("Double check that the skeleton is matched with the human point cloud. Then press next and wait for half a minute. Your iPad will now remove the background from the static scanned model and pair skeleton joints with it so it can be dynamic.") .font(.caption) Button(action: { waiting = true OperationManager.shared.goTo(mode: .animateSkeleton) { waiting = false } }, label: { FilledButtonView(icon: "", text: (waiting ? "Processing" : "Next"), color: Color.accentColor, shadow: false, primary: true) }) .disabled(waiting) }) .padding(.horizontal) }) } } struct ARDebugStepRemoveBgAndRigView_Previews: PreviewProvider { static var previews: some View { ARDebugStepRemoveBgAndRigView() } }
40.674419
263
0.598056
e4db317dc6c8f24b02d58bf278541ab1c6f213f5
896
// // EmptyStateView.swift // // Created on 5/18/20. // Copyright © 2020 WildAid. All rights reserved. // import SwiftUI struct EmptyStateView: View { var searchWord = "" private enum Dimensions { static let spacing: CGFloat = 32.0 static let imageSize: CGFloat = 100.0 static let topPadding: CGFloat = 40.0 } var body: some View { VStack(spacing: Dimensions.spacing) { Image(systemName: "magnifyingglass") .font(.system(size: Dimensions.imageSize)) .foregroundColor(Color.iconsGray) Text("No Results for “\(searchWord)“") .font(Font.title3.weight(.semibold)) } .padding(.top, Dimensions.topPadding) } } struct EmptyStateView_Previews: PreviewProvider { static var previews: some View { EmptyStateView(searchWord: "Predat") } }
24.888889
58
0.608259
d7ae80d1c4ef9946000c125831024ee5a3c2fe37
2,737
// // CircularProgressView.swift // GrabShuttle // // Created by Navnit Baldha on 06/06/20. // Copyright © 2020 Navneet Baldha. All rights reserved. // import UIKit class CircularProgressView: UIView { // MARK: - Properties var progressLayer: CAShapeLayer! var trackLayer: CAShapeLayer! var pulsatingLayer: CAShapeLayer! // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) configureCircleLayers() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Helper Functions private func configureCircleLayers() { pulsatingLayer = circleShapeLayer(strokeColor: .clear, fillColor: .rgb(red: 86, green: 30, blue: 63)) layer.addSublayer(pulsatingLayer) trackLayer = circleShapeLayer(strokeColor: .rgb(red: 56, green: 25, blue: 49), fillColor: .clear) layer.addSublayer(trackLayer) progressLayer = circleShapeLayer(strokeColor: .rgb(red: 234, green: 46, blue: 111), fillColor: .clear) layer.addSublayer(progressLayer) } private func circleShapeLayer(strokeColor: UIColor, fillColor: UIColor) -> CAShapeLayer { let layer = CAShapeLayer() let circularPath = UIBezierPath(arcCenter: .zero, radius: self.frame.width / 2, startAngle: -0.5 * .pi, endAngle: 1.5 * .pi, clockwise: true) layer.path = circularPath.cgPath layer.strokeColor = strokeColor.cgColor layer.lineWidth = 12 layer.fillColor = fillColor.cgColor layer.lineCap = .round layer.position = center return layer } func animatePulsatingLayer() { let animation = CABasicAnimation(keyPath: "transform.scale") animation.toValue = 1.25 animation.duration = 1 animation.timingFunction = CAMediaTimingFunction(name: .easeOut) animation.autoreverses = true animation.repeatCount = Float.infinity pulsatingLayer.add(animation, forKey: "pulsing") } func animateProgress(duration: TimeInterval, completion: @escaping() -> Void) { animatePulsatingLayer() CATransaction.begin() CATransaction.setCompletionBlock(completion) let animation = CABasicAnimation(keyPath: "strokeEnd") animation.duration = duration animation.fromValue = 1 animation.toValue = 0 animation.timingFunction = CAMediaTimingFunction(name: .linear) progressLayer.strokeEnd = 0 progressLayer.add(animation, forKey: "progress") CATransaction.commit() } }
31.102273
149
0.635002
bbf586bf92ee472272ec3ae8f396165f19e04584
111
import Foundation import CoreGraphics public protocol CFValueConvertible { var cfValue: AnyObject { get } }
15.857143
36
0.792793
f7c5cf10cae7bcd2bdf71db1c300092df678ed1b
288
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } }
28.8
144
0.767361
9ba9364a1241bfdbdd356121dbaf19b100047e96
10,615
import Eureka import FirebaseInstallations import FirebaseMessaging import PromiseKit import RealmSwift import Shared import UIKit class NotificationSettingsViewController: FormViewController { public var doneButton: Bool = false private var observerTokens: [Any] = [] deinit { for token in observerTokens { NotificationCenter.default.removeObserver(token) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if doneButton { navigationItem.rightBarButtonItem = nil doneButton = false } } override func viewDidLoad() { super.viewDidLoad() if doneButton { let doneButton = UIBarButtonItem( barButtonSystemItem: .done, target: self, action: #selector(closeSettingsDetailView(_:)) ) navigationItem.setRightBarButton(doneButton, animated: true) } title = L10n.SettingsDetails.Notifications.title form +++ Section() <<< notificationPermissionRow() +++ Section( footer: L10n.SettingsDetails.Notifications.Categories.footer ) <<< ButtonRow { $0.title = L10n.SettingsDetails.Notifications.Categories.header $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { NotificationCategoryListViewController() }, onDismiss: { vc in _ = vc.navigationController?.popViewController(animated: true) }) } +++ Section( footer: L10n.SettingsDetails.Notifications.Sounds.footer ) <<< ButtonRow { $0.title = L10n.SettingsDetails.Notifications.Sounds.title $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { NotificationSoundsViewController() }, onDismiss: nil) } +++ ButtonRow { $0.title = L10n.SettingsDetails.Notifications.BadgeSection.Button.title $0.onCellSelection { cell, _ in UIApplication.shared.applicationIconBadgeNumber = 0 let title = L10n.SettingsDetails.Notifications.BadgeSection.ResetAlert.title let message = L10n.SettingsDetails.Notifications.BadgeSection.ResetAlert.message let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: L10n.okLabel, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.sourceView = cell.formViewController()?.view } } +++ Section( header: L10n.debugSectionLabel, footer: nil ) <<< ButtonRowOf<Int> { row in let value = NotificationRateLimitListViewController.newPromise() row.cellStyle = .value1 func update(for response: RateLimitResponse) { row.value = response.rateLimits.remaining row.updateCell() } value.done { response in update(for: response) }.cauterize() row.title = L10n.SettingsDetails.Notifications.RateLimits.header row.presentationMode = .show(controllerProvider: ControllerProvider.callback { let controller = NotificationRateLimitListViewController(initialPromise: value) controller.rateLimitDidChange = { rateLimit in update(for: rateLimit) } return controller }, onDismiss: nil) row.displayValueFor = { value in value.map { NumberFormatter.localizedString( from: NSNumber(value: $0), number: .decimal ) } } } <<< ButtonRow { $0.title = L10n.SettingsDetails.Location.Notifications.header $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { NotificationDebugNotificationsViewController() }, onDismiss: nil) } <<< LabelRow("pushID") { $0.title = L10n.SettingsDetails.Notifications.PushIdSection.header if let pushID = Current.settingsStore.pushID { $0.value = pushID } else { $0.value = L10n.SettingsDetails.Notifications.PushIdSection.notRegistered } $0.cellSetup { cell, _ in cell.detailTextLabel?.lineBreakMode = .byTruncatingMiddle } $0.cellUpdate { cell, _ in cell.selectionStyle = .default } $0.onCellSelection { [weak self] cell, row in guard let id = Current.settingsStore.pushID else { return } let vc = UIActivityViewController(activityItems: [id], applicationActivities: nil) with(vc.popoverPresentationController) { $0?.sourceView = cell $0?.sourceRect = cell.bounds } self?.present(vc, animated: true, completion: nil) row.deselect(animated: true) } } <<< ButtonRow { $0.tag = "resetPushID" $0.title = L10n.Settings.ResetSection.ResetRow.title }.cellUpdate { cell, _ in cell.textLabel?.textColor = .red }.onCellSelection { cell, _ in Current.Log.verbose("Resetting push token!") firstly { self.resetInstanceID() }.done { token in Current.settingsStore.pushID = token guard let idRow = self.form.rowBy(tag: "pushID") as? LabelRow else { return } idRow.value = token idRow.updateCell() }.then { _ in Current.api.then(on: nil) { $0.Connect(reason: .periodic) } }.catch { error in Current.Log.error("Error resetting push token: \(error)") let alert = UIAlertController( title: L10n.errorLabel, message: error.localizedDescription, preferredStyle: .alert ) alert.addAction(UIAlertAction(title: L10n.okLabel, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.sourceView = cell.formViewController()?.view } } } @objc func closeSettingsDetailView(_ sender: UIButton) { dismiss(animated: true, completion: nil) } func deleteInstanceID() -> Promise<Void> { Promise { seal in Messaging.messaging().deleteToken(completion: seal.resolve) } } func createInstanceID() -> Promise<String> { Promise { seal in Messaging.messaging().token(completion: seal.resolve) } } func resetInstanceID() -> Promise<String> { firstly { self.deleteInstanceID() }.then { _ in self.createInstanceID() } } private func notificationPermissionRow() -> BaseRow { var lastPermissionSeen: UNAuthorizationStatus? func update(_ row: LabelRow) { UNUserNotificationCenter.current().getNotificationSettings { settings in DispatchQueue.main.async { lastPermissionSeen = settings.authorizationStatus row.value = { switch settings.authorizationStatus { #if compiler(>=5.3) case .ephemeral: return L10n.SettingsDetails.Notifications.Permission.enabled #endif case .authorized, .provisional: return L10n.SettingsDetails.Notifications.Permission.enabled case .denied: return L10n.SettingsDetails.Notifications.Permission.disabled case .notDetermined: return L10n.SettingsDetails.Notifications.Permission.needsRequest @unknown default: return L10n.SettingsDetails.Notifications.Permission.disabled } }() row.updateCell() } } } return LabelRow { row in row.title = L10n.SettingsDetails.Notifications.Permission.title update(row) observerTokens.append(NotificationCenter.default.addObserver( forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main ) { _ in // in case the user jumps to settings and changes while we're open, update the value update(row) }) row.cellUpdate { cell, _ in cell.accessoryType = .disclosureIndicator cell.selectionStyle = .default } row.onCellSelection { _, row in UNUserNotificationCenter.current().requestAuthorization(options: .defaultOptions) { _, _ in DispatchQueue.main.async { update(row) row.deselect(animated: true) if lastPermissionSeen != .notDetermined { // if we weren't prompting for permission with this request, open settings // we can't avoid the request code-path since getting settings is async UIApplication.shared.openSettings(destination: .notification) } } } } } } }
38.183453
107
0.526048
ddadbae8da3c5b246b082281727d5904f6e3205f
825
// swift-tools-version:5.5 import PackageDescription let package = Package( name: "swift-aws-lambda-runtime-example", platforms: [ .macOS(.v12), ], products: [ .executable(name: "MyLambda", targets: ["MyLambda"]), ], dependencies: [ // this is the dependency on the swift-aws-lambda-runtime library // in real-world projects this would say // .package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", from: "1.0.0") .package(name: "swift-aws-lambda-runtime", path: "../.."), ], targets: [ .executableTarget( name: "MyLambda", dependencies: [ .product(name: "AWSLambdaRuntimeCore", package: "swift-aws-lambda-runtime"), ], path: "." ), ] )
28.448276
103
0.558788
08e99da0e2e3224fb787d02996676909a0bf4487
2,353
// // SceneDelegate.swift // swift-demo-project-pod // // Created by kingcos on 2019/11/4. // Copyright © 2019 kingcos. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.574074
147
0.713557
f91b66b0ad563494a7d552be39bca16e739a130c
7,830
// // OperationsViewController.swift // MoneyM // // Created by Савелий Никулин on 15.01.2022. // import UIKit protocol DisplayOperations { func displayOperation(viewModel: OperationsModel.Operations.ViewModel) func displayStatistics(viewModel: OperationsModel.Statistics.ViewModel) func deletedOperation(viewModel: OperationsModel.DeleteOperation.ViewModel) } class OperationsViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var balanceTitleLabel: UILabel! @IBOutlet weak var balanceValueLabel: UILabel! @IBOutlet weak var expenseTitleLabel: UILabel! @IBOutlet weak var expenseValueLabel: UILabel! @IBOutlet weak var incomeTitleLabel: UILabel! @IBOutlet weak var incomeValueLabel: UILabel! @IBOutlet weak var operationsTableView: UITableView! @IBOutlet weak var scrollViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var statusStackViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var newOperationButton: UIButton! @IBOutlet weak var expenseView: UIView! @IBOutlet weak var incomeView: UIView! @IBOutlet weak var balanceView: UIView! var interactor: OperationsBusinessLogic? var router: OperationNavigate? var accountViewController: AccountsViewController? public var account: AccountEntity? // MARK: - Private variables private var viewModel: OperationsModel.Operations.ViewModel? private let bottomMargin: CGFloat = 48 private(set) var categoryModel: CategoryModel! private var constants: Constants! private var currency: CurrencyModel.Model! override func viewDidLoad() { super.viewDidLoad() // CleanSwift setup setup() otherInit() updateStatistics() } // MARK: - Private functions private func setup() { guard let account = account else { return } let viewController = self let operationsInteractor = OperationsInteractor(account: account) let operationsPresenter = OperationsPresenter() let operationRouter = OperationsRouter() operationsInteractor.presenter = operationsPresenter operationsPresenter.viewController = viewController operationRouter.viewController = viewController interactor = operationsInteractor router = operationRouter } private func otherInit() { constants = Constants() categoryModel = CategoryModel() operationsTableView.delegate = self operationsTableView.dataSource = self fetchOperations() balanceValueLabel.font = constants.roundedFont(28) expenseValueLabel.font = constants.roundedFont(24) incomeValueLabel.font = constants.roundedFont(24) newOperationButton.titleLabel?.font = constants.roundedFont(20) dropShadowOf(view: expenseView) dropShadowOf(view: incomeView) dropShadowOf(view: balanceView) currency = getCurrency() balanceValueLabel.text = "0 $" incomeValueLabel.text = "0 $" expenseValueLabel.text = "0 $" newOperationButton.isEnabled = account != nil } private func getCurrency() -> CurrencyModel.Model? { guard let account = account else { return nil } let currencyModel = CurrencyModel() let result = currencyModel.currencyBy(id: Int(account.currencyID)) return result } private func dropShadowOf(view: UIView) { view.layer.masksToBounds = false view.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) view.layer.shadowOpacity = 0.1 view.layer.shadowRadius = 9 view.layer.shadowOffset = CGSize(width: 0, height: 0) } private func fetchOperations() { if let account = account { let request = OperationsModel.Operations.Request(account: account) interactor?.requestOperations(request: request) } } private func updateStatistics() { if let account = account { let request = OperationsModel.Statistics.Request(account: account) interactor?.requestStatistics(request: request) } } private func updateScrollViewHeight() { let tableViewContentHeight = operationsTableView.contentSize.height let height = tableViewContentHeight + statusStackViewHeightConstraint.constant + bottomMargin let viewHeight = view.frame.height - statusStackViewHeightConstraint.constant scrollViewHeightConstraint.constant = (scrollViewHeightConstraint.constant < viewHeight) ? view.frame.height - 80 : height } // MARK: - Actions @IBAction func newOperationButtonClicked(_ sender: Any) { router?.navigateToNewOperation() } } // MARK: - TableView delegate extension OperationsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewModel?.operations.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = operationsTableView.dequeueReusableCell(withIdentifier: "cell") as! UIOperationTableViewCell let operation = viewModel?.operations[indexPath.row] let categoryID = Int((operation?.operation.categoryID)!) let category = categoryModel.categoryBy(id: categoryID) ?? categoryModel.categoryUncategorized cell.categoryLabel.text = category?.title cell.iconLabel.text = category?.emojiIcon cell.amountLabel.text = (operation?.amountValue ?? "0") + " " + currency.symbol cell.amountLabel.textColor = operation?.amountColor cell.noteLabel.text = operation?.operation.note cell.amountLabel.font = constants.roundedFont(20) updateScrollViewHeight() return cell } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { true } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (action, view, complitionHandler) in if let account = self.account { let request = OperationsModel.DeleteOperation.Request(account: account, index: indexPath.row) self.interactor?.deleteOperation(request: request) self.operationsTableView.deleteRows(at: [indexPath], with: .automatic) self.updateStatistics() } } return UISwipeActionsConfiguration(actions: [deleteAction]) } } // MARK: - Display Operations extension OperationsViewController: DisplayOperations { func deletedOperation(viewModel: OperationsModel.DeleteOperation.ViewModel) { self.viewModel?.operations = viewModel.operations } func displayStatistics(viewModel: OperationsModel.Statistics.ViewModel) { balanceValueLabel.text = viewModel.balance + " " + currency.symbol balanceValueLabel.textColor = viewModel.balanceColor expenseValueLabel.text = viewModel.expense + " " + currency.symbol incomeValueLabel.text = viewModel.income + " " + currency.symbol } func displayOperation(viewModel: OperationsModel.Operations.ViewModel) { DispatchQueue.main.async { self.viewModel = viewModel self.operationsTableView.reloadData() } } } // MARK: - NewOperation Delegate extension OperationsViewController: NewOperationDelegate { func operationCreated() { fetchOperations() operationsTableView.reloadData() updateStatistics() accountViewController?.updateAccountsBalance() } }
30.115385
142
0.699234
280351739e963bd59278d4df65bfd3be946c431a
10,032
// // AHFMEpisodeListVC.swift // Pods // // Created by Andy Tong on 7/24/17. // // import UIKit import AHAudioPlayer import BundleExtension import SDWebImage private let CellID = "AHFMEpisodeListCellID" @objc public protocol AHFMEpisodeListVCDelegate: class { /// ["showId": 666] /// Call loadIntialShowid(_:) func AHFMEpisodeListVCShouldLoadInitialShowId(_ vc: UIViewController) /// Call loadShow(_:) func AHFMEpisodeListVC(_ vc: UIViewController, shouldLoadShow showId:Int) /// Call loadEpisode(_:episodeArr:) func AHFMEpisodeListVC(_ vc: UIViewController, shouldLoadEpisodes showId:Int) } struct Episode { var id: Int var showId: Int var remoteURL: String var title: String var duration: TimeInterval? var lastPlayedTime: TimeInterval? var isDownloaded: Bool? var localFilePath: String? init(_ dict: [String: Any]) { self.id = dict["id"] as! Int self.showId = dict["showId"] as! Int self.remoteURL = dict["remoteURL"] as! String self.title = dict["title"] as! String self.duration = dict["duration"] as? TimeInterval self.lastPlayedTime = dict["lastPlayedTime"] as? TimeInterval self.localFilePath = dict["localFilePath"] as? String self.isDownloaded = dict["isDownloaded"] as? Bool } public static func ==(lhs: Episode, rhs: Episode) -> Bool { return lhs.id == rhs.id } } struct Show { var id: Int var title: String var fullCover: String? init(_ dict: [String: Any]) { self.id = dict["id"] as! Int self.title = dict["title"] as! String self.fullCover = dict["fullCover"] as? String } public static func ==(lhs: Show, rhs: Show) -> Bool { return lhs.id == rhs.id } } public class AHFMEpisodeListVC: UIViewController { public var manager: AHFMEpisodeListVCDelegate? weak var tableView: UITableView! var bgImageView: UIImageView? var showId: Int? var show: Show? { didSet { if let show = show { headerLabel.text = show.title headerLabel.textColor = UIColor.white headerLabel.sizeToFit() headerLabel.frame.size.width = 300.0 headerLabel.textAlignment = .center headerLabel.center = CGPoint(x: self.headerView.bounds.width * 0.5, y: headerView.bounds.height * 0.7) } } } lazy var episodes = [Episode]() fileprivate var notificationhandlers = [NSObjectProtocol]() fileprivate var headerLabel = UILabel() fileprivate lazy var headerView = UIView() // key is indexPath.row, value is the episode's title height fileprivate var episodeTitleHeights = [CGFloat]() override public func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false setupBackground() setupTableView() setupHeader() let switchPlayHandler = NotificationCenter.default.addObserver(forName: AHAudioPlayerDidSwitchPlay, object: nil, queue: nil) {[weak self] (_) in guard self != nil else {return} self?.tableView.reloadData() } notificationhandlers.append(switchPlayHandler) } deinit { for handler in notificationhandlers { NotificationCenter.default.removeObserver(handler) } } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.manager?.AHFMEpisodeListVCShouldLoadInitialShowId(self) } public override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } } //MARK:- Loading Methods extension AHFMEpisodeListVC{ public func loadIntialShowid(_ showIdDict: [String: Any]) { guard let showId = showIdDict["showId"] as? Int else { return } self.showId = showId self.manager?.AHFMEpisodeListVC(self, shouldLoadShow: showId) } public func loadShow(_ data: [String:Any]?) { guard let data = data else { return } self.show = Show(data) let url = URL(string: self.show!.fullCover ?? "") bgImageView?.sd_setImage(with: url) self.manager?.AHFMEpisodeListVC(self, shouldLoadEpisodes: self.show!.id) } /// showIdDict = ["showId": 666] public func loadEpisodes(_ showIdDict: [String: Int], episodeArr: [[String:Any]]?) { guard let episodeArr = episodeArr else { return } guard episodeArr.count > 0 else { return } self.episodes.removeAll() for epDict in episodeArr { let ep = Episode(epDict) self.episodes.append(ep) } self.tableView.reloadData() } } //MARK:- Setups extension AHFMEpisodeListVC { func setupBackground() { bgImageView = UIImageView() bgImageView?.frame = self.view.bounds self.view.addSubview(bgImageView!) let blue = UIBlurEffect(style: .dark) let effectView = UIVisualEffectView(effect: blue) effectView.frame = self.view.bounds self.view.addSubview(effectView) } func setupTableView() { let tableView = UITableView() tableView.frame = self.view.bounds tableView.frame.origin.y = 64.0 tableView.contentInset.bottom = 64.0 tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = UIColor.clear // this line is to prevent extra separators in the bottom tableView.tableFooterView = UIView() tableView.estimatedRowHeight = 100.0 self.view.addSubview(tableView) self.tableView = tableView let bundle = Bundle.currentBundle(self) let nib = UINib(nibName: "\(AHFMEpisodeListCell.self)", bundle: bundle) tableView.register(nib, forCellReuseIdentifier: CellID) } func setupHeader() { // create headerView headerView.frame.origin.x = 0.0 headerView.frame.origin.y = 0.0 headerView.frame.size.width = self.view.bounds.width headerView.frame.size.height = 64.0 headerView.backgroundColor = UIColor.clear self.view.addSubview(headerView) // add title label headerView.addSubview(headerLabel) // add header bottom white separator let separator = UIView() separator.frame = CGRect(x: 0, y: headerView.bounds.height - 1, width: headerView.bounds.width, height: 1) separator.backgroundColor = UIColor.white.withAlphaComponent(0.5) headerView.addSubview(separator) // add right dismiss button let btn = UIButton(type: .custom) let img = UIImage(name: "dismiss-white", user: self) btn.setImage(img, for: .normal) btn.sizeToFit() btn.frame.origin.x = headerView.bounds.width - btn.frame.size.width - 8 - 8.0 btn.center.y = headerView.bounds.height * 0.7 btn.addTarget(self, action: #selector(dismiss(_:)), for: .touchUpInside) headerView.addSubview(btn) } func dismiss(_ button: UIButton) { self.dismiss(animated: true, completion: nil) } } //MARK:- TableView Delegate/DataSource extension AHFMEpisodeListVC: UITableViewDelegate, UITableViewDataSource { // MARK: - Table view data source public func numberOfSections(in tableView: UITableView) -> Int { return show == nil ? 0 : 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return episodes.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellID, for: indexPath) as! AHFMEpisodeListCell let episode = self.episodes[indexPath.row] cell.episode = episode cell.isPurchasedImg.isHidden = indexPath.row % 2 == 0 return cell } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard self.episodes.count > 0 else { print("episodes.count == 0") return } let ep = self.episodes[indexPath.row] if let playingTrackId = AHAudioPlayerManager.shared.playingTrackId,ep.id == playingTrackId { if self.navigationController == nil { self.dismiss(animated: true) }else{ self.navigationController?.popViewController(animated: true) } }else{ AHAudioPlayerManager.shared.stop() var url: URL? if ep.localFilePath != nil { url = URL(fileURLWithPath: ep.localFilePath!) }else{ url = URL(string: ep.remoteURL) } var toTime: TimeInterval? = nil if let lastPlayedTime = ep.lastPlayedTime, let duration = ep.duration, lastPlayedTime > 0.0, duration > 0.0{ toTime = lastPlayedTime } if self.navigationController == nil { self.dismiss(animated: true) { AHAudioPlayerManager.shared.play(trackId: ep.id, trackURL: url!, toTime: toTime) } }else{ self.navigationController?.popViewController(animated: true) AHAudioPlayerManager.shared.play(trackId: ep.id, trackURL: url!, toTime: toTime) } } } }
30.308157
152
0.603668
dd0970dac44e25246a5a63f69c7b0b1178341751
668
/* * Fetchable.swift * NYTimesArticles * * Created by Adham Alkhateeb on 10/2/19. * Copyright 2019 Adham Alkhateeb. All rights reserved. */ import Alamofire // MARK: - Type typealias NetworkCompletion = (_ data: Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void protocol Fetchable { func fetch(_ dataRequest: DataRequest, completion: @escaping NetworkCompletion) } extension Fetchable { func fetch(_ dataRequest: DataRequest, completion: @escaping NetworkCompletion) { dataRequest.responseString { responseString in completion(responseString.data, responseString.response, responseString.error) } } }
25.692308
100
0.717066
4abd9d1a9eadc00b958aa36e6ad8292711ce0593
26,500
// // UploadTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation import XCTest class UploadFileInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndFile() { // Given let urlString = "https://httpbin.org/" let imageURL = url(forResource: "rainbow", withExtension: "jpg") // When let request = Alamofire.upload(imageURL, to: urlString) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndFile() { // Given let urlString = "https://httpbin.org/" let headers = ["Authorization": "123456"] let imageURL = url(forResource: "rainbow", withExtension: "jpg") // When let request = Alamofire.upload(imageURL, to: urlString, method: .post, headers: headers) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadDataInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndData() { // Given let urlString = "https://httpbin.org/" // When let request = Alamofire.upload(Data(), to: urlString) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndData() { // Given let urlString = "https://httpbin.org/" let headers = ["Authorization": "123456"] // When let request = Alamofire.upload(Data(), to: urlString, headers: headers) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadStreamInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndStream() { // Given let urlString = "https://httpbin.org/" let imageURL = url(forResource: "rainbow", withExtension: "jpg") let imageStream = InputStream(url: imageURL)! // When let request = Alamofire.upload(imageStream, to: urlString) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndStream() { // Given let urlString = "https://httpbin.org/" let imageURL = url(forResource: "rainbow", withExtension: "jpg") let headers = ["Authorization": "123456"] let imageStream = InputStream(url: imageURL)! // When let request = Alamofire.upload(imageStream, to: urlString, headers: headers) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadDataTestCase: BaseTestCase { func testUploadDataRequest() { // Given let urlString = "https://httpbin.org/post" let data = "Lorem ipsum dolor sit amet".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(description: "Upload request should succeed: \(urlString)") var response: DefaultDataResponse? // When Alamofire.upload(data, to: urlString) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNil(response?.error) } func testUploadDataRequestWithProgress() { // Given let urlString = "https://httpbin.org/post" let data: Data = { var text = "" for _ in 1...3_000 { text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " } return text.data(using: String.Encoding.utf8, allowLossyConversion: false)! }() let expectation = self.expectation(description: "Bytes upload progress should be reported: \(urlString)") var uploadProgressValues: [Double] = [] var downloadProgressValues: [Double] = [] var response: DefaultDataResponse? // When Alamofire.upload(data, to: urlString) .uploadProgress { progress in uploadProgressValues.append(progress.fractionCompleted) } .downloadProgress { progress in downloadProgressValues.append(progress.fractionCompleted) } .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNil(response?.error) var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0 for progress in uploadProgressValues { XCTAssertGreaterThanOrEqual(progress, previousUploadProgress) previousUploadProgress = progress } if let lastProgressValue = uploadProgressValues.last { XCTAssertEqual(lastProgressValue, 1.0) } else { XCTFail("last item in uploadProgressValues should not be nil") } var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0 for progress in downloadProgressValues { XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress) previousDownloadProgress = progress } if let lastProgressValue = downloadProgressValues.last { XCTAssertEqual(lastProgressValue, 1.0) } else { XCTFail("last item in downloadProgressValues should not be nil") } } } // MARK: - class UploadMultipartFormDataTestCase: BaseTestCase { // MARK: Tests func testThatUploadingMultipartFormDataSetsContentTypeHeader() { // Given let urlString = "https://httpbin.org/post" let uploadData = "upload_data".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(description: "multipart form data upload should succeed") var formData: MultipartFormData? var response: DefaultDataResponse? // When Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(uploadData, withName: "upload_data") formData = multipartFormData }, to: urlString, encodingCompletion: { result in switch result { case .success(let upload, _, _): upload.response { resp in response = resp expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNil(response?.error) if let request = response?.request, let multipartFormData = formData, let contentType = request.value(forHTTPHeaderField: "Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType) } else { XCTFail("Content-Type header value should not be nil") } } func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() { // Given let urlString = "https://httpbin.org/post" let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(description: "multipart form data upload should succeed") var response: DefaultDataResponse? // When Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(frenchData, withName: "french") multipartFormData.append(japaneseData, withName: "japanese") }, to: urlString, encodingCompletion: { result in switch result { case .success(let upload, _, _): upload.response { resp in response = resp expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNil(response?.error) } func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() { executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false) } func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() { executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true) } func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() { // Given let urlString = "https://httpbin.org/post" let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(description: "multipart form data upload should succeed") var streamingFromDisk: Bool? var streamFileURL: URL? // When Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(frenchData, withName: "french") multipartFormData.append(japaneseData, withName: "japanese") }, to: urlString, encodingCompletion: { result in switch result { case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL): streamingFromDisk = uploadStreamingFromDisk streamFileURL = uploadStreamFileURL upload.response { _ in expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") XCTAssertNil(streamFileURL, "stream file URL should be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertFalse(streamingFromDisk, "streaming from disk should be false") } } func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() { // Given let urlString = "https://httpbin.org/post" let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(description: "multipart form data upload should succeed") var formData: MultipartFormData? var request: URLRequest? var streamingFromDisk: Bool? // When Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(uploadData, withName: "upload_data") formData = multipartFormData }, to: urlString, encodingCompletion: { result in switch result { case let .success(upload, uploadStreamingFromDisk, _): streamingFromDisk = uploadStreamingFromDisk upload.response { resp in request = resp.request expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertFalse(streamingFromDisk, "streaming from disk should be false") } if let request = request, let multipartFormData = formData, let contentType = request.value(forHTTPHeaderField: "Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() { // Given let urlString = "https://httpbin.org/post" let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(description: "multipart form data upload should succeed") var streamingFromDisk: Bool? var streamFileURL: URL? // When Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(frenchData, withName: "french") multipartFormData.append(japaneseData, withName: "japanese") }, usingThreshold: 0, to: urlString, encodingCompletion: { result in switch result { case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL): streamingFromDisk = uploadStreamingFromDisk streamFileURL = uploadStreamFileURL upload.response { _ in expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") XCTAssertNotNil(streamFileURL, "stream file URL should not be nil") if let streamingFromDisk = streamingFromDisk, let streamFilePath = streamFileURL?.path { XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") XCTAssertTrue( FileManager.default.fileExists(atPath: streamFilePath), "stream file path should exist" ) } } func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() { // Given let urlString = "https://httpbin.org/post" let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(description: "multipart form data upload should succeed") var formData: MultipartFormData? var request: URLRequest? var streamingFromDisk: Bool? // When Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(uploadData, withName: "upload_data") formData = multipartFormData }, usingThreshold: 0, to: urlString, encodingCompletion: { result in switch result { case let .success(upload, uploadStreamingFromDisk, _): streamingFromDisk = uploadStreamingFromDisk upload.response { resp in request = resp.request expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") } if let request = request, let multipartFormData = formData, let contentType = request.value(forHTTPHeaderField: "Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } // ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1 // func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() { // // Given // let manager: SessionManager = { // let identifier = "org.alamofire.uploadtests.\(UUID().uuidString)" // let configuration = URLSessionConfiguration.background(withIdentifier: identifier) // // return SessionManager(configuration: configuration, serverTrustPolicyManager: nil) // }() // // let urlString = "https://httpbin.org/post" // let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! // let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! // // let expectation = self.expectation(description: "multipart form data upload should succeed") // // var request: URLRequest? // var response: HTTPURLResponse? // var data: Data? // var error: Error? // var streamingFromDisk: Bool? // // // When // manager.upload( // multipartFormData: { multipartFormData in // multipartFormData.append(french, withName: "french") // multipartFormData.append(japanese, withName: "japanese") // }, // to: urlString, // withMethod: .post, // encodingCompletion: { result in // switch result { // case let .success(upload, uploadStreamingFromDisk, _): // streamingFromDisk = uploadStreamingFromDisk // // upload.response { responseRequest, responseResponse, responseData, responseError in // request = responseRequest // response = responseResponse // data = responseData // error = responseError // // expectation.fulfill() // } // case .failure: // expectation.fulfill() // } // } // ) // // waitForExpectations(timeout: timeout, handler: nil) // // // Then // XCTAssertNotNil(request, "request should not be nil") // XCTAssertNotNil(response, "response should not be nil") // XCTAssertNotNil(data, "data should not be nil") // XCTAssertNil(error, "error should be nil") // // if let streamingFromDisk = streamingFromDisk { // XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") // } else { // XCTFail("streaming from disk should not be nil") // } // } // MARK: Combined Test Execution private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) { // Given let urlString = "https://httpbin.org/post" let loremData1: Data = { var loremValues: [String] = [] for _ in 1...1_500 { loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") } return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)! }() let loremData2: Data = { var loremValues: [String] = [] for _ in 1...1_500 { loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.") } return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)! }() let expectation = self.expectation(description: "multipart form data upload should succeed") var uploadProgressValues: [Double] = [] var downloadProgressValues: [Double] = [] var response: DefaultDataResponse? // When Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(loremData1, withName: "lorem1") multipartFormData.append(loremData2, withName: "lorem2") }, usingThreshold: streamFromDisk ? 0 : 100_000_000, to: urlString, encodingCompletion: { result in switch result { case .success(let upload, _, _): upload .uploadProgress { progress in uploadProgressValues.append(progress.fractionCompleted) } .downloadProgress { progress in downloadProgressValues.append(progress.fractionCompleted) } .response { resp in response = resp expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNil(response?.error) var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0 for progress in uploadProgressValues { XCTAssertGreaterThanOrEqual(progress, previousUploadProgress) previousUploadProgress = progress } if let lastProgressValue = uploadProgressValues.last { XCTAssertEqual(lastProgressValue, 1.0) } else { XCTFail("last item in uploadProgressValues should not be nil") } var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0 for progress in downloadProgressValues { XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress) previousDownloadProgress = progress } if let lastProgressValue = downloadProgressValues.last { XCTAssertEqual(lastProgressValue, 1.0) } else { XCTFail("last item in downloadProgressValues should not be nil") } } }
38.129496
117
0.614264
2245c5b327b6df53d8d8c7fefe51743ba9f2a7ce
1,388
// // Copyright (c) 2016 Keun young Kim <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit let words: NSDictionary = ["A": "Apple", "B": "Banana", "C": "City"] let countOfWords = words.count if countOfWords > 0 { print("\(countOfWords) element(s)") } else { print("empty dictionary") } // 3 element(s)
40.823529
81
0.729827
8a82b4d4d5f1ca4d3f69db41386364af441125db
3,142
import Foundation /// Posiiton of text public struct ParserPosition: Equatable { /// line starting from 0 let row: Int /// column starting from 0 let col: Int } extension ParserPosition { /// initial position of a input text init() { self.row = 0 self.col = 0 } /// Increment column. /// This is line agnostic. It's upto the client to make sure /// that the line actually has this column func incrCol() -> ParserPosition { return ParserPosition(row: row, col: col + 1) } /// Increment row/line count. /// This is line agnostic. It's upto the client to make sure /// that the line actually has this row func incrRow() -> ParserPosition { return ParserPosition(row: row + 1, col: 0) } } /// Parser Input Representation public struct InputState { /// Lines from the source text public let lines: [String] /// Current cursror / parser position public let position: ParserPosition } extension InputState { public static var EOF: String { return "end of file" } public init(from str: String) { var l = str.split(separator: "\n", omittingEmptySubsequences: false).map { return $0.isEmpty ? "" : String($0) } if str.hasSuffix("\n") { // for each n separator there are n+1 splits. We dont need the last one. // If we have a trailing "\n", we dont need the empty subsequence after the end. _ = l.popLast() } lines = Array(l) position = ParserPosition() } public var currentLine: String { guard position.row < lines.count else { return InputState.EOF } return lines[position.row] } /// Retrieve the next character. /// /// three cases /// 1) if line >= maxLine -> /// return EOF /// 2) if col less than line length -> /// return char at colPos, increment colPos /// 3) if col at line length -> /// return NewLine, increment linePos public func nextChar() -> (InputState, Character?) { guard position.row < lines.count else { return (self, nil) } let thisLine = lines[position.row] if position.col < thisLine.count { let state = InputState(lines: lines, position: position.incrCol()) let char = thisLine[String.Index.init(encodedOffset: position.col)] return (state, char) } else /*can only be equal */{ let state = InputState(lines: lines, position: position.incrRow()) let char = Character("\n") return (state, char) } } } /// Represents the Position of parser /// Especially useful for error reporting public struct ParserErrorPosition: Equatable { let currentLine: String let row: Int let col: Int } extension InputState { func parserPosition() -> ParserErrorPosition { return ParserErrorPosition(currentLine: self.currentLine, row: self.position.row, col: self.position.col) } }
26.183333
113
0.590707
08ffdef454557bde95375210880a3e9c8acdd0da
1,198
// // LeetCode322.swift // LeetCodeProject // // Created by lmg on 2018/12/11. // Copyright © 2018 lmg. All rights reserved. // import UIKit /* 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 输入: coins = [1, 2, 5], amount = 11 输出: 3 解释: 11 = 5 + 5 + 1 输入: coins = [2], amount = 3 输出: -1 [1,2,5] 0 1 2 3 4 5 6 7 8 9 10 11 [0 0 0 0 0 0 0 0 0 0 0 0] [0 1 1 0 0 1 0 0 0 0 0 0] [0 1 1 2 0 1 2 0 0 0 0 0] i = [0 1 1 2 2 1 2 2 0 0 2 0] [0 1 1 2 2 1 2 2 3 3 2 3] */ class LeetCode322: NSObject { class func coinChange(_ coins: [Int], _ amount: Int) -> Int { if amount == 0 { return 0 } if amount < 0 { return -1 } var nums = [Int].init(repeating: -1, count: amount+1) nums[0] = 0 for i in 0..<amount { if nums[i] == -1 { continue } for j in 0..<coins.count{ let k = i + coins[j] if k <= amount && (nums[k] == -1 || nums[k] > nums[i] + 1) { nums[k] = nums[i] + 1 } } } return nums[amount] } }
23.038462
83
0.453255
1d7d5caf7c2fbfafebdd9c66035c4d788408dd78
2,132
// // CalcResultViewController.swift // BXIntent // // Created by Haizhen Lee on 11/15/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import BXIntent struct CalcResult: IntentResult{ let result: Double init(result: Double){ self.result = result } } class CalcResultViewController: UIViewController ,IntentForResultComponent { var requestCode: Int = 0 var intentResultDelegate: IntentResultDelegate? = nil private var intentExtras:[String:Any] = [:] func setExtras(_ extras: [String : Any]?) { self.intentExtras = extras ?? [:] } var resultValue: Double = 0 override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onDone)) navigationItem.rightBarButtonItem = doneItem let a = intentExtras["a"] as? Int ?? 0 let b = intentExtras["b"] as? Int ?? 0 resultValue = Double(a) * Double(b) let label = UILabel(frame: CGRect.zero) label.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(label) label.pac_center() label.font = UIFont.systemFont(ofSize: 18) label.textColor = .darkGray label.text = "\(a) * \(b) = \(resultValue)" } func onDone(sender:AnyObject){ dismiss(animated: true, completion: nil) let result = CalcResult(result: resultValue) intentResultDelegate?.onIntentResult(requestCode: requestCode, resultCode: .ok, result:result) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
28.810811
106
0.665103
1c876c9ccb83d6518504efb0553faf1567dddfc8
8,161
// // OPDSGroupTableViewCell.swift // r2-testapp-swift // // Created by Geoffrey Bugniot on 24/04/2018. // // Copyright 2018 European Digital Reading Lab. All rights reserved. // Licensed to the Readium Foundation under one or more contributor license agreements. // Use of this source code is governed by a BSD-style license which is detailed in the // LICENSE file present in the project repository where this source code is maintained. // import UIKit import R2Shared import Kingfisher class OPDSGroupTableViewCell: UITableViewCell { var group: Group? weak var opdsRootTableViewController: OPDSRootTableViewController? weak var collectionView: UICollectionView? var browsingState: FeedBrowsingState = .None static let iPadLayoutNumberPerRow:[ScreenOrientation: Int] = [.portrait: 4, .landscape: 5] static let iPhoneLayoutNumberPerRow:[ScreenOrientation: Int] = [.portrait: 3, .landscape: 4] lazy var layoutNumberPerRow:[UIUserInterfaceIdiom:[ScreenOrientation: Int]] = [ .pad : OPDSGroupTableViewCell.iPadLayoutNumberPerRow, .phone : OPDSGroupTableViewCell.iPhoneLayoutNumberPerRow ] override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func prepareForReuse() { super.prepareForReuse() collectionView?.setContentOffset(.zero, animated: false) collectionView?.reloadData() } override func layoutSubviews() { super.layoutSubviews() collectionView?.collectionViewLayout.invalidateLayout() } } extension OPDSGroupTableViewCell: UICollectionViewDataSource { // MARK: - Collection view data source func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var count = 0 if let group = group { if group.publications.count > 0 { count = group.publications.count browsingState = .Publication } else if group.navigation.count > 0 { count = group.navigation.count browsingState = .Navigation } } return count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { self.collectionView = collectionView if browsingState == .Publication { collectionView.register(UINib(nibName: "PublicationCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "publicationCollectionViewCell") let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "publicationCollectionViewCell", for: indexPath) as! PublicationCollectionViewCell cell.isAccessibilityElement = true cell.accessibilityHint = NSLocalizedString("opds_show_detail_view_a11y_hint", comment: "Accessibility hint for OPDS publication cell") if let publication = group?.publications[indexPath.row] { cell.accessibilityLabel = publication.metadata.title let titleTextView = OPDSPlaceholderListView( frame: cell.frame, title: publication.metadata.title, author: publication.metadata.authors .map { $0.name } .joined(separator: ", ") ) let coverURL: URL? = publication.link(withRel: .cover)?.url(relativeTo: publication.baseURL) ?? publication.images.first.flatMap { URL(string: $0.href) } if let coverURL = coverURL { UIApplication.shared.isNetworkActivityIndicatorVisible = true cell.coverImageView.kf.setImage( with: coverURL, placeholder: titleTextView, options: [.transition(ImageTransition.fade(0.5))], progressBlock: nil) { _ in DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false } } } cell.titleLabel.text = publication.metadata.title cell.authorLabel.text = publication.metadata.authors .map { $0.name } .joined(separator: ", ") } return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "opdsNavigationCollectionViewCell", for: indexPath) as! OPDSGroupCollectionViewCell if let navigation = group?.navigation[indexPath.row] { cell.accessibilityLabel = navigation.title cell.navigationTitleLabel.text = navigation.title if let count = navigation.properties.numberOfItems { cell.navigationCountLabel.text = "\(count)" } else { cell.navigationCountLabel.text = "" } } return cell } } } extension OPDSGroupTableViewCell: UICollectionViewDelegateFlowLayout { // MARK: - Collection view delegate func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if browsingState == .Publication { let idiom = { () -> UIUserInterfaceIdiom in let tempIdion = UIDevice.current.userInterfaceIdiom return (tempIdion != .pad) ? .phone:.pad // ignnore carplay and others } () guard let deviceLayoutNumberPerRow = layoutNumberPerRow[idiom] else {return CGSize(width: 0, height: 0)} guard let numberPerRow = deviceLayoutNumberPerRow[.current] else {return CGSize(width: 0, height: 0)} let minimumSpacing: CGFloat = 5.0 let labelHeight: CGFloat = 50.0 let coverRatio: CGFloat = 1.5 let itemWidth = (collectionView.frame.width / CGFloat(numberPerRow)) - (CGFloat(minimumSpacing) * CGFloat(numberPerRow)) - minimumSpacing let itemHeight = (itemWidth * coverRatio) + labelHeight return CGSize(width: itemWidth, height: itemHeight) } else { return CGSize(width: 200, height: 50) } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if browsingState == . Publication { if let publication = group?.publications[indexPath.row] { let opdsPublicationInfoViewController: OPDSPublicationInfoViewController = OPDSFactory.shared.make(publication: publication) opdsRootTableViewController?.navigationController?.pushViewController(opdsPublicationInfoViewController, animated: true) } } else { if let href = group?.navigation[indexPath.row].href, let url = URL(string: href) { let newOPDSRootTableViewController: OPDSRootTableViewController = OPDSFactory.shared.make(feedURL: url, indexPath: nil) opdsRootTableViewController?.navigationController?.pushViewController(newOPDSRootTableViewController, animated: true) } } } }
39.047847
149
0.586693
e9fe7929f5f4d34a67b20decc7040982e6f524be
5,424
// // Mixpanel.swift // Simcoe // // Created by Yoseob Lee on 2/28/17. // Copyright © 2017 Prolific Interactive. All rights reserved. // import Mixpanel /// The definition of MixpanelProperties typealias MixpanelProperties = [String: MixpanelType] /// The Mixpanel analytics provider. public class MixpanelPlaceholder { /// The name of the tracker. public let name = "Mixpanel" /// Initializes an API object with the input token. /// /// - Parameters: /// - token: The token. /// - launchOptions: The launch options. /// - flushInterval: The interval for background flushing. /// - instanceName: The instance name. public init(token: String, launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil, flushInterval: Double = 60, instanceName: String = UUID().uuidString) { Mixpanel.initialize(token: token, launchOptions: launchOptions, flushInterval: flushInterval, instanceName: instanceName) } /// Force uploading of queued data to the Mixpanel server. public func flush() { Mixpanel.mainInstance().flush() } } // MARK: - EventTracking extension MixpanelPlaceholder: EventTracking { /// Tracks the given event with optional additional properties. /// /// - Parameters: /// - event: The event to track. /// - properties: The optional additional properties. /// - Returns: A tracking result. public func track(event: String, withAdditionalProperties properties: Properties?) -> TrackingResult { guard let data = properties as? MixpanelProperties else { return .error(message: "All values must map to MixpanelType") } Mixpanel.mainInstance().track(event: event, properties: data) return .success } } // MARK: - LifetimeValueTracking extension MixpanelPlaceholder: LifetimeValueTracking { /// Tracks the lifetime value. /// /// - Parameters: /// - key: The lifetime value's identifier. /// - value: The lifetime value. /// - properties: The optional additional properties. /// - Returns: A tracking result. public func trackLifetimeValue(_ key: String, value: Any, withAdditionalProperties properties: Properties?) -> TrackingResult { guard let value = value as? Double else { return .error(message: "Value must map to a Double") } Mixpanel.mainInstance().people.increment(property: key, by: value) return .success } /// Track the lifetime values. /// /// - Parameter: /// - attributes: The lifetime attribute values. /// - properties: The optional additional properties. /// - Returns: A tracking result. public func trackLifetimeValues(_ attributes: Properties, withAdditionalProperties properties: Properties?) -> TrackingResult { guard let attributes = attributes as? MixpanelProperties else { return .error(message: "All values must map to MixpanelType") } Mixpanel.mainInstance().people.increment(properties: attributes) return .success } } // MARK: - SuperPropertyTracking extension MixpanelPlaceholder: SuperPropertyTracking { /// Sets the super properties. /// /// - Parameter properties: The super properties. /// - Returns: A tracking result. public func set(superProperties: Properties) -> TrackingResult { guard let properties = superProperties as? MixpanelProperties else { return .error(message: "All values must map to MixpanelType") } Mixpanel.mainInstance().registerSuperProperties(properties) return .success } /// Unsets the super property. /// /// - Parameter superProperty: The super property. /// - Returns: A tracking result. public func unset(superProperty: String) -> TrackingResult { Mixpanel.mainInstance().unregisterSuperProperty(superProperty) return .success } /// Clears all currently set super properties. /// /// - Returns: A tracking result. public func clearSuperProperties() -> TrackingResult { Mixpanel.mainInstance().clearSuperProperties() return .success } } // MARK: - UserAttributeTracking extension MixpanelPlaceholder: UserAttributeTracking { /// Sets the User Attribute. /// /// - Parameters: /// - key: The attribute key to log. /// - value: The attribute value to log. /// - Returns: A tracking result. public func setUserAttribute(_ key: String, value: Any) -> TrackingResult { guard let value = value as? MixpanelType else { return .error(message: "Value must map to MixpanelType") } Mixpanel.mainInstance().people.set(property: key, to: value) return .success } /// Sets the User Attributes. /// /// - Parameter attributes: The attribute values to log. /// - Returns: A tracking result. public func setUserAttributes(_ attributes: Properties) -> TrackingResult { guard let properties = attributes as? MixpanelProperties else { return .error(message: "All values must map to MixpanelType") } Mixpanel.mainInstance().people.set(properties: properties) return .success } }
30.133333
131
0.641409
0eaafda159d215f3fdfccae7a074472d7cae61d9
538
// // ListFactory.swift // AbstractFactory // // Created by satorun on 2016/02/04. // Copyright © 2016年 satorun. All rights reserved. // class ListFactory: Factory { override func createLink(caption: String, url: String) -> Link { return ListLink(caption: caption, url: url) } override func createTray(caption: String) -> Tray { return ListTray(caption: caption) } override func createPage(title: String, author: String) -> Page { return ListPage(title: title, author: author) } }
26.9
69
0.654275
295b2adb2c29b512d42d3b3e43d5ea30cbf7e5f6
2,606
// // TableViewDataSource.swift // // Created by Indragie on 10/6/14. // Copyright (c) 2014 Indragie Karunaratne. All rights reserved. // import UIKit public struct TableViewDataSource<T: AnyObject, U: UITableViewCell where U: ReusableCell> { public typealias CellConfigurator = (T, U) -> Void let dataSource: SectionedDataSource<T> let configurator: CellConfigurator public init(sections: [Section<T>], configurator: CellConfigurator) { self.dataSource = SectionedDataSource(sections: sections) self.configurator = configurator } public func numberOfSections() -> Int { return dataSource.sections.count } public func numberOfRowsInSection(section: Int) -> Int { return dataSource.numberOfItemsInSection(section) } public func itemAtIndexPath(indexPath: NSIndexPath) -> T { return dataSource.itemAtIndexPath(indexPath) } public func toObjC() -> TableViewDataSourceObjC { let sections = dataSource.sections.map { section in section.toObjC() } let configurator = self.configurator return TableViewDataSourceObjC(sections: sections, reuseIdentifier: U.reuseIdentifier()) { (object, cell) in configurator(object as T, cell as U) } } } public class TableViewDataSourceObjC: NSObject, UITableViewDataSource { typealias ObjCCellConfigurator = (AnyObject, AnyObject) -> Void let sections: [SectionObjC] let reuseIdentifier: String let configurator: ObjCCellConfigurator init(sections: [SectionObjC], reuseIdentifier: String, configurator: ObjCCellConfigurator) { self.sections = sections self.reuseIdentifier = reuseIdentifier self.configurator = configurator } // MARK: UITableViewDataSource public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].items.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? UITableViewCell { let object: AnyObject = sections[indexPath.section].items[indexPath.row] self.configurator(object, cell) return cell } else { assert(false, "Unable to create table view cell for reuse identifier \(reuseIdentifier)") } } }
34.746667
116
0.689946
71a37274a94f2ba6a50fcff39ca46bf2d3f73249
2,255
// // ChallengeTableViewControllerTests.swift // Progressus // // Created by Choong Kai Wern on 10/08/2017. // Copyright © 2017 Choong Kai Wern. All rights reserved. // import XCTest import CoreData @testable import Progressus class ChallengeTableViewControllerTests: XCTestCase { var controller: ChallengesTableViewController! var context: NSManagedObjectContext? override func setUp() { super.setUp() context = setUpInMemoryManagedObjectContext() let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) controller = storyboard.instantiateViewController(withIdentifier: "ChallengesTableViewController") as? ChallengesTableViewController controller.context = context! XCTAssertNotNil(controller.view) XCTAssertNotNil(controller.tableView) } override func tearDown() { context = nil super.tearDown() } func testBlankViewShouldAppearIfChallengesIsBlank() { XCTAssert(controller.challenges.isEmpty) XCTAssertEqual(controller.numberOfSections(in: controller.tableView), 0) XCTAssertNotNil(controller.tableView.backgroundView) XCTAssertEqual(controller.tableView.backgroundView!.frame, controller.blankView.frame) } func testNumberOfSectionEqualsToChallengesCount() { _ = addAndReturnChallenge(unique: "Workout", context: context!) _ = addAndReturnChallenge(unique: "Read", context: context!) XCTAssertEqual(controller.challenges.count, 2) let sec = controller.numberOfSections(in: controller.tableView) XCTAssertEqual(sec, controller.challenges.count) } func testCell() { let challenge = addAndReturnChallenge(unique: "Workout", context: context!) let cell = controller.tableView(controller.tableView, cellForRowAt: IndexPath(row: 0, section: 0)) as? ChallengeTableViewCell XCTAssertNotNil(cell) XCTAssertEqual(cell!.challengeNameLabel.text, challenge.unique) XCTAssertEqual(cell!.dayTimeLabel.text, challenge.progressDescription) XCTAssertEqual(cell!.percentageLabel.text, challenge.progressPercentageString + "%") } }
35.793651
140
0.703326
9bc6fa6969bcea5838c097a6817de1bbdb941d02
2,926
import Foundation import azureSwiftRuntime public protocol FirewallRulesGet { var headerParameters: [String: String] { get set } var subscriptionId : String { get set } var resourceGroupName : String { get set } var accountName : String { get set } var firewallRuleName : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (FirewallRuleProtocol?, Error?) -> Void) -> Void ; } extension Commands.FirewallRules { // Get gets the specified Data Lake Store firewall rule. internal class GetCommand : BaseCommand, FirewallRulesGet { public var subscriptionId : String public var resourceGroupName : String public var accountName : String public var firewallRuleName : String public var apiVersion = "2016-11-01" public init(subscriptionId: String, resourceGroupName: String, accountName: String, firewallRuleName: String) { self.subscriptionId = subscriptionId self.resourceGroupName = resourceGroupName self.accountName = accountName self.firewallRuleName = firewallRuleName super.init() self.method = "Get" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules/{firewallRuleName}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{accountName}"] = String(describing: self.accountName) self.pathParameters["{firewallRuleName}"] = String(describing: self.firewallRuleName) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(FirewallRuleData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (FirewallRuleProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: FirewallRuleData?, error: Error?) in completionHandler(result, error) } } } }
47.193548
183
0.644566
f89ff143444cda419fa18e332d5f625e88cee970
391
// // MultiIndexHitsController.swift // InstantSearchCore // // Created by Vladislav Fitc on 23/05/2019. // Copyright © 2019 Algolia. All rights reserved. // import Foundation public protocol MultiIndexHitsController: class, Reloadable { var hitsSource: MultiIndexHitsSource? { get set } func scrollToTop() } extension MultiIndexHitsInteractor: MultiIndexHitsSource {}
19.55
61
0.744246
037ef4c06eed4248686b9255bde4e215136d8474
2,450
import XCTest @testable import ShallowPromises final class ShallowPromisesTests: XCTestCase { func testFulfillTwice() { let expectation = self.expectation(description: "twice") Promise().fulfill(with: 0).fulfill(with: 1).onSuccess { result in XCTAssertEqual(result, 0) }.finally { expectation.fulfill() } wait(for: [expectation], timeout: 1.0) } func testCancelLittlePromise() { let expectation = self.expectation(description: "littlePromise") let littlePromise = Promise<Int>() littlePromise.onSuccess { _ in XCTFail() }.onError { error in XCTAssertTrue(error is PromiseFailure) }.finally { expectation.fulfill() } let promise = Promise<Int>(littlePromise: littlePromise) promise.cancel() wait(for: [expectation], timeout: 1.0) } func testCancelledLittlePromise() { let expectation = self.expectation(description: "littlePromise") let littlePromise = Promise<Int>() littlePromise.onSuccess { _ in XCTFail() }.onError { error in XCTAssertTrue(error is PromiseFailure) }.finally { expectation.fulfill() } let promise = Promise<Int>().complete(with: TestError.test) promise.littlePromise = littlePromise wait(for: [expectation], timeout: 1.0) } func testFinally() { let expectation = self.expectation(description: "testFinally") Promise<Int>().fulfill(with: 0, in: .main).finally { expectation.fulfill() } wait(for: [expectation], timeout: 1.0) } func testInitCompletion() { let expectation = self.expectation(description: "testFinally") Promise(successClosure: { (result: Int) in expectation.fulfill() }, queue: .main).fulfill(with: 0) wait(for: [expectation], timeout: 1.0) } static var allTests = [ ("testFulfillTwice", testFulfillTwice), ("testCancelLittlePromise", testCancelLittlePromise), ("testCancelledLittlePromise", testCancelledLittlePromise), ("testFinally", testFinally), ("testInitCompletion", testInitCompletion), ] } enum TestError: Error { case test }
29.166667
73
0.584082
efeb8c4af45a04c56db01e61cd2a89d4408e048a
1,733
// // ViewController.swift // SalsaExample // // Created by Max Rabiciuc on 2/21/18. // Copyright © 2018 Yelp. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let onlineTwoLines = UserView(user: User(name: "User Name", subtitle: "Last conversation message", image: UIImage(named: "user")!), isOnline: true) let offlineTwoLines = UserView(user: User(name: "User Name", subtitle: "Last conversation message", image: UIImage(named: "user")!), isOnline: false) let onlineOneLine = UserView(user: User(name: "User Name", subtitle: nil, image: UIImage(named: "user")!), isOnline: true) let offlineOneLine = UserView(user: User(name: "User Name", subtitle: nil, image: UIImage(named: "user")!), isOnline: false) view.addSubview(onlineTwoLines) view.addSubview(offlineTwoLines) view.addSubview(onlineOneLine) view.addSubview(offlineOneLine) let views: [String: UIView] = [ "onlineTwoLines": onlineTwoLines, "offlineTwoLines": offlineTwoLines, "onlineOneLine": onlineOneLine, "offlineOneLine": offlineOneLine ] views.forEach { $1.translatesAutoresizingMaskIntoConstraints = false } let horizontalConstraints = views.values.map { [ $0.leftAnchor.constraint(equalTo: view.leftAnchor), $0.rightAnchor.constraint(equalTo: view.rightAnchor) ] }.flatMap { $0 } let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[onlineTwoLines][offlineTwoLines][onlineOneLine][offlineOneLine]", options: [], metrics: nil, views: views) NSLayoutConstraint.activate(verticalConstraints + horizontalConstraints) } }
36.87234
191
0.708021
ded14563c56a9e34e624e104279128e9e4d41dd4
2,207
/* This source file is part of the Swift.org open source project Copyright (c) 2021 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 Swift project authors */ import XCTest @testable import SwiftDocC class Sequence_MapFirstTests: XCTestCase { struct Val { let id: Int let name: String } func testEmpty() { // Test that the closure is never called for an empty collection. XCTAssertNil([].mapFirst(where: { "" })) } func testNotFound() { XCTAssertNil([1, 2, 3].mapFirst(where: { _ in nil })) XCTAssertNil([1, 2, 3].mapFirst(where: { $0 == 100 ? $0 : nil})) // Should call the closure for each element when no match is found var values = [Int]() XCTAssertNil([1, 2, 3].mapFirst(where: { values.append($0); return nil })) XCTAssertEqual(values, [1, 2, 3]) } func testFound() { // Should return a string for the first element XCTAssertEqual([1, 2, 3].mapFirst(where: { _ in "TEST" }), "TEST") // Should return a boolean for the first element XCTAssertEqual([1, 2, 3].mapFirst(where: { $0 == 3 }), false) // Should return the last element as string XCTAssertEqual([1, 2, 3].mapFirst(where: { $0 == 3 ? "\($0)" : nil }), "3") // Should return the name of value with id = 2 let values = [ Val(id: 1, name: "Anna"), Val(id: 2, name: "Hannah"), Val(id: 3, name: "Joanna"), ] XCTAssertEqual(values.mapFirst(where: { value -> String? in return value.id == 2 ? value.name : nil }), "Hannah") // Should call the closure for each element up until the matching one do { var values = [Int]() _ = [1, 2, 3, 4, 5].mapFirst(where: { value -> Bool? in values.append(value); return value == 3 ? true : nil }) XCTAssertEqual(values, [1, 2, 3]) } } }
33.439394
83
0.556411
d583b1f69ce5019570b9a56b5ec520c5c6807191
2,681
// // CustomGroup.swift // CompositionalLayoutDSL // // Created by Alexandre Podlewski on 07/04/2021. // Copyright © 2021 Fabernovel. All rights reserved. // #if os(macOS) import AppKit #else import UIKit #endif /// A customizable container for a set of items. public struct CustomGroup: LayoutGroup, ResizableItem { private var widthDimension: NSCollectionLayoutDimension private var heightDimension: NSCollectionLayoutDimension private let itemProvider: NSCollectionLayoutGroupCustomItemProvider // MARK: - Life cycle /// Creates a group of the specified size, with an item provider that creates a custom /// arrangement for those items. public init(width: NSCollectionLayoutDimension = .fractionalWidth(1), height: NSCollectionLayoutDimension = .fractionalHeight(1), itemProvider: @escaping NSCollectionLayoutGroupCustomItemProvider) { self.widthDimension = width self.heightDimension = height self.itemProvider = itemProvider } /// Creates a group of the specified size, with an item provider that creates a custom /// arrangement for those items. public init(size: NSCollectionLayoutSize, itemProvider: @escaping NSCollectionLayoutGroupCustomItemProvider) { self.widthDimension = size.widthDimension self.heightDimension = size.heightDimension self.itemProvider = itemProvider } /// Creates a group with an item provider that creates a custom arrangement for those items. public init(itemProvider: @escaping NSCollectionLayoutGroupCustomItemProvider) { self.init(width: .fractionalWidth(1), height: .fractionalHeight(1), itemProvider: itemProvider) } // MARK: - LayoutGroup public var layoutGroup: LayoutGroup { return self } // MARK: - ResizableItem /// Configure the width of the group /// /// The default value is `.fractionalWidth(1.0)` public func width(_ width: NSCollectionLayoutDimension) -> Self { with(self) { $0.widthDimension = width } } /// Configure the height of the group /// /// The default value is `.fractionalHeight(1.0)` public func height(_ height: NSCollectionLayoutDimension) -> Self { with(self) { $0.heightDimension = height } } } extension CustomGroup: BuildableGroup { func makeGroup() -> NSCollectionLayoutGroup { let size = NSCollectionLayoutSize( widthDimension: widthDimension, heightDimension: heightDimension ) let group = NSCollectionLayoutGroup.custom(layoutSize: size, itemProvider: itemProvider) return group } }
33.098765
103
0.696755
1a08756435814eb17114d141b2e3847211a554aa
2,122
// // SILSecurity_7_2TestCase.swift // BlueGecko // // Created by Kamil Czajka on 25.3.2021. // Copyright © 2021 SiliconLabs. All rights reserved. // import Foundation class SILSecurity_7_2TestCase: SILTestCase { var testResult: SILObservable<SILTestResult?> = SILObservable(initialValue: nil) var testID: String = "7.2" var testName: String = "Security and Encryption." var observableTokens: [SILObservableToken?] = [] private var disposeBag = SILObservableTokenBag() private var securityTestHelper: SILIOPSecurityTestHelper private var iopTestPhase3TestSecurityPairing = SILIOPPeripheral.SILIOPTestPhase3.IOPTest_Security_Pairing.cbUUID private let InitialValue = "0x000100" private let ExceptedValue = "0x55" init() { securityTestHelper = SILIOPSecurityTestHelper(testedCharacteristic: iopTestPhase3TestSecurityPairing, initialValue: InitialValue, exceptedValue: ExceptedValue) } func injectParameters(parameters: Dictionary<String, Any>) { securityTestHelper.injectParameters(parameters: parameters) } func performTestCase() { weak var weakSelf = self let securityTestHelperResultSubscription = securityTestHelper.testResult.observe( { testResult in guard let weakSelf = weakSelf else { return } guard let testResult = testResult else { return } weakSelf.securityTestHelper.invalidateObservableTokens() weakSelf.publishTestResult(passed: testResult.passed, description: testResult.description) }) disposeBag.add(token: securityTestHelperResultSubscription) observableTokens.append(securityTestHelperResultSubscription) publishStartTestEvent() securityTestHelper.performTestCase() } func getTestArtifacts() -> Dictionary<String, Any> { return [:] } func stopTesting() { securityTestHelper.stopTesting() invalidateObservableTokens() } }
35.966102
116
0.675778
9145f74df418cf4f5cc729f9681be582843fd256
1,647
// // Copyright © 2019 Essential Developer. All rights reserved. // import Foundation import FeedFeature protocol FeedLoadingView { func display(_ viewModel: FeedLoadingViewModel) } protocol FeedView { func display(_ viewModel: FeedViewModel) } protocol FeedErrorView { func display(_ viewModel: FeedErrorViewModel) } final class FeedPresenter { private let feedView: FeedView private let loadingView: FeedLoadingView private let feedErrorView: FeedErrorView init(feedView: FeedView, loadingView: FeedLoadingView, feedErrorView: FeedErrorView) { self.feedView = feedView self.loadingView = loadingView self.feedErrorView = feedErrorView } static var title: String { return NSLocalizedString("FEED_VIEW_TITLE", tableName: "Feed", bundle: Bundle(for: FeedPresenter.self), comment: "Title for the feed view") } var loadingError: String { return NSLocalizedString("FEED_VIEW_CONNECTION_ERROR", tableName: "Feed", bundle: Bundle(for: FeedPresenter.self), comment: "Error message that is displayed, when loading image feed from server does not work.") } func didStartLoadingFeed() { feedErrorView.display(FeedErrorViewModel(errorMessage: nil)) loadingView.display(FeedLoadingViewModel(isLoading: true)) } func didFinishLoadingFeed(with feed: [FeedImage]) { feedView.display(FeedViewModel(feed: feed)) loadingView.display(FeedLoadingViewModel(isLoading: false)) } func didFinishLoadingFeed(with error: Error) { loadingView.display(FeedLoadingViewModel(isLoading: false)) feedErrorView.display(FeedErrorViewModel(errorMessage: loadingError)) } }
28.894737
218
0.759563
de10795ec09152217f2ebfa24ff1e35d43ad8e2f
305
// // UIColor+Ext.swift // DemoArcade // // Created by Jonathan Rasmusson Work Pro on 2020-03-26. // Copyright © 2020 Rasmusson Software Consulting. All rights reserved. // import UIKit extension UIColor { static let spotifyGreen = UIColor(red: 28/255, green: 184/255, blue: 89/255, alpha: 1) }
21.785714
90
0.701639
69c38939241858e034f84acbc51b39b753546c16
6,226
// // FlexBoxComponent.swift // // Copyright (c) 2016-present, LINE Corporation. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by LINE Corporation. // // As with any software that integrates with the LINE Corporation platform, your use of this software // is subject to the LINE Developers Agreement [http://terms2.line.me/LINE_Developers_Agreement]. // This copyright 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. // /// LINE internal use only. /// Represents a box component in a flex message. /// A box component behave as a container of other components. It defines the layout of its child components. /// You can also include a nested box in a box. public struct FlexBoxComponent: Codable, FlexMessageComponentTypeCompatible, MessageActionContainer { let type: FlexMessageComponentType = .box /// The placement style of components in this box. public let layout: FlexMessageComponent.Layout /// Components in this box. /// /// When the `layout` is `.horizontal` or `.vertical`, the following components are supported as nested: /// - `FlexBoxComponent` /// - `FlexTextComponent` /// - `FlexImageComponent` /// - `FlexButtonComponent` /// - `FlexFillerComponent` /// - `FlexSeparatorComponent` /// - `FlexSpacerComponent` /// /// When the `layout` is `.baseline`, the following components are supported as nested:: /// - `FlexTextComponent` /// - `FlexFillerComponent` /// - `FlexIconComponent` /// - `FlexSpacerComponent` /// /// LineSDK does not check the validation of contents for a certain layout. However, it might cause a response error /// if you try to send a message with invalid component `contents` public var contents: [FlexMessageComponent] /// The ratio of the width or height of this box within the parent box. The default value for the horizontal parent /// box is 1, and the default value for the vertical parent box is 0. public var flex: FlexMessageComponent.Ratio? /// Minimum space between components in this box. If not specified, `.none` will be used. public var spacing: FlexMessageComponent.Spacing? /// Minimum space between this box and the previous component in the parent box. /// If not specified, the `spacing` of parent box will be used. /// If this box is the first component in the parent box, this margin property will be ignored. public var margin: FlexMessageComponent.Margin? /// An action to perform when the box tapped. /// Use `setAction` method if you want to set a `MessageActionConvertible` as the action of current component. /// /// - Note: /// This property is supported on the following versions of LINE: /// - LINE for iOS and Android: 8.11.0 and later /// - LINE for Windows and macOS: 5.9.0 and later public var action: MessageAction? /// Creates a box component with given information. /// /// - Parameters: /// - layout: The placement style of components in this box. /// - contents: Components in this box. /// /// - Note: /// When the `layout` is `.horizontal` or `.vertical`, the following components are supported as nested: /// - `FlexBoxComponent` /// - `FlexTextComponent` /// - `FlexImageComponent` /// - `FlexButtonComponent` /// - `FlexFillerComponent` /// - `FlexSeparatorComponent` /// - `FlexSpacerComponent` /// /// When the `layout` is `.baseline`, the following components are supported as nested:: /// - `FlexTextComponent` /// - `FlexFillerComponent` /// - `FlexIconComponent` /// - `FlexSpacerComponent` /// /// LineSDK does not check the validation of contents for a certain layout. However, it might cause a response error /// if you try to send a message with invalid component `contents` /// public init(layout: FlexMessageComponent.Layout, contents: [FlexMessageComponentConvertible] = []) { self.layout = layout self.contents = contents.map { $0.component } } /// Appends a component to current `contents`. /// /// - Parameter value: The component to append. public mutating func addComponent(_ value: FlexMessageComponentConvertible) { contents.append(value.component) } /// Removes the first component from `contents` which meets the given `condition`. /// /// - Parameter condition: A closure that takes an element as its argument and returns a `Bool` value that /// indicates whether the passed element represents a match. /// - Returns: The element which was removed, or `nil` if matched element not found. /// - Throws: Rethrows the `condition` block error. public mutating func removeFisrtComponent( where condition: (FlexMessageComponent) throws -> Bool) rethrows -> FlexMessageComponent? { #if swift(>=5.0) guard let index = try contents.firstIndex(where: condition) else { return nil } #else guard let index = try contents.index(where: condition) else { return nil } #endif return contents.remove(at: index) } } extension FlexBoxComponent: FlexMessageComponentConvertible { /// Returns a converted `FlexMessageComponent` which wraps this `FlexBoxComponent`. public var component: FlexMessageComponent { return .box(self) } }
45.115942
120
0.675554
8af77f9d7131221dcd3bcadf8b4af8c2fdbff5e0
788
// // UIButton+Helper.swift // BanCompo // // Created by Nurboldy on 6/16/18. // import UIKit extension UIButton { static public func systemButton(title: String? = nil, image: UIImage? = nil, titleColor: UIColor? = .white, font: UIFont? = nil, target: Any? = nil, selector: Selector? = nil) -> UIButton { let button = UIButton(type: .system) button.setTitle(title, for: .normal) button.setImage(image?.withRenderingMode(.alwaysOriginal), for: .normal) button.imageView?.contentMode = .scaleAspectFit button.setTitleColor(titleColor, for: .normal) button.titleLabel?.font = font if let selector = selector { button.addTarget(target, action: selector, for: .touchUpInside) } return button } }
32.833333
193
0.647208
20993af6f9b1bc89bac0b4efe4f8f1a22eeebd1b
5,292
// // AppAssets.swift // NetNewsWire // // Created by Maurice Parker on 4/8/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import UIKit import RSCore import Account struct AppAssets { static var accountLocalPadImage: UIImage = { return UIImage(named: "accountLocalPad")! }() static var accountLocalPhoneImage: UIImage = { return UIImage(named: "accountLocalPhone")! }() static var accountFeedbinImage: UIImage = { return UIImage(named: "accountFeedbin")! }() static var accountFeedlyImage: UIImage = { return UIImage(named: "accountFeedly")! }() static var accountFreshRSSImage: UIImage = { return UIImage(named: "accountFreshRSS")! }() static var articleExtractorError: UIImage = { return UIImage(named: "articleExtractorError")! }() static var articleExtractorOff: UIImage = { return UIImage(named: "articleExtractorOff")! }() static var articleExtractorOffTinted: UIImage = { let image = UIImage(named: "articleExtractorOff")! return image.maskWithColor(color: AppAssets.primaryAccentColor.cgColor)! }() static var articleExtractorOn: UIImage = { return UIImage(named: "articleExtractorOn")! }() static var articleExtractorOnTinted: UIImage = { let image = UIImage(named: "articleExtractorOn")! return image.maskWithColor(color: AppAssets.primaryAccentColor.cgColor)! }() static var iconBackgroundColor: UIColor = { return UIColor(named: "iconBackgroundColor")! }() static var barBackgroundColor: UIColor = { return UIColor(named: "barBackgroundColor")! }() static var circleClosedImage: UIImage = { return UIImage(systemName: "largecircle.fill.circle")! }() static var circleOpenImage: UIImage = { return UIImage(systemName: "circle")! }() static var disclosureImage: UIImage = { return UIImage(named: "disclosure")! }() static var copyImage: UIImage = { return UIImage(systemName: "doc.on.doc")! }() static var deactivateImage: UIImage = { UIImage(systemName: "minus.circle")! }() static var editImage: UIImage = { UIImage(systemName: "square.and.pencil")! }() static var faviconTemplateImage: RSImage = { return RSImage(named: "faviconTemplateImage")! }() static var fullScreenBackgroundColor: UIColor = { return UIColor(named: "fullScreenBackgroundColor")! }() static var infoImage: UIImage = { UIImage(systemName: "info.circle")! }() static var markAllInFeedAsReadImage: UIImage = { return UIImage(systemName: "asterisk.circle")! }() static var markOlderAsReadDownImage: UIImage = { return UIImage(systemName: "arrowtriangle.down.circle")! }() static var markOlderAsReadUpImage: UIImage = { return UIImage(systemName: "arrowtriangle.up.circle")! }() static var masterFolderImage: IconImage = { return IconImage(UIImage(systemName: "folder.fill")!) }() static var moreImage: UIImage = { return UIImage(systemName: "ellipsis.circle")! }() static var openInSidebarImage: UIImage = { return UIImage(systemName: "arrow.turn.down.left")! }() static var primaryAccentColor: UIColor = { return UIColor(named: "primaryAccentColor")! }() static var safariImage: UIImage = { return UIImage(systemName: "safari")! }() static var searchFeedImage: IconImage = { return IconImage(UIImage(systemName: "magnifyingglass")!) }() static var secondaryAccentColor: UIColor = { return UIColor(named: "secondaryAccentColor")! }() static var sectionHeaderColor: UIColor = { return UIColor(named: "sectionHeaderColor")! }() static var shareImage: UIImage = { return UIImage(systemName: "square.and.arrow.up")! }() static var smartFeedImage: UIImage = { return UIImage(systemName: "gear")! }() static var starColor: UIColor = { return UIColor(named: "starColor")! }() static var starClosedImage: UIImage = { return UIImage(systemName: "star.fill")! }() static var starOpenImage: UIImage = { return UIImage(systemName: "star")! }() static var starredFeedImage: IconImage = { return IconImage(UIImage(systemName: "star.fill")!) }() static var tickMarkColor: UIColor = { return UIColor(named: "tickMarkColor")! }() static var timelineStarImage: UIImage = { let image = UIImage(systemName: "star.fill")! return image.withTintColor(AppAssets.starColor, renderingMode: .alwaysOriginal) }() static var todayFeedImage: IconImage = { return IconImage(UIImage(systemName: "sun.max.fill")!) }() static var trashImage: UIImage = { return UIImage(systemName: "trash")! }() static var unreadFeedImage: IconImage = { return IconImage(UIImage(systemName: "largecircle.fill.circle")!) }() static var vibrantTextColor: UIColor = { return UIColor(named: "vibrantTextColor")! }() static var controlBackgroundColor: UIColor = { return UIColor(named: "controlBackgroundColor")! }() static func image(for accountType: AccountType) -> UIImage? { switch accountType { case .onMyMac: if UIDevice.current.userInterfaceIdiom == .pad { return AppAssets.accountLocalPadImage } else { return AppAssets.accountLocalPhoneImage } case .feedbin: return AppAssets.accountFeedbinImage case .feedly: return AppAssets.accountFeedlyImage case .freshRSS: return AppAssets.accountFreshRSSImage default: return nil } } }
24.387097
81
0.714664
1453de161765e2b2782f62fd2574f012b51aac75
2,592
import Foundation import ProjectDescription import TSCBasic import TuistCore import TuistGraph import TuistSupport public protocol TemplateLoading { /// Load `TuistScaffold.Template` at given `path` /// - Parameters: /// - path: Path of template manifest file `name_of_template.swift` /// - Returns: Loaded `TuistScaffold.Template` func loadTemplate(at path: AbsolutePath) throws -> TuistGraph.Template } public class TemplateLoader: TemplateLoading { private let manifestLoader: ManifestLoading /// Default constructor. public convenience init() { self.init(manifestLoader: ManifestLoader()) } init(manifestLoader: ManifestLoading) { self.manifestLoader = manifestLoader } public func loadTemplate(at path: AbsolutePath) throws -> TuistGraph.Template { let template = try manifestLoader.loadTemplate(at: path) let generatorPaths = GeneratorPaths(manifestDirectory: path) return try TuistGraph.Template.from( manifest: template, generatorPaths: generatorPaths ) } } extension TuistGraph.Template { static func from(manifest: ProjectDescription.Template, generatorPaths: GeneratorPaths) throws -> TuistGraph.Template { let attributes = try manifest.attributes.map(TuistGraph.Template.Attribute.from) let files = try manifest.files.map { File( path: RelativePath($0.path), contents: try TuistGraph.Template.Contents.from( manifest: $0.contents, generatorPaths: generatorPaths ) ) } return TuistGraph.Template( description: manifest.description, attributes: attributes, files: files ) } } extension TuistGraph.Template.Attribute { static func from(manifest: ProjectDescription.Template.Attribute) throws -> TuistGraph.Template.Attribute { switch manifest { case let .required(name): return .required(name) case let .optional(name, default: defaultValue): return .optional(name, default: defaultValue) } } } extension TuistGraph.Template.Contents { static func from(manifest: ProjectDescription.Template.Contents, generatorPaths: GeneratorPaths) throws -> TuistGraph.Template.Contents { switch manifest { case let .string(contents): return .string(contents) case let .file(templatePath): return .file(try generatorPaths.resolve(path: templatePath)) } } }
32.810127
123
0.665509
1e4dd2be52f8a43747d2515366daa4fef9679298
2,810
// // PUINowPlayingInfoCoordinator.swift // PlayerUI // // Created by Guilherme Rambo on 22/04/18. // Copyright © 2018 Guilherme Rambo. All rights reserved. // import Foundation import MediaPlayer final class PUINowPlayingInfoCoordinator { let player: AVPlayer init(player: AVPlayer) { self.player = player observePlayer() } var basicNowPlayingInfo: PUINowPlayingInfo? // MARK: - Playback state var playbackStateAppropriateForPlayer: MPNowPlayingPlaybackState { return player.rate.isZero ? .paused : .playing } // MARK: - Playback info var nowPlayingInfo: [String: Any]? { guard let item = player.currentItem else { return nil } var info: [String: Any] = [ MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.video.rawValue, MPNowPlayingInfoPropertyPlaybackRate: player.rate, MPNowPlayingInfoPropertyElapsedPlaybackTime: CMTimeGetSeconds(player.currentTime()) ] if let urlAsset = item.asset as? AVURLAsset { info[MPNowPlayingInfoPropertyAssetURL] = urlAsset.url } info[MPNowPlayingInfoPropertyCurrentPlaybackDate] = item.currentDate() if let basicInfo = basicNowPlayingInfo?.dictionaryRepresentation { info.merge(basicInfo, uniquingKeysWith: { a, b in b }) } if item.duration.isValid, item.duration.isNumeric { info[MPMediaItemPropertyPlaybackDuration] = TimeInterval(CMTimeGetSeconds(item.duration)) } return info } // MARK: - Player observation private var rateObservation: NSKeyValueObservation? private var itemObservation: NSKeyValueObservation? private var timeObserver: Any? private func observePlayer() { rateObservation = player.observe(\.rate) { [weak self] _, _ in DispatchQueue.main.async { self?.playbackRateDidChange() } } itemObservation = player.observe(\.currentItem) { [weak self] _, _ in DispatchQueue.main.async { self?.updateNowPlayingInfo() } } timeObserver = player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 30000), queue: .main) { [weak self] _ in DispatchQueue.main.async { self?.updateNowPlayingInfo() } } } private func playbackRateDidChange() { MPNowPlayingInfoCenter.default().playbackState = playbackStateAppropriateForPlayer } private func updateNowPlayingInfo() { MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } deinit { if let timeObserver = timeObserver { player.removeTimeObserver(timeObserver) } rateObservation?.invalidate() itemObservation?.invalidate() } }
29.270833
152
0.674377
aca054e396c5f1440d4b3ac0f25258a0a584f24c
1,810
import Foundation import Combine public struct WampID: Codable, Equatable, ExpressibleByIntegerLiteral, RawRepresentable { public typealias RawValue = Int public typealias IntegerLiteralType = Int public let value: Int public var rawValue: Int { value } public init(integerLiteral value: Int) { self.value = value } public init(rawValue: Int) { self.value = rawValue } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let value = try container.decode(Int.self) self = .init(integerLiteral: value) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(value) } } extension WampID { /// https://wamp-proto.org/_static/gen/wamp_latest.html#global-scope-ids /// WELCOME.Session /// PUBLISHED.Publication /// EVENT.Publication public static func createSessionScopeIDs() -> AutoIncrementID { AutoIncrementID(range: 1...Int(pow(2.0, 53)), overflowStrategy: .resetToMin) } } extension WampID { /// https://wamp-proto.org/_static/gen/wamp_latest.html#session-scope-ids /// ERROR.Request /// PUBLISH.Request /// PUBLISHED.Request /// SUBSCRIBE.Request /// SUBSCRIBED.Request /// UNSUBSCRIBE.Request /// UNSUBSCRIBED.Request /// CALL.Request /// CANCEL.Request /// RESULT.Request /// REGISTER.Request /// REGISTERED.Request /// UNREGISTER.Request /// UNREGISTERED.Request /// INVOCATION.Request /// INTERRUPT.Request /// YIELD.Request public static func createGlobalScopeIDs() -> RandomNumericID { RandomNumericID(range: 1...Int(pow(2.0, 53)), overflowStrategy: .resetList) } }
28.28125
89
0.663536
1df5f52d74d4746c6647bcd9ea934e9efb61569f
5,765
// // TermsOfUseEndpoint.swift // AirWatchServices // // Copyright © 2017 VMware, Inc. All rights reserved. This product is protected // by copyright and intellectual property laws in the United States and other // countries as well as by international treaties. VMware products are covered // by one or more patents listed at http://www.vmware.com/go/patents. // import Foundation import AWNetwork import AWError extension AWServices { public enum EULAAcceptanceStatus: Int { case accepted case notAccepted case unknown } } internal class EULAAcceptanceStatusEndpoint: DeviceServicesEndpoint { private static let kIsEulaAcceptanceRequired = "IsEulaAcceptanceRequired" required init(config: DeviceServicesConfiguration, authorizer: CTLAuthorizationProtocol?, validator: CTLResponseValidationProtocol?) { super.init(config: config, authorizer: authorizer, validator: validator) self.serviceEndpoint = "/deviceservices/awmdmsdk/v1/platform/2/uid/\(self.config.deviceId)/eula" } internal func getAcceptanceStatus(completion: @escaping (_ requiredEULAAcceptance: AWServices.EULAAcceptanceStatus, _ error: NSError?) -> Void) { self.serviceEndpoint.append("/checkeula/appid/\(self.config.bundleId)") self.GET { (response: CTLJSONObject?, error: NSError?) in if let error = error { completion(.unknown, error) return } guard let response = response, let jsonObject = response.JSON as? [String: AnyObject] else { completion(.unknown, AWError.SDK.Service.General.invalidJSONResponse.error as NSError) return } guard let eulaAcceptanceRequired = jsonObject[EULAAcceptanceStatusEndpoint.kIsEulaAcceptanceRequired] as? Bool else { completion(.unknown, AWError.SDK.Service.General.unexpectedResponse.error as NSError) return } if eulaAcceptanceRequired { completion(AWServices.EULAAcceptanceStatus.notAccepted, nil) } else { completion(AWServices.EULAAcceptanceStatus.accepted, nil) } } } internal func updateEULAAcceptance(contentID: UInt, status: AWServices.EULAAcceptanceStatus, completion: @escaping (Bool, NSError?)-> Void) { switch status { case .unknown: log(error: "Can not update unknown status to server") completion(false, AWError.SDK.Service.Authorization.invalidInputs.error) return case .accepted: self.serviceEndpoint.append("/accepteula") case .notAccepted: self.serviceEndpoint.append("/rejecteula") } let requestBodyDict = [AWServices.EULAContent.kAWTOUContentId: contentID] let requestBodyData = try? JSONSerialization.data(withJSONObject: requestBodyDict, options: []) self.POST(requestBodyData) { (json: CTLJSONObject?, error: NSError?) in if let error = error { completion(false, error) return } guard let urlResponse = json?.properties?[CTLConstants.kCTLDataObjectURLResponse] as? HTTPURLResponse else { completion(false, AWError.SDK.Service.General.unexpectedResponse.error) return } completion(urlResponse.statusCode == 200, error) } } } extension AWServices { public final class EULAContent: CTLDataObjectProtocol { let contentID: UInt let content: String let applicationList: [String] private init(contentID: UInt, content: String, applicationList: [String]) { self.contentID = contentID self.content = content self.applicationList = applicationList } static let kAWTOUContentId = "EulaContentId" static let kAWTOUContent = "EulaContent" static let kAWTOUApplicationList = "ApplicationList" public static func objectWithData(_ data: Data?, additionalProperties: Dictionary<String, AnyObject>?) throws -> EULAContent { guard let data = data else { throw AWError.SDK.Service.General.invalidJSONResponse } guard let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject], let contentID = jsonObject[AWServices.EULAContent.kAWTOUContentId] as? UInt, let content = jsonObject[AWServices.EULAContent.kAWTOUContent] as? String else { throw AWError.SDK.Service.General.unexpectedResponse } let applicationList = jsonObject[AWServices.EULAContent.kAWTOUApplicationList] as? [String] ?? [] return EULAContent(contentID: contentID, content: content, applicationList: applicationList) } } } internal class EULAContentFetchEndpoint: DeviceServicesEndpoint { required init(config: DeviceServicesConfiguration, authorizer: CTLAuthorizationProtocol?, validator: CTLResponseValidationProtocol?) { super.init(config: config, authorizer: authorizer, validator: validator) self.serviceEndpoint = "/deviceservices/awmdmsdk/v1/platform/2/uid/\(self.config.deviceId)/eula/fetcheula/appid/\(self.config.bundleId)" } internal func fetchEULAContent(contentID: Int = -1, completion: @escaping (_ content: AWServices.EULAContent?, NSError?) -> Void) { if contentID >= 0 { self.serviceEndpoint.append("/eulacontentid/\(contentID)") } self.GET { (content: AWServices.EULAContent?, error: NSError?) in completion(content, error) } } }
40.314685
149
0.66314
217d960466fe7f2f77928c8ac8de246aa90e4c23
464
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol P{ typealias e func f:P protocol P{ func f:e typealias a
33.142857
79
0.756466
fc7c69a9e6f64b6d9ba35f029ef896dfe5c8d7b4
1,046
// // DataManager(FOAAS).swift // Boarding Pass // // Created by Karen Fuentes on 11/26/16. // Copyright © 2016 Karen Fuentes. All rights reserved. // import Foundation class DataManager { static let shared: DataManager = DataManager() private init() {} private static let operationsKey: String = "FoaasOperationsKey" private static let defaults = UserDefaults.standard internal private(set) var operations: [FoaasOperation]? func save(operations: [FoaasOperation]) { let data = operations.flatMap{FoaasOperation.toData($0)} //still missing defaults } func load() -> Bool { guard let data = DataManager.defaults.value(forKey: DataManager.operationsKey) as? [Data] else { return false } let operationsArray = data.flatMap{ FoaasOperation(data: $0) } DataManager.shared.operations = operationsArray return true } func deleteStoredOperations() { DataManager.defaults.set(nil, forKey: DataManager.operationsKey) } }
25.512195
119
0.672084
e464f092d2a16951a20b45f95a5ee80298dfb6a3
452
// Copyright © 2017-2019 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import Foundation public typealias TWNimiqSigningInput = TW_Nimiq_Proto_SigningInput public typealias TWNimiqSigningOutput = TW_Nimiq_Proto_SigningOutput extension NimiqAddress: Address {}
34.769231
77
0.809735
876e10da3b80a210db27e2fa6c9db28ecea0d717
9,416
// // PaperOnboarding.swift // AnimatedPageView // // Created by Alex K. on 20/04/16. // Copyright © 2016 Alex K. All rights reserved. // import UIKit public struct OnboardingItemInfo { public let informationImage: UIImage public let title: String public let description: String public let pageIcon: UIImage public let color: UIColor public let titleColor: UIColor public let descriptionColor: UIColor public let titleFont: UIFont public let descriptionFont: UIFont public let descriptionLabelPadding: CGFloat public let titleLabelPadding: CGFloat public init (informationImage: UIImage, title: String, description: String, pageIcon: UIImage, color: UIColor, titleColor: UIColor, descriptionColor: UIColor, titleFont: UIFont, descriptionFont: UIFont, descriptionLabelPadding: CGFloat = 0, titleLabelPadding: CGFloat = 0) { self.informationImage = informationImage self.title = title self.description = description self.pageIcon = pageIcon self.color = color self.titleColor = titleColor self.descriptionColor = descriptionColor self.titleFont = titleFont self.descriptionFont = descriptionFont self.descriptionLabelPadding = descriptionLabelPadding self.titleLabelPadding = titleLabelPadding } } /// An instance of PaperOnboarding which display collection of information. open class PaperOnboarding: UIView { /// The object that acts as the data source of the PaperOnboardingDataSource. @IBOutlet weak open var dataSource: AnyObject? { didSet { commonInit() } } /// The object that acts as the delegate of the PaperOnboarding. PaperOnboardingDelegate protocol @IBOutlet weak open var delegate: AnyObject? /// current index item open fileprivate(set) var currentIndex: Int = 0 fileprivate(set) var itemsCount: Int = 0 fileprivate var itemsInfo: [OnboardingItemInfo]? fileprivate let pageViewBottomConstant: CGFloat fileprivate var pageViewSelectedRadius: CGFloat = 22 fileprivate var pageViewRadius: CGFloat = 8 fileprivate var fillAnimationView: FillAnimationView? fileprivate var pageView: PageView? public fileprivate(set) var gestureControl: GestureControl? fileprivate var contentView: OnboardingContentView? public init(pageViewBottomConstant: CGFloat = 32) { self.pageViewBottomConstant = pageViewBottomConstant super.init(frame: CGRect.zero) } public required init?(coder aDecoder: NSCoder) { self.pageViewBottomConstant = 32 self.pageViewSelectedRadius = 22 self.pageViewRadius = 8 super.init(coder: aDecoder) } } // MARK: methods public extension PaperOnboarding { /** Scrolls through the PaperOnboarding until a index is at a particular location on the screen. - parameter index: Scrolling to a curretn index item. - parameter animated: True if you want to animate the change in position; false if it should be immediate. */ func currentIndex(_ index: Int, animated: Bool) { if 0 ..< itemsCount ~= index { (delegate as? PaperOnboardingDelegate)?.onboardingWillTransitonToIndex(index) currentIndex = index CATransaction.begin() CATransaction.setCompletionBlock({ (self.delegate as? PaperOnboardingDelegate)?.onboardingDidTransitonToIndex(index) }) if let postion = pageView?.positionItemIndex(index, onView: self) { fillAnimationView?.fillAnimation(backgroundColor(currentIndex), centerPosition: postion, duration: 0.5) } pageView?.currentIndex(index, animated: animated) contentView?.currentItem(index, animated: animated) CATransaction.commit() } else if index >= itemsCount { (delegate as? PaperOnboardingDelegate)?.onboardingWillTransitonToLeaving() } } } // MARK: create extension PaperOnboarding { fileprivate func commonInit() { if case let dataSource as PaperOnboardingDataSource = dataSource { itemsCount = dataSource.onboardingItemsCount() } if case let dataSource as PaperOnboardingDataSource = dataSource { pageViewRadius = dataSource.onboardinPageItemRadius() } if case let dataSource as PaperOnboardingDataSource = dataSource { pageViewSelectedRadius = dataSource.onboardingPageItemSelectedRadius() } itemsInfo = createItemsInfo() translatesAutoresizingMaskIntoConstraints = false fillAnimationView = FillAnimationView.animationViewOnView(self, color: backgroundColor(currentIndex)) contentView = OnboardingContentView.contentViewOnView(self, delegate: self, itemsCount: itemsCount, bottomConstant: pageViewBottomConstant * -1 - pageViewSelectedRadius) pageView = createPageView() gestureControl = GestureControl(view: self, delegate: self) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapAction)) addGestureRecognizer(tapGesture) } @objc fileprivate func tapAction(_ sender: UITapGestureRecognizer) { guard (delegate as? PaperOnboardingDelegate)?.enableTapsOnPageControl == true, let pageView = self.pageView, let pageControl = pageView.containerView else { return } let touchLocation = sender.location(in: self) let convertedLocation = pageControl.convert(touchLocation, from: self) guard let pageItem = pageView.hitTest(convertedLocation, with: nil) else { return } let index = pageItem.tag - 1 guard index != currentIndex else { return } currentIndex(index, animated: true) (delegate as? PaperOnboardingDelegate)?.onboardingWillTransitonToIndex(index) } fileprivate func createPageView() -> PageView { let screenMaxLength = max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) let iPhone10 = UIDevice.current.userInterfaceIdiom == .phone && screenMaxLength >= 812.0 if iPhone10{ let pageView = PageView.pageViewOnView( self, itemsCount: itemsCount, bottomConstant: pageViewBottomConstant * -0.7, radius: pageViewRadius, selectedRadius: pageViewSelectedRadius - 3, itemColor: { [weak self] in guard let dataSource = self?.dataSource as? PaperOnboardingDataSource else { return .white } return dataSource.onboardingPageItemColor(at: $0) }) pageView.configuration = { [weak self] item, index in item.imageView?.image = self?.itemsInfo?[index].pageIcon } return pageView }else{ let pageView = PageView.pageViewOnView( self, itemsCount: itemsCount, bottomConstant: pageViewBottomConstant * -0.3, radius: pageViewRadius, selectedRadius: pageViewSelectedRadius - 3, itemColor: { [weak self] in guard let dataSource = self?.dataSource as? PaperOnboardingDataSource else { return .white } return dataSource.onboardingPageItemColor(at: $0) }) pageView.configuration = { [weak self] item, index in item.imageView?.image = self?.itemsInfo?[index].pageIcon } return pageView } } fileprivate func createItemsInfo() -> [OnboardingItemInfo] { guard case let dataSource as PaperOnboardingDataSource = self.dataSource else { fatalError("set dataSource") } var items = [OnboardingItemInfo]() for index in 0 ..< itemsCount { let info = dataSource.onboardingItem(at: index) items.append(info) } return items } } // MARK: helpers extension PaperOnboarding { fileprivate func backgroundColor(_ index: Int) -> UIColor { guard let color = itemsInfo?[index].color else { return .black } return color } } // MARK: GestureControlDelegate extension PaperOnboarding: GestureControlDelegate { func gestureControlDidSwipe(_ direction: UISwipeGestureRecognizer.Direction) { switch direction { case UISwipeGestureRecognizer.Direction.right: currentIndex(currentIndex - 1, animated: true) case UISwipeGestureRecognizer.Direction.left: currentIndex(currentIndex + 1, animated: true) default: fatalError() } } } // MARK: OnboardingDelegate extension PaperOnboarding: OnboardingContentViewDelegate { func onboardingItemAtIndex(_ index: Int) -> OnboardingItemInfo? { return itemsInfo?[index] } @objc func onboardingConfigurationItem(_ item: OnboardingContentViewItem, index: Int) { (delegate as? PaperOnboardingDelegate)?.onboardingConfigurationItem(item, index: index) } }
37.513944
278
0.65102
14863914ac879b3d44912969d4d943fc70ae9b01
8,523
// Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // A copy of the License is located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license" file accompanying this file. This file 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. // // SmokeHTTP1HandlerSelector+futureFromProviderWithInputWithOutput.swift // SmokeOperationsHTTP1 // import Foundation import SmokeOperations import NIOHTTP1 import SmokeOperationsHTTP1 import NIO import SmokeAsync import Logging public extension SmokeHTTP1HandlerSelector { /** Adds a handler for the specified uri and http method. - Parameters: - operationIdentifer: The identifer for the handler being added. - httpMethod: The HTTP method this handler will respond to. - operationProvider: when given a `ContextType` instance will provide the handler method for the operation. - allowedErrors: the errors that can be serialized as responses from the operation and their error codes. - inputLocation: the location in the incoming http request to decode the input from. - outputLocation: the location in the outgoing http response to place the encoded output. */ mutating func addHandlerForOperationProvider<InputType: ValidatableCodable, OutputType: ValidatableCodable, ErrorType: ErrorIdentifiableByDescription>( _ operationIdentifer: OperationIdentifer, httpMethod: HTTPMethod, operationProvider: @escaping ((ContextType) -> ((InputType) throws -> EventLoopFuture<OutputType>)), allowedErrors: [(ErrorType, Int)], inputLocation: OperationInputHTTPLocation, outputLocation: OperationOutputHTTPLocation) { func operation(input: InputType, context: ContextType) throws -> EventLoopFuture<OutputType> { let innerOperation = operationProvider(context) return try innerOperation(input) } addHandlerForOperation(operationIdentifer, httpMethod: httpMethod, operation: operation, allowedErrors: allowedErrors, inputLocation: inputLocation, outputLocation: outputLocation) } /** Adds a handler for the specified uri and http method. - Parameters: - operationIdentifer: The identifer for the handler being added. - httpMethod: The HTTP method this handler will respond to. - operationProvider: when given a `ContextType` instance will provide the handler method for the operation. - allowedErrors: the errors that can be serialized as responses from the operation and their error codes. - inputLocation: the location in the incoming http request to decode the input from. - outputLocation: the location in the outgoing http response to place the encoded output. - operationDelegate: an operation-specific delegate to use when handling the operation. */ mutating func addHandlerForOperationProvider<InputType: ValidatableCodable, OutputType: ValidatableCodable, ErrorType: ErrorIdentifiableByDescription, OperationDelegateType: HTTP1OperationDelegate> ( _ operationIdentifer: OperationIdentifer, httpMethod: HTTPMethod, operationProvider: @escaping ((ContextType) -> ((InputType) throws -> EventLoopFuture<OutputType>)), allowedErrors: [(ErrorType, Int)], inputLocation: OperationInputHTTPLocation, outputLocation: OperationOutputHTTPLocation, operationDelegate: OperationDelegateType) where DefaultOperationDelegateType.RequestHeadType == OperationDelegateType.RequestHeadType, DefaultOperationDelegateType.InvocationReportingType == OperationDelegateType.InvocationReportingType, DefaultOperationDelegateType.ResponseHandlerType == OperationDelegateType.ResponseHandlerType { func operation(input: InputType, context: ContextType) throws -> EventLoopFuture<OutputType> { let innerOperation = operationProvider(context) return try innerOperation(input) } addHandlerForOperation(operationIdentifer, httpMethod: httpMethod, operation: operation, allowedErrors: allowedErrors, inputLocation: inputLocation, outputLocation: outputLocation, operationDelegate: operationDelegate) } /** Adds a handler for the specified uri and http method. - Parameters: - operationIdentifer: The identifer for the handler being added. - httpMethod: The HTTP method this handler will respond to. - operationProvider: when given a `ContextType` instance will provide the handler method for the operation. - allowedErrors: the errors that can be serialized as responses from the operation and their error codes. */ mutating func addHandlerForOperationProvider<InputType: ValidatableOperationHTTP1InputProtocol, OutputType: ValidatableOperationHTTP1OutputProtocol, ErrorType: ErrorIdentifiableByDescription>( _ operationIdentifer: OperationIdentifer, httpMethod: HTTPMethod, operationProvider: @escaping ((ContextType) -> ((InputType) throws -> EventLoopFuture<OutputType>)), allowedErrors: [(ErrorType, Int)]) { func operation(input: InputType, context: ContextType) throws -> EventLoopFuture<OutputType> { let innerOperation = operationProvider(context) return try innerOperation(input) } addHandlerForOperation(operationIdentifer, httpMethod: httpMethod, operation: operation, allowedErrors: allowedErrors) } /** Adds a handler for the specified uri and http method. - Parameters: - operationIdentifer: The identifer for the handler being added. - httpMethod: The HTTP method this handler will respond to. - operationProvider: when given a `ContextType` instance will provide the handler method for the operation. - allowedErrors: the errors that can be serialized as responses from the operation and their error codes. - operationDelegate: an operation-specific delegate to use when handling the operation. */ mutating func addHandlerForOperationProvider<InputType: ValidatableOperationHTTP1InputProtocol, OutputType: ValidatableOperationHTTP1OutputProtocol, ErrorType: ErrorIdentifiableByDescription, OperationDelegateType: HTTP1OperationDelegate>( _ operationIdentifer: OperationIdentifer, httpMethod: HTTPMethod, operationProvider: @escaping ((ContextType) -> ((InputType) throws -> EventLoopFuture<OutputType>)), allowedErrors: [(ErrorType, Int)], operationDelegate: OperationDelegateType) where DefaultOperationDelegateType.RequestHeadType == OperationDelegateType.RequestHeadType, DefaultOperationDelegateType.InvocationReportingType == OperationDelegateType.InvocationReportingType, DefaultOperationDelegateType.ResponseHandlerType == OperationDelegateType.ResponseHandlerType { func operation(input: InputType, context: ContextType) throws -> EventLoopFuture<OutputType> { let innerOperation = operationProvider(context) return try innerOperation(input) } addHandlerForOperation(operationIdentifer, httpMethod: httpMethod, operation: operation, allowedErrors: allowedErrors, operationDelegate: operationDelegate) } }
52.611111
152
0.668779
9c770290a36e27bc4685955e9af9500962b0e50f
3,391
// // Created by Natsuki on 2019-08-13. // Copyright (c) 2019 All rights reserved. // import UIKit class SwipebackNavigationController: UINavigationController { // should we respect View Controller individual NavigationBar setting var individualNavigationBarAppearance = false private lazy var swipebackGesture: UIPanGestureRecognizer = { let swipebackGesture = UIPanGestureRecognizer() (interactivePopGestureRecognizer?.value(forKey: "targets") as? [NSObject]).flatMap { $0.first?.value(forKey: "target") }.map { target in let selector = NSSelectorFromString("handleNavigationTransition:") swipebackGesture.delegate = self swipebackGesture.addTarget(target, action: selector) } interactivePopGestureRecognizer?.view?.addGestureRecognizer(swipebackGesture) interactivePopGestureRecognizer?.isEnabled = false return swipebackGesture }() override func pushViewController(_ viewController: UIViewController, animated: Bool) { _ = swipebackGesture super.pushViewController(viewController, animated: animated) } } extension SwipebackNavigationController: UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard viewControllers.count > 1, let last = viewControllers.last, last.swipebackEnabled else { return false } let xOffset = Int(gestureRecognizer.location(in: gestureRecognizer.view).x) if case let SwipeDistance.atMost(distance) = last.swipeDistanceThreshold, distance < xOffset { return false } guard let transition = value(forKey: "_isTransitioning") as? Bool, !transition else { return false } return (gestureRecognizer as? UIPanGestureRecognizer).map { ($0.translation(in: $0.view).x > CGFloat(0.0)) ^ (UIApplication.shared.userInterfaceLayoutDirection == .leftToRight) } ?? false } } protocol Swipebackable { var swipebackEnabled: Bool { get } var preferNavigationBarHidden: Bool { get } var swipeDistanceThreshold: SwipeDistance { get } } class SwipebackViewController: UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (navigationController as? SwipebackNavigationController)?.individualNavigationBarAppearance ?? false { navigationController?.setNavigationBarHidden(preferNavigationBarHidden, animated: animated) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) DispatchQueue.main.async { [weak self] in if !(self?.navigationController?.viewControllers.last?.preferNavigationBarHidden ?? true) { self?.navigationController?.setNavigationBarHidden(false, animated: false) } } } } extension UIViewController: Swipebackable { var swipebackEnabled: Bool { return true } var preferNavigationBarHidden: Bool { return false } var swipeDistanceThreshold: SwipeDistance { return .always } } enum SwipeDistance { case always case atMost(distance: Int) } func ^(_ left: Bool, _ right: Bool) -> Bool { return (left && right) || (!left && !right) }
33.91
144
0.689177
d522a6fbfcd171caab1d02d0197aee954e2da055
96,330
// Copyright 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // NOTE: This file is automatically-generated! import Foundation import OAuth2 import GoogleAPIRuntime public class Bigquery : Service { public init(tokenProvider: TokenProvider) throws { try super.init(tokenProvider, "https://bigquery.googleapis.com/bigquery/v2/") } public class Object : Codable {} public struct AggregateClassificationMetrics : Codable { public init (`accuracy`: Double?, `f1Score`: Double?, `logLoss`: Double?, `precision`: Double?, `recall`: Double?, `rocAuc`: Double?, `threshold`: Double?) { self.`accuracy` = `accuracy` self.`f1Score` = `f1Score` self.`logLoss` = `logLoss` self.`precision` = `precision` self.`recall` = `recall` self.`rocAuc` = `rocAuc` self.`threshold` = `threshold` } public var `accuracy` : Double? public var `f1Score` : Double? public var `logLoss` : Double? public var `precision` : Double? public var `recall` : Double? public var `rocAuc` : Double? public var `threshold` : Double? } public struct Argument : Codable { public init (`argumentKind`: String?, `dataType`: StandardSqlDataType?, `mode`: String?, `name`: String?) { self.`argumentKind` = `argumentKind` self.`dataType` = `dataType` self.`mode` = `mode` self.`name` = `name` } public var `argumentKind` : String? public var `dataType` : StandardSqlDataType? public var `mode` : String? public var `name` : String? } public struct ArimaCoefficients : Codable { public init (`autoRegressiveCoefficients`: [Double]?, `interceptCoefficient`: Double?, `movingAverageCoefficients`: [Double]?) { self.`autoRegressiveCoefficients` = `autoRegressiveCoefficients` self.`interceptCoefficient` = `interceptCoefficient` self.`movingAverageCoefficients` = `movingAverageCoefficients` } public var `autoRegressiveCoefficients` : [Double]? public var `interceptCoefficient` : Double? public var `movingAverageCoefficients` : [Double]? } public struct ArimaFittingMetrics : Codable { public init (`aic`: Double?, `logLikelihood`: Double?, `variance`: Double?) { self.`aic` = `aic` self.`logLikelihood` = `logLikelihood` self.`variance` = `variance` } public var `aic` : Double? public var `logLikelihood` : Double? public var `variance` : Double? } public struct ArimaModelInfo : Codable { public init (`arimaCoefficients`: ArimaCoefficients?, `arimaFittingMetrics`: ArimaFittingMetrics?, `nonSeasonalOrder`: ArimaOrder?) { self.`arimaCoefficients` = `arimaCoefficients` self.`arimaFittingMetrics` = `arimaFittingMetrics` self.`nonSeasonalOrder` = `nonSeasonalOrder` } public var `arimaCoefficients` : ArimaCoefficients? public var `arimaFittingMetrics` : ArimaFittingMetrics? public var `nonSeasonalOrder` : ArimaOrder? } public struct ArimaOrder : Codable { public init (`d`: String?, `p`: String?, `q`: String?) { self.`d` = `d` self.`p` = `p` self.`q` = `q` } public var `d` : String? public var `p` : String? public var `q` : String? } public struct ArimaResult : Codable { public init (`arimaModelInfo`: [ArimaModelInfo]?, `seasonalPeriods`: [String]?) { self.`arimaModelInfo` = `arimaModelInfo` self.`seasonalPeriods` = `seasonalPeriods` } public var `arimaModelInfo` : [ArimaModelInfo]? public var `seasonalPeriods` : [String]? } public struct BigQueryModelTraining : Codable { public init (`currentIteration`: Int?, `expectedTotalIterations`: String?) { self.`currentIteration` = `currentIteration` self.`expectedTotalIterations` = `expectedTotalIterations` } public var `currentIteration` : Int? public var `expectedTotalIterations` : String? } public struct BigtableColumn : Codable { public init (`encoding`: String?, `fieldName`: String?, `onlyReadLatest`: Bool?, `qualifierEncoded`: String?, `qualifierString`: String?, `type`: String?) { self.`encoding` = `encoding` self.`fieldName` = `fieldName` self.`onlyReadLatest` = `onlyReadLatest` self.`qualifierEncoded` = `qualifierEncoded` self.`qualifierString` = `qualifierString` self.`type` = `type` } public var `encoding` : String? public var `fieldName` : String? public var `onlyReadLatest` : Bool? public var `qualifierEncoded` : String? public var `qualifierString` : String? public var `type` : String? } public struct BigtableColumnFamily : Codable { public init (`columns`: [BigtableColumn]?, `encoding`: String?, `familyId`: String?, `onlyReadLatest`: Bool?, `type`: String?) { self.`columns` = `columns` self.`encoding` = `encoding` self.`familyId` = `familyId` self.`onlyReadLatest` = `onlyReadLatest` self.`type` = `type` } public var `columns` : [BigtableColumn]? public var `encoding` : String? public var `familyId` : String? public var `onlyReadLatest` : Bool? public var `type` : String? } public struct BigtableOptions : Codable { public init (`columnFamilies`: [BigtableColumnFamily]?, `ignoreUnspecifiedColumnFamilies`: Bool?, `readRowkeyAsString`: Bool?) { self.`columnFamilies` = `columnFamilies` self.`ignoreUnspecifiedColumnFamilies` = `ignoreUnspecifiedColumnFamilies` self.`readRowkeyAsString` = `readRowkeyAsString` } public var `columnFamilies` : [BigtableColumnFamily]? public var `ignoreUnspecifiedColumnFamilies` : Bool? public var `readRowkeyAsString` : Bool? } public struct BinaryClassificationMetrics : Codable { public init (`aggregateClassificationMetrics`: AggregateClassificationMetrics?, `binaryConfusionMatrixList`: [BinaryConfusionMatrix]?, `negativeLabel`: String?, `positiveLabel`: String?) { self.`aggregateClassificationMetrics` = `aggregateClassificationMetrics` self.`binaryConfusionMatrixList` = `binaryConfusionMatrixList` self.`negativeLabel` = `negativeLabel` self.`positiveLabel` = `positiveLabel` } public var `aggregateClassificationMetrics` : AggregateClassificationMetrics? public var `binaryConfusionMatrixList` : [BinaryConfusionMatrix]? public var `negativeLabel` : String? public var `positiveLabel` : String? } public struct BinaryConfusionMatrix : Codable { public init (`accuracy`: Double?, `f1Score`: Double?, `falseNegatives`: String?, `falsePositives`: String?, `positiveClassThreshold`: Double?, `precision`: Double?, `recall`: Double?, `trueNegatives`: String?, `truePositives`: String?) { self.`accuracy` = `accuracy` self.`f1Score` = `f1Score` self.`falseNegatives` = `falseNegatives` self.`falsePositives` = `falsePositives` self.`positiveClassThreshold` = `positiveClassThreshold` self.`precision` = `precision` self.`recall` = `recall` self.`trueNegatives` = `trueNegatives` self.`truePositives` = `truePositives` } public var `accuracy` : Double? public var `f1Score` : Double? public var `falseNegatives` : String? public var `falsePositives` : String? public var `positiveClassThreshold` : Double? public var `precision` : Double? public var `recall` : Double? public var `trueNegatives` : String? public var `truePositives` : String? } public struct BqmlIterationResult : Codable { public init (`durationMs`: String?, `evalLoss`: Double?, `index`: Int?, `learnRate`: Double?, `trainingLoss`: Double?) { self.`durationMs` = `durationMs` self.`evalLoss` = `evalLoss` self.`index` = `index` self.`learnRate` = `learnRate` self.`trainingLoss` = `trainingLoss` } public var `durationMs` : String? public var `evalLoss` : Double? public var `index` : Int? public var `learnRate` : Double? public var `trainingLoss` : Double? } public struct BqmlTrainingRun : Codable { public init (`iterationResults`: [BqmlIterationResult]?, `startTime`: String?, `state`: String?, `trainingOptions`: Object?) { self.`iterationResults` = `iterationResults` self.`startTime` = `startTime` self.`state` = `state` self.`trainingOptions` = `trainingOptions` } public var `iterationResults` : [BqmlIterationResult]? public var `startTime` : String? public var `state` : String? public var `trainingOptions` : Object? } public struct CategoricalValue : Codable { public init (`categoryCounts`: [CategoryCount]?) { self.`categoryCounts` = `categoryCounts` } public var `categoryCounts` : [CategoryCount]? } public struct CategoryCount : Codable { public init (`category`: String?, `count`: String?) { self.`category` = `category` self.`count` = `count` } public var `category` : String? public var `count` : String? } public struct Cluster : Codable { public init (`centroidId`: String?, `count`: String?, `featureValues`: [FeatureValue]?) { self.`centroidId` = `centroidId` self.`count` = `count` self.`featureValues` = `featureValues` } public var `centroidId` : String? public var `count` : String? public var `featureValues` : [FeatureValue]? } public struct ClusterInfo : Codable { public init (`centroidId`: String?, `clusterRadius`: Double?, `clusterSize`: String?) { self.`centroidId` = `centroidId` self.`clusterRadius` = `clusterRadius` self.`clusterSize` = `clusterSize` } public var `centroidId` : String? public var `clusterRadius` : Double? public var `clusterSize` : String? } public struct Clustering : Codable { public init (`fields`: [String]?) { self.`fields` = `fields` } public var `fields` : [String]? } public struct ClusteringMetrics : Codable { public init (`clusters`: [Cluster]?, `daviesBouldinIndex`: Double?, `meanSquaredDistance`: Double?) { self.`clusters` = `clusters` self.`daviesBouldinIndex` = `daviesBouldinIndex` self.`meanSquaredDistance` = `meanSquaredDistance` } public var `clusters` : [Cluster]? public var `daviesBouldinIndex` : Double? public var `meanSquaredDistance` : Double? } public struct ConfusionMatrix : Codable { public init (`confidenceThreshold`: Double?, `rows`: [Row]?) { self.`confidenceThreshold` = `confidenceThreshold` self.`rows` = `rows` } public var `confidenceThreshold` : Double? public var `rows` : [Row]? } public struct CsvOptions : Codable { public init (`allowJaggedRows`: Bool?, `allowQuotedNewlines`: Bool?, `encoding`: String?, `fieldDelimiter`: String?, `quote`: String?, `skipLeadingRows`: String?) { self.`allowJaggedRows` = `allowJaggedRows` self.`allowQuotedNewlines` = `allowQuotedNewlines` self.`encoding` = `encoding` self.`fieldDelimiter` = `fieldDelimiter` self.`quote` = `quote` self.`skipLeadingRows` = `skipLeadingRows` } public var `allowJaggedRows` : Bool? public var `allowQuotedNewlines` : Bool? public var `encoding` : String? public var `fieldDelimiter` : String? public var `quote` : String? public var `skipLeadingRows` : String? } public struct DataSplitResult : Codable { public init (`evaluationTable`: TableReference?, `trainingTable`: TableReference?) { self.`evaluationTable` = `evaluationTable` self.`trainingTable` = `trainingTable` } public var `evaluationTable` : TableReference? public var `trainingTable` : TableReference? } public struct Dataset : Codable { public init (`access`: [Object]?, `creationTime`: String?, `datasetReference`: DatasetReference?, `defaultEncryptionConfiguration`: EncryptionConfiguration?, `defaultPartitionExpirationMs`: String?, `defaultTableExpirationMs`: String?, `description`: String?, `etag`: String?, `friendlyName`: String?, `id`: String?, `kind`: String?, `labels`: Object?, `lastModifiedTime`: String?, `location`: String?, `selfLink`: String?) { self.`access` = `access` self.`creationTime` = `creationTime` self.`datasetReference` = `datasetReference` self.`defaultEncryptionConfiguration` = `defaultEncryptionConfiguration` self.`defaultPartitionExpirationMs` = `defaultPartitionExpirationMs` self.`defaultTableExpirationMs` = `defaultTableExpirationMs` self.`description` = `description` self.`etag` = `etag` self.`friendlyName` = `friendlyName` self.`id` = `id` self.`kind` = `kind` self.`labels` = `labels` self.`lastModifiedTime` = `lastModifiedTime` self.`location` = `location` self.`selfLink` = `selfLink` } public var `access` : [Object]? public var `creationTime` : String? public var `datasetReference` : DatasetReference? public var `defaultEncryptionConfiguration` : EncryptionConfiguration? public var `defaultPartitionExpirationMs` : String? public var `defaultTableExpirationMs` : String? public var `description` : String? public var `etag` : String? public var `friendlyName` : String? public var `id` : String? public var `kind` : String? public var `labels` : Object? public var `lastModifiedTime` : String? public var `location` : String? public var `selfLink` : String? } public struct DatasetList : Codable { public init (`datasets`: [Object]?, `etag`: String?, `kind`: String?, `nextPageToken`: String?) { self.`datasets` = `datasets` self.`etag` = `etag` self.`kind` = `kind` self.`nextPageToken` = `nextPageToken` } public var `datasets` : [Object]? public var `etag` : String? public var `kind` : String? public var `nextPageToken` : String? } public struct DatasetReference : Codable { public init (`datasetId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` } public var `datasetId` : String? public var `projectId` : String? } public struct DestinationTableProperties : Codable { public init (`description`: String?, `friendlyName`: String?, `labels`: Object?) { self.`description` = `description` self.`friendlyName` = `friendlyName` self.`labels` = `labels` } public var `description` : String? public var `friendlyName` : String? public var `labels` : Object? } public struct EncryptionConfiguration : Codable { public init (`kmsKeyName`: String?) { self.`kmsKeyName` = `kmsKeyName` } public var `kmsKeyName` : String? } public struct Entry : Codable { public init (`itemCount`: String?, `predictedLabel`: String?) { self.`itemCount` = `itemCount` self.`predictedLabel` = `predictedLabel` } public var `itemCount` : String? public var `predictedLabel` : String? } public struct ErrorProto : Codable { public init (`debugInfo`: String?, `location`: String?, `message`: String?, `reason`: String?) { self.`debugInfo` = `debugInfo` self.`location` = `location` self.`message` = `message` self.`reason` = `reason` } public var `debugInfo` : String? public var `location` : String? public var `message` : String? public var `reason` : String? } public struct EvaluationMetrics : Codable { public init (`binaryClassificationMetrics`: BinaryClassificationMetrics?, `clusteringMetrics`: ClusteringMetrics?, `multiClassClassificationMetrics`: MultiClassClassificationMetrics?, `regressionMetrics`: RegressionMetrics?) { self.`binaryClassificationMetrics` = `binaryClassificationMetrics` self.`clusteringMetrics` = `clusteringMetrics` self.`multiClassClassificationMetrics` = `multiClassClassificationMetrics` self.`regressionMetrics` = `regressionMetrics` } public var `binaryClassificationMetrics` : BinaryClassificationMetrics? public var `clusteringMetrics` : ClusteringMetrics? public var `multiClassClassificationMetrics` : MultiClassClassificationMetrics? public var `regressionMetrics` : RegressionMetrics? } public struct ExplainQueryStage : Codable { public init (`completedParallelInputs`: String?, `computeMsAvg`: String?, `computeMsMax`: String?, `computeRatioAvg`: Double?, `computeRatioMax`: Double?, `endMs`: String?, `id`: String?, `inputStages`: [String]?, `name`: String?, `parallelInputs`: String?, `readMsAvg`: String?, `readMsMax`: String?, `readRatioAvg`: Double?, `readRatioMax`: Double?, `recordsRead`: String?, `recordsWritten`: String?, `shuffleOutputBytes`: String?, `shuffleOutputBytesSpilled`: String?, `slotMs`: String?, `startMs`: String?, `status`: String?, `steps`: [ExplainQueryStep]?, `waitMsAvg`: String?, `waitMsMax`: String?, `waitRatioAvg`: Double?, `waitRatioMax`: Double?, `writeMsAvg`: String?, `writeMsMax`: String?, `writeRatioAvg`: Double?, `writeRatioMax`: Double?) { self.`completedParallelInputs` = `completedParallelInputs` self.`computeMsAvg` = `computeMsAvg` self.`computeMsMax` = `computeMsMax` self.`computeRatioAvg` = `computeRatioAvg` self.`computeRatioMax` = `computeRatioMax` self.`endMs` = `endMs` self.`id` = `id` self.`inputStages` = `inputStages` self.`name` = `name` self.`parallelInputs` = `parallelInputs` self.`readMsAvg` = `readMsAvg` self.`readMsMax` = `readMsMax` self.`readRatioAvg` = `readRatioAvg` self.`readRatioMax` = `readRatioMax` self.`recordsRead` = `recordsRead` self.`recordsWritten` = `recordsWritten` self.`shuffleOutputBytes` = `shuffleOutputBytes` self.`shuffleOutputBytesSpilled` = `shuffleOutputBytesSpilled` self.`slotMs` = `slotMs` self.`startMs` = `startMs` self.`status` = `status` self.`steps` = `steps` self.`waitMsAvg` = `waitMsAvg` self.`waitMsMax` = `waitMsMax` self.`waitRatioAvg` = `waitRatioAvg` self.`waitRatioMax` = `waitRatioMax` self.`writeMsAvg` = `writeMsAvg` self.`writeMsMax` = `writeMsMax` self.`writeRatioAvg` = `writeRatioAvg` self.`writeRatioMax` = `writeRatioMax` } public var `completedParallelInputs` : String? public var `computeMsAvg` : String? public var `computeMsMax` : String? public var `computeRatioAvg` : Double? public var `computeRatioMax` : Double? public var `endMs` : String? public var `id` : String? public var `inputStages` : [String]? public var `name` : String? public var `parallelInputs` : String? public var `readMsAvg` : String? public var `readMsMax` : String? public var `readRatioAvg` : Double? public var `readRatioMax` : Double? public var `recordsRead` : String? public var `recordsWritten` : String? public var `shuffleOutputBytes` : String? public var `shuffleOutputBytesSpilled` : String? public var `slotMs` : String? public var `startMs` : String? public var `status` : String? public var `steps` : [ExplainQueryStep]? public var `waitMsAvg` : String? public var `waitMsMax` : String? public var `waitRatioAvg` : Double? public var `waitRatioMax` : Double? public var `writeMsAvg` : String? public var `writeMsMax` : String? public var `writeRatioAvg` : Double? public var `writeRatioMax` : Double? } public struct ExplainQueryStep : Codable { public init (`kind`: String?, `substeps`: [String]?) { self.`kind` = `kind` self.`substeps` = `substeps` } public var `kind` : String? public var `substeps` : [String]? } public struct ExternalDataConfiguration : Codable { public init (`autodetect`: Bool?, `bigtableOptions`: BigtableOptions?, `compression`: String?, `csvOptions`: CsvOptions?, `googleSheetsOptions`: GoogleSheetsOptions?, `hivePartitioningMode`: String?, `hivePartitioningOptions`: HivePartitioningOptions?, `ignoreUnknownValues`: Bool?, `maxBadRecords`: Int?, `schema`: TableSchema?, `sourceFormat`: String?, `sourceUris`: [String]?) { self.`autodetect` = `autodetect` self.`bigtableOptions` = `bigtableOptions` self.`compression` = `compression` self.`csvOptions` = `csvOptions` self.`googleSheetsOptions` = `googleSheetsOptions` self.`hivePartitioningMode` = `hivePartitioningMode` self.`hivePartitioningOptions` = `hivePartitioningOptions` self.`ignoreUnknownValues` = `ignoreUnknownValues` self.`maxBadRecords` = `maxBadRecords` self.`schema` = `schema` self.`sourceFormat` = `sourceFormat` self.`sourceUris` = `sourceUris` } public var `autodetect` : Bool? public var `bigtableOptions` : BigtableOptions? public var `compression` : String? public var `csvOptions` : CsvOptions? public var `googleSheetsOptions` : GoogleSheetsOptions? public var `hivePartitioningMode` : String? public var `hivePartitioningOptions` : HivePartitioningOptions? public var `ignoreUnknownValues` : Bool? public var `maxBadRecords` : Int? public var `schema` : TableSchema? public var `sourceFormat` : String? public var `sourceUris` : [String]? } public struct FeatureValue : Codable { public init (`categoricalValue`: CategoricalValue?, `featureColumn`: String?, `numericalValue`: Double?) { self.`categoricalValue` = `categoricalValue` self.`featureColumn` = `featureColumn` self.`numericalValue` = `numericalValue` } public var `categoricalValue` : CategoricalValue? public var `featureColumn` : String? public var `numericalValue` : Double? } public struct GetQueryResultsResponse : Codable { public init (`cacheHit`: Bool?, `errors`: [ErrorProto]?, `etag`: String?, `jobComplete`: Bool?, `jobReference`: JobReference?, `kind`: String?, `numDmlAffectedRows`: String?, `pageToken`: String?, `rows`: [TableRow]?, `schema`: TableSchema?, `totalBytesProcessed`: String?, `totalRows`: String?) { self.`cacheHit` = `cacheHit` self.`errors` = `errors` self.`etag` = `etag` self.`jobComplete` = `jobComplete` self.`jobReference` = `jobReference` self.`kind` = `kind` self.`numDmlAffectedRows` = `numDmlAffectedRows` self.`pageToken` = `pageToken` self.`rows` = `rows` self.`schema` = `schema` self.`totalBytesProcessed` = `totalBytesProcessed` self.`totalRows` = `totalRows` } public var `cacheHit` : Bool? public var `errors` : [ErrorProto]? public var `etag` : String? public var `jobComplete` : Bool? public var `jobReference` : JobReference? public var `kind` : String? public var `numDmlAffectedRows` : String? public var `pageToken` : String? public var `rows` : [TableRow]? public var `schema` : TableSchema? public var `totalBytesProcessed` : String? public var `totalRows` : String? } public struct GetServiceAccountResponse : Codable { public init (`email`: String?, `kind`: String?) { self.`email` = `email` self.`kind` = `kind` } public var `email` : String? public var `kind` : String? } public struct GoogleSheetsOptions : Codable { public init (`range`: String?, `skipLeadingRows`: String?) { self.`range` = `range` self.`skipLeadingRows` = `skipLeadingRows` } public var `range` : String? public var `skipLeadingRows` : String? } public struct HivePartitioningOptions : Codable { public init (`mode`: String?, `sourceUriPrefix`: String?) { self.`mode` = `mode` self.`sourceUriPrefix` = `sourceUriPrefix` } public var `mode` : String? public var `sourceUriPrefix` : String? } public struct IterationResult : Codable { public init (`arimaResult`: ArimaResult?, `clusterInfos`: [ClusterInfo]?, `durationMs`: String?, `evalLoss`: Double?, `index`: Int?, `learnRate`: Double?, `trainingLoss`: Double?) { self.`arimaResult` = `arimaResult` self.`clusterInfos` = `clusterInfos` self.`durationMs` = `durationMs` self.`evalLoss` = `evalLoss` self.`index` = `index` self.`learnRate` = `learnRate` self.`trainingLoss` = `trainingLoss` } public var `arimaResult` : ArimaResult? public var `clusterInfos` : [ClusterInfo]? public var `durationMs` : String? public var `evalLoss` : Double? public var `index` : Int? public var `learnRate` : Double? public var `trainingLoss` : Double? } public struct Job : Codable { public init (`configuration`: JobConfiguration?, `etag`: String?, `id`: String?, `jobReference`: JobReference?, `kind`: String?, `selfLink`: String?, `statistics`: JobStatistics?, `status`: JobStatus?, `user_email`: String?) { self.`configuration` = `configuration` self.`etag` = `etag` self.`id` = `id` self.`jobReference` = `jobReference` self.`kind` = `kind` self.`selfLink` = `selfLink` self.`statistics` = `statistics` self.`status` = `status` self.`user_email` = `user_email` } public var `configuration` : JobConfiguration? public var `etag` : String? public var `id` : String? public var `jobReference` : JobReference? public var `kind` : String? public var `selfLink` : String? public var `statistics` : JobStatistics? public var `status` : JobStatus? public var `user_email` : String? } public struct JobCancelResponse : Codable { public init (`job`: Job?, `kind`: String?) { self.`job` = `job` self.`kind` = `kind` } public var `job` : Job? public var `kind` : String? } public struct JobConfiguration : Codable { public init (`copy`: JobConfigurationTableCopy?, `dryRun`: Bool?, `extract`: JobConfigurationExtract?, `jobTimeoutMs`: String?, `jobType`: String?, `labels`: Object?, `load`: JobConfigurationLoad?, `query`: JobConfigurationQuery?) { self.`copy` = `copy` self.`dryRun` = `dryRun` self.`extract` = `extract` self.`jobTimeoutMs` = `jobTimeoutMs` self.`jobType` = `jobType` self.`labels` = `labels` self.`load` = `load` self.`query` = `query` } public var `copy` : JobConfigurationTableCopy? public var `dryRun` : Bool? public var `extract` : JobConfigurationExtract? public var `jobTimeoutMs` : String? public var `jobType` : String? public var `labels` : Object? public var `load` : JobConfigurationLoad? public var `query` : JobConfigurationQuery? } public struct JobConfigurationExtract : Codable { public init (`compression`: String?, `destinationFormat`: String?, `destinationUri`: String?, `destinationUris`: [String]?, `fieldDelimiter`: String?, `printHeader`: Bool?, `sourceModel`: ModelReference?, `sourceTable`: TableReference?, `useAvroLogicalTypes`: Bool?) { self.`compression` = `compression` self.`destinationFormat` = `destinationFormat` self.`destinationUri` = `destinationUri` self.`destinationUris` = `destinationUris` self.`fieldDelimiter` = `fieldDelimiter` self.`printHeader` = `printHeader` self.`sourceModel` = `sourceModel` self.`sourceTable` = `sourceTable` self.`useAvroLogicalTypes` = `useAvroLogicalTypes` } public var `compression` : String? public var `destinationFormat` : String? public var `destinationUri` : String? public var `destinationUris` : [String]? public var `fieldDelimiter` : String? public var `printHeader` : Bool? public var `sourceModel` : ModelReference? public var `sourceTable` : TableReference? public var `useAvroLogicalTypes` : Bool? } public struct JobConfigurationLoad : Codable { public init (`allowJaggedRows`: Bool?, `allowQuotedNewlines`: Bool?, `autodetect`: Bool?, `clustering`: Clustering?, `createDisposition`: String?, `destinationEncryptionConfiguration`: EncryptionConfiguration?, `destinationTable`: TableReference?, `destinationTableProperties`: DestinationTableProperties?, `encoding`: String?, `fieldDelimiter`: String?, `hivePartitioningMode`: String?, `hivePartitioningOptions`: HivePartitioningOptions?, `ignoreUnknownValues`: Bool?, `maxBadRecords`: Int?, `nullMarker`: String?, `projectionFields`: [String]?, `quote`: String?, `rangePartitioning`: RangePartitioning?, `schema`: TableSchema?, `schemaInline`: String?, `schemaInlineFormat`: String?, `schemaUpdateOptions`: [String]?, `skipLeadingRows`: Int?, `sourceFormat`: String?, `sourceUris`: [String]?, `timePartitioning`: TimePartitioning?, `useAvroLogicalTypes`: Bool?, `writeDisposition`: String?) { self.`allowJaggedRows` = `allowJaggedRows` self.`allowQuotedNewlines` = `allowQuotedNewlines` self.`autodetect` = `autodetect` self.`clustering` = `clustering` self.`createDisposition` = `createDisposition` self.`destinationEncryptionConfiguration` = `destinationEncryptionConfiguration` self.`destinationTable` = `destinationTable` self.`destinationTableProperties` = `destinationTableProperties` self.`encoding` = `encoding` self.`fieldDelimiter` = `fieldDelimiter` self.`hivePartitioningMode` = `hivePartitioningMode` self.`hivePartitioningOptions` = `hivePartitioningOptions` self.`ignoreUnknownValues` = `ignoreUnknownValues` self.`maxBadRecords` = `maxBadRecords` self.`nullMarker` = `nullMarker` self.`projectionFields` = `projectionFields` self.`quote` = `quote` self.`rangePartitioning` = `rangePartitioning` self.`schema` = `schema` self.`schemaInline` = `schemaInline` self.`schemaInlineFormat` = `schemaInlineFormat` self.`schemaUpdateOptions` = `schemaUpdateOptions` self.`skipLeadingRows` = `skipLeadingRows` self.`sourceFormat` = `sourceFormat` self.`sourceUris` = `sourceUris` self.`timePartitioning` = `timePartitioning` self.`useAvroLogicalTypes` = `useAvroLogicalTypes` self.`writeDisposition` = `writeDisposition` } public var `allowJaggedRows` : Bool? public var `allowQuotedNewlines` : Bool? public var `autodetect` : Bool? public var `clustering` : Clustering? public var `createDisposition` : String? public var `destinationEncryptionConfiguration` : EncryptionConfiguration? public var `destinationTable` : TableReference? public var `destinationTableProperties` : DestinationTableProperties? public var `encoding` : String? public var `fieldDelimiter` : String? public var `hivePartitioningMode` : String? public var `hivePartitioningOptions` : HivePartitioningOptions? public var `ignoreUnknownValues` : Bool? public var `maxBadRecords` : Int? public var `nullMarker` : String? public var `projectionFields` : [String]? public var `quote` : String? public var `rangePartitioning` : RangePartitioning? public var `schema` : TableSchema? public var `schemaInline` : String? public var `schemaInlineFormat` : String? public var `schemaUpdateOptions` : [String]? public var `skipLeadingRows` : Int? public var `sourceFormat` : String? public var `sourceUris` : [String]? public var `timePartitioning` : TimePartitioning? public var `useAvroLogicalTypes` : Bool? public var `writeDisposition` : String? } public struct JobConfigurationQuery : Codable { public init (`allowLargeResults`: Bool?, `clustering`: Clustering?, `createDisposition`: String?, `defaultDataset`: DatasetReference?, `destinationEncryptionConfiguration`: EncryptionConfiguration?, `destinationTable`: TableReference?, `flattenResults`: Bool?, `maximumBillingTier`: Int?, `maximumBytesBilled`: String?, `parameterMode`: String?, `preserveNulls`: Bool?, `priority`: String?, `query`: String?, `queryParameters`: [QueryParameter]?, `rangePartitioning`: RangePartitioning?, `schemaUpdateOptions`: [String]?, `tableDefinitions`: Object?, `timePartitioning`: TimePartitioning?, `useLegacySql`: Bool?, `useQueryCache`: Bool?, `userDefinedFunctionResources`: [UserDefinedFunctionResource]?, `writeDisposition`: String?) { self.`allowLargeResults` = `allowLargeResults` self.`clustering` = `clustering` self.`createDisposition` = `createDisposition` self.`defaultDataset` = `defaultDataset` self.`destinationEncryptionConfiguration` = `destinationEncryptionConfiguration` self.`destinationTable` = `destinationTable` self.`flattenResults` = `flattenResults` self.`maximumBillingTier` = `maximumBillingTier` self.`maximumBytesBilled` = `maximumBytesBilled` self.`parameterMode` = `parameterMode` self.`preserveNulls` = `preserveNulls` self.`priority` = `priority` self.`query` = `query` self.`queryParameters` = `queryParameters` self.`rangePartitioning` = `rangePartitioning` self.`schemaUpdateOptions` = `schemaUpdateOptions` self.`tableDefinitions` = `tableDefinitions` self.`timePartitioning` = `timePartitioning` self.`useLegacySql` = `useLegacySql` self.`useQueryCache` = `useQueryCache` self.`userDefinedFunctionResources` = `userDefinedFunctionResources` self.`writeDisposition` = `writeDisposition` } public var `allowLargeResults` : Bool? public var `clustering` : Clustering? public var `createDisposition` : String? public var `defaultDataset` : DatasetReference? public var `destinationEncryptionConfiguration` : EncryptionConfiguration? public var `destinationTable` : TableReference? public var `flattenResults` : Bool? public var `maximumBillingTier` : Int? public var `maximumBytesBilled` : String? public var `parameterMode` : String? public var `preserveNulls` : Bool? public var `priority` : String? public var `query` : String? public var `queryParameters` : [QueryParameter]? public var `rangePartitioning` : RangePartitioning? public var `schemaUpdateOptions` : [String]? public var `tableDefinitions` : Object? public var `timePartitioning` : TimePartitioning? public var `useLegacySql` : Bool? public var `useQueryCache` : Bool? public var `userDefinedFunctionResources` : [UserDefinedFunctionResource]? public var `writeDisposition` : String? } public struct JobConfigurationTableCopy : Codable { public init (`createDisposition`: String?, `destinationEncryptionConfiguration`: EncryptionConfiguration?, `destinationTable`: TableReference?, `sourceTable`: TableReference?, `sourceTables`: [TableReference]?, `writeDisposition`: String?) { self.`createDisposition` = `createDisposition` self.`destinationEncryptionConfiguration` = `destinationEncryptionConfiguration` self.`destinationTable` = `destinationTable` self.`sourceTable` = `sourceTable` self.`sourceTables` = `sourceTables` self.`writeDisposition` = `writeDisposition` } public var `createDisposition` : String? public var `destinationEncryptionConfiguration` : EncryptionConfiguration? public var `destinationTable` : TableReference? public var `sourceTable` : TableReference? public var `sourceTables` : [TableReference]? public var `writeDisposition` : String? } public struct JobList : Codable { public init (`etag`: String?, `jobs`: [Object]?, `kind`: String?, `nextPageToken`: String?) { self.`etag` = `etag` self.`jobs` = `jobs` self.`kind` = `kind` self.`nextPageToken` = `nextPageToken` } public var `etag` : String? public var `jobs` : [Object]? public var `kind` : String? public var `nextPageToken` : String? } public struct JobReference : Codable { public init (`jobId`: String?, `location`: String?, `projectId`: String?) { self.`jobId` = `jobId` self.`location` = `location` self.`projectId` = `projectId` } public var `jobId` : String? public var `location` : String? public var `projectId` : String? } public struct JobStatistics : Codable { public init (`completionRatio`: Double?, `creationTime`: String?, `endTime`: String?, `extract`: JobStatistics4?, `load`: JobStatistics3?, `numChildJobs`: String?, `parentJobId`: String?, `query`: JobStatistics2?, `quotaDeferments`: [String]?, `reservationUsage`: [Object]?, `reservation_id`: String?, `scriptStatistics`: ScriptStatistics?, `startTime`: String?, `totalBytesProcessed`: String?, `totalSlotMs`: String?) { self.`completionRatio` = `completionRatio` self.`creationTime` = `creationTime` self.`endTime` = `endTime` self.`extract` = `extract` self.`load` = `load` self.`numChildJobs` = `numChildJobs` self.`parentJobId` = `parentJobId` self.`query` = `query` self.`quotaDeferments` = `quotaDeferments` self.`reservationUsage` = `reservationUsage` self.`reservation_id` = `reservation_id` self.`scriptStatistics` = `scriptStatistics` self.`startTime` = `startTime` self.`totalBytesProcessed` = `totalBytesProcessed` self.`totalSlotMs` = `totalSlotMs` } public var `completionRatio` : Double? public var `creationTime` : String? public var `endTime` : String? public var `extract` : JobStatistics4? public var `load` : JobStatistics3? public var `numChildJobs` : String? public var `parentJobId` : String? public var `query` : JobStatistics2? public var `quotaDeferments` : [String]? public var `reservationUsage` : [Object]? public var `reservation_id` : String? public var `scriptStatistics` : ScriptStatistics? public var `startTime` : String? public var `totalBytesProcessed` : String? public var `totalSlotMs` : String? } public struct JobStatistics2 : Codable { public init (`billingTier`: Int?, `cacheHit`: Bool?, `ddlOperationPerformed`: String?, `ddlTargetRoutine`: RoutineReference?, `ddlTargetTable`: TableReference?, `estimatedBytesProcessed`: String?, `modelTraining`: BigQueryModelTraining?, `modelTrainingCurrentIteration`: Int?, `modelTrainingExpectedTotalIteration`: String?, `numDmlAffectedRows`: String?, `queryPlan`: [ExplainQueryStage]?, `referencedRoutines`: [RoutineReference]?, `referencedTables`: [TableReference]?, `reservationUsage`: [Object]?, `schema`: TableSchema?, `statementType`: String?, `timeline`: [QueryTimelineSample]?, `totalBytesBilled`: String?, `totalBytesProcessed`: String?, `totalBytesProcessedAccuracy`: String?, `totalPartitionsProcessed`: String?, `totalSlotMs`: String?, `undeclaredQueryParameters`: [QueryParameter]?) { self.`billingTier` = `billingTier` self.`cacheHit` = `cacheHit` self.`ddlOperationPerformed` = `ddlOperationPerformed` self.`ddlTargetRoutine` = `ddlTargetRoutine` self.`ddlTargetTable` = `ddlTargetTable` self.`estimatedBytesProcessed` = `estimatedBytesProcessed` self.`modelTraining` = `modelTraining` self.`modelTrainingCurrentIteration` = `modelTrainingCurrentIteration` self.`modelTrainingExpectedTotalIteration` = `modelTrainingExpectedTotalIteration` self.`numDmlAffectedRows` = `numDmlAffectedRows` self.`queryPlan` = `queryPlan` self.`referencedRoutines` = `referencedRoutines` self.`referencedTables` = `referencedTables` self.`reservationUsage` = `reservationUsage` self.`schema` = `schema` self.`statementType` = `statementType` self.`timeline` = `timeline` self.`totalBytesBilled` = `totalBytesBilled` self.`totalBytesProcessed` = `totalBytesProcessed` self.`totalBytesProcessedAccuracy` = `totalBytesProcessedAccuracy` self.`totalPartitionsProcessed` = `totalPartitionsProcessed` self.`totalSlotMs` = `totalSlotMs` self.`undeclaredQueryParameters` = `undeclaredQueryParameters` } public var `billingTier` : Int? public var `cacheHit` : Bool? public var `ddlOperationPerformed` : String? public var `ddlTargetRoutine` : RoutineReference? public var `ddlTargetTable` : TableReference? public var `estimatedBytesProcessed` : String? public var `modelTraining` : BigQueryModelTraining? public var `modelTrainingCurrentIteration` : Int? public var `modelTrainingExpectedTotalIteration` : String? public var `numDmlAffectedRows` : String? public var `queryPlan` : [ExplainQueryStage]? public var `referencedRoutines` : [RoutineReference]? public var `referencedTables` : [TableReference]? public var `reservationUsage` : [Object]? public var `schema` : TableSchema? public var `statementType` : String? public var `timeline` : [QueryTimelineSample]? public var `totalBytesBilled` : String? public var `totalBytesProcessed` : String? public var `totalBytesProcessedAccuracy` : String? public var `totalPartitionsProcessed` : String? public var `totalSlotMs` : String? public var `undeclaredQueryParameters` : [QueryParameter]? } public struct JobStatistics3 : Codable { public init (`badRecords`: String?, `inputFileBytes`: String?, `inputFiles`: String?, `outputBytes`: String?, `outputRows`: String?) { self.`badRecords` = `badRecords` self.`inputFileBytes` = `inputFileBytes` self.`inputFiles` = `inputFiles` self.`outputBytes` = `outputBytes` self.`outputRows` = `outputRows` } public var `badRecords` : String? public var `inputFileBytes` : String? public var `inputFiles` : String? public var `outputBytes` : String? public var `outputRows` : String? } public struct JobStatistics4 : Codable { public init (`destinationUriFileCounts`: [String]?, `inputBytes`: String?) { self.`destinationUriFileCounts` = `destinationUriFileCounts` self.`inputBytes` = `inputBytes` } public var `destinationUriFileCounts` : [String]? public var `inputBytes` : String? } public struct JobStatus : Codable { public init (`errorResult`: ErrorProto?, `errors`: [ErrorProto]?, `state`: String?) { self.`errorResult` = `errorResult` self.`errors` = `errors` self.`state` = `state` } public var `errorResult` : ErrorProto? public var `errors` : [ErrorProto]? public var `state` : String? } public struct JsonObject : Codable { } public typealias `JsonValue` = JSONAny public struct ListModelsResponse : Codable { public init (`models`: [Model]?, `nextPageToken`: String?) { self.`models` = `models` self.`nextPageToken` = `nextPageToken` } public var `models` : [Model]? public var `nextPageToken` : String? } public struct ListRoutinesResponse : Codable { public init (`nextPageToken`: String?, `routines`: [Routine]?) { self.`nextPageToken` = `nextPageToken` self.`routines` = `routines` } public var `nextPageToken` : String? public var `routines` : [Routine]? } public struct LocationMetadata : Codable { public init (`legacyLocationId`: String?) { self.`legacyLocationId` = `legacyLocationId` } public var `legacyLocationId` : String? } public struct MaterializedViewDefinition : Codable { public init (`enableRefresh`: Bool?, `lastRefreshTime`: String?, `query`: String?, `refreshIntervalMs`: String?) { self.`enableRefresh` = `enableRefresh` self.`lastRefreshTime` = `lastRefreshTime` self.`query` = `query` self.`refreshIntervalMs` = `refreshIntervalMs` } public var `enableRefresh` : Bool? public var `lastRefreshTime` : String? public var `query` : String? public var `refreshIntervalMs` : String? } public struct Model : Codable { public init (`creationTime`: String?, `description`: String?, `encryptionConfiguration`: EncryptionConfiguration?, `etag`: String?, `expirationTime`: String?, `featureColumns`: [StandardSqlField]?, `friendlyName`: String?, `labelColumns`: [StandardSqlField]?, `labels`: Object?, `lastModifiedTime`: String?, `location`: String?, `modelReference`: ModelReference?, `modelType`: String?, `trainingRuns`: [TrainingRun]?) { self.`creationTime` = `creationTime` self.`description` = `description` self.`encryptionConfiguration` = `encryptionConfiguration` self.`etag` = `etag` self.`expirationTime` = `expirationTime` self.`featureColumns` = `featureColumns` self.`friendlyName` = `friendlyName` self.`labelColumns` = `labelColumns` self.`labels` = `labels` self.`lastModifiedTime` = `lastModifiedTime` self.`location` = `location` self.`modelReference` = `modelReference` self.`modelType` = `modelType` self.`trainingRuns` = `trainingRuns` } public var `creationTime` : String? public var `description` : String? public var `encryptionConfiguration` : EncryptionConfiguration? public var `etag` : String? public var `expirationTime` : String? public var `featureColumns` : [StandardSqlField]? public var `friendlyName` : String? public var `labelColumns` : [StandardSqlField]? public var `labels` : Object? public var `lastModifiedTime` : String? public var `location` : String? public var `modelReference` : ModelReference? public var `modelType` : String? public var `trainingRuns` : [TrainingRun]? } public struct ModelDefinition : Codable { public init (`modelOptions`: Object?, `trainingRuns`: [BqmlTrainingRun]?) { self.`modelOptions` = `modelOptions` self.`trainingRuns` = `trainingRuns` } public var `modelOptions` : Object? public var `trainingRuns` : [BqmlTrainingRun]? } public struct ModelReference : Codable { public init (`datasetId`: String?, `modelId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`modelId` = `modelId` self.`projectId` = `projectId` } public var `datasetId` : String? public var `modelId` : String? public var `projectId` : String? } public struct MultiClassClassificationMetrics : Codable { public init (`aggregateClassificationMetrics`: AggregateClassificationMetrics?, `confusionMatrixList`: [ConfusionMatrix]?) { self.`aggregateClassificationMetrics` = `aggregateClassificationMetrics` self.`confusionMatrixList` = `confusionMatrixList` } public var `aggregateClassificationMetrics` : AggregateClassificationMetrics? public var `confusionMatrixList` : [ConfusionMatrix]? } public struct ProjectList : Codable { public init (`etag`: String?, `kind`: String?, `nextPageToken`: String?, `projects`: [Object]?, `totalItems`: Int?) { self.`etag` = `etag` self.`kind` = `kind` self.`nextPageToken` = `nextPageToken` self.`projects` = `projects` self.`totalItems` = `totalItems` } public var `etag` : String? public var `kind` : String? public var `nextPageToken` : String? public var `projects` : [Object]? public var `totalItems` : Int? } public struct ProjectReference : Codable { public init (`projectId`: String?) { self.`projectId` = `projectId` } public var `projectId` : String? } public struct QueryParameter : Codable { public init (`name`: String?, `parameterType`: QueryParameterType?, `parameterValue`: QueryParameterValue?) { self.`name` = `name` self.`parameterType` = `parameterType` self.`parameterValue` = `parameterValue` } public var `name` : String? public var `parameterType` : QueryParameterType? public var `parameterValue` : QueryParameterValue? } public class QueryParameterType : Codable { public init (`arrayType`: QueryParameterType?, `structTypes`: [Object]?, `type`: String?) { self.`arrayType` = `arrayType` self.`structTypes` = `structTypes` self.`type` = `type` } public var `arrayType` : QueryParameterType? public var `structTypes` : [Object]? public var `type` : String? } public struct QueryParameterValue : Codable { public init (`arrayValues`: [QueryParameterValue]?, `structValues`: Object?, `value`: String?) { self.`arrayValues` = `arrayValues` self.`structValues` = `structValues` self.`value` = `value` } public var `arrayValues` : [QueryParameterValue]? public var `structValues` : Object? public var `value` : String? } public struct QueryRequest : Codable { public init (`defaultDataset`: DatasetReference?, `dryRun`: Bool?, `kind`: String?, `location`: String?, `maxResults`: Int?, `parameterMode`: String?, `preserveNulls`: Bool?, `query`: String?, `queryParameters`: [QueryParameter]?, `timeoutMs`: Int?, `useLegacySql`: Bool?, `useQueryCache`: Bool?) { self.`defaultDataset` = `defaultDataset` self.`dryRun` = `dryRun` self.`kind` = `kind` self.`location` = `location` self.`maxResults` = `maxResults` self.`parameterMode` = `parameterMode` self.`preserveNulls` = `preserveNulls` self.`query` = `query` self.`queryParameters` = `queryParameters` self.`timeoutMs` = `timeoutMs` self.`useLegacySql` = `useLegacySql` self.`useQueryCache` = `useQueryCache` } public var `defaultDataset` : DatasetReference? public var `dryRun` : Bool? public var `kind` : String? public var `location` : String? public var `maxResults` : Int? public var `parameterMode` : String? public var `preserveNulls` : Bool? public var `query` : String? public var `queryParameters` : [QueryParameter]? public var `timeoutMs` : Int? public var `useLegacySql` : Bool? public var `useQueryCache` : Bool? } public struct QueryResponse : Codable { public init (`cacheHit`: Bool?, `errors`: [ErrorProto]?, `jobComplete`: Bool?, `jobReference`: JobReference?, `kind`: String?, `numDmlAffectedRows`: String?, `pageToken`: String?, `rows`: [TableRow]?, `schema`: TableSchema?, `totalBytesProcessed`: String?, `totalRows`: String?) { self.`cacheHit` = `cacheHit` self.`errors` = `errors` self.`jobComplete` = `jobComplete` self.`jobReference` = `jobReference` self.`kind` = `kind` self.`numDmlAffectedRows` = `numDmlAffectedRows` self.`pageToken` = `pageToken` self.`rows` = `rows` self.`schema` = `schema` self.`totalBytesProcessed` = `totalBytesProcessed` self.`totalRows` = `totalRows` } public var `cacheHit` : Bool? public var `errors` : [ErrorProto]? public var `jobComplete` : Bool? public var `jobReference` : JobReference? public var `kind` : String? public var `numDmlAffectedRows` : String? public var `pageToken` : String? public var `rows` : [TableRow]? public var `schema` : TableSchema? public var `totalBytesProcessed` : String? public var `totalRows` : String? } public struct QueryTimelineSample : Codable { public init (`activeUnits`: String?, `completedUnits`: String?, `elapsedMs`: String?, `pendingUnits`: String?, `totalSlotMs`: String?) { self.`activeUnits` = `activeUnits` self.`completedUnits` = `completedUnits` self.`elapsedMs` = `elapsedMs` self.`pendingUnits` = `pendingUnits` self.`totalSlotMs` = `totalSlotMs` } public var `activeUnits` : String? public var `completedUnits` : String? public var `elapsedMs` : String? public var `pendingUnits` : String? public var `totalSlotMs` : String? } public struct RangePartitioning : Codable { public init (`field`: String?, `range`: Object?) { self.`field` = `field` self.`range` = `range` } public var `field` : String? public var `range` : Object? } public struct RegressionMetrics : Codable { public init (`meanAbsoluteError`: Double?, `meanSquaredError`: Double?, `meanSquaredLogError`: Double?, `medianAbsoluteError`: Double?, `rSquared`: Double?) { self.`meanAbsoluteError` = `meanAbsoluteError` self.`meanSquaredError` = `meanSquaredError` self.`meanSquaredLogError` = `meanSquaredLogError` self.`medianAbsoluteError` = `medianAbsoluteError` self.`rSquared` = `rSquared` } public var `meanAbsoluteError` : Double? public var `meanSquaredError` : Double? public var `meanSquaredLogError` : Double? public var `medianAbsoluteError` : Double? public var `rSquared` : Double? } public struct Routine : Codable { public init (`arguments`: [Argument]?, `creationTime`: String?, `definitionBody`: String?, `description`: String?, `etag`: String?, `importedLibraries`: [String]?, `language`: String?, `lastModifiedTime`: String?, `returnType`: StandardSqlDataType?, `routineReference`: RoutineReference?, `routineType`: String?) { self.`arguments` = `arguments` self.`creationTime` = `creationTime` self.`definitionBody` = `definitionBody` self.`description` = `description` self.`etag` = `etag` self.`importedLibraries` = `importedLibraries` self.`language` = `language` self.`lastModifiedTime` = `lastModifiedTime` self.`returnType` = `returnType` self.`routineReference` = `routineReference` self.`routineType` = `routineType` } public var `arguments` : [Argument]? public var `creationTime` : String? public var `definitionBody` : String? public var `description` : String? public var `etag` : String? public var `importedLibraries` : [String]? public var `language` : String? public var `lastModifiedTime` : String? public var `returnType` : StandardSqlDataType? public var `routineReference` : RoutineReference? public var `routineType` : String? } public struct RoutineReference : Codable { public init (`datasetId`: String?, `projectId`: String?, `routineId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`routineId` = `routineId` } public var `datasetId` : String? public var `projectId` : String? public var `routineId` : String? } public struct Row : Codable { public init (`actualLabel`: String?, `entries`: [Entry]?) { self.`actualLabel` = `actualLabel` self.`entries` = `entries` } public var `actualLabel` : String? public var `entries` : [Entry]? } public struct ScriptStackFrame : Codable { public init (`endColumn`: Int?, `endLine`: Int?, `procedureId`: String?, `startColumn`: Int?, `startLine`: Int?, `text`: String?) { self.`endColumn` = `endColumn` self.`endLine` = `endLine` self.`procedureId` = `procedureId` self.`startColumn` = `startColumn` self.`startLine` = `startLine` self.`text` = `text` } public var `endColumn` : Int? public var `endLine` : Int? public var `procedureId` : String? public var `startColumn` : Int? public var `startLine` : Int? public var `text` : String? } public struct ScriptStatistics : Codable { public init (`evaluationKind`: String?, `stackFrames`: [ScriptStackFrame]?) { self.`evaluationKind` = `evaluationKind` self.`stackFrames` = `stackFrames` } public var `evaluationKind` : String? public var `stackFrames` : [ScriptStackFrame]? } public class StandardSqlDataType : Codable { public init (`arrayElementType`: StandardSqlDataType?, `structType`: StandardSqlStructType?, `typeKind`: String?) { self.`arrayElementType` = `arrayElementType` self.`structType` = `structType` self.`typeKind` = `typeKind` } public var `arrayElementType` : StandardSqlDataType? public var `structType` : StandardSqlStructType? public var `typeKind` : String? } public struct StandardSqlField : Codable { public init (`name`: String?, `type`: StandardSqlDataType?) { self.`name` = `name` self.`type` = `type` } public var `name` : String? public var `type` : StandardSqlDataType? } public struct StandardSqlStructType : Codable { public init (`fields`: [StandardSqlField]?) { self.`fields` = `fields` } public var `fields` : [StandardSqlField]? } public struct Streamingbuffer : Codable { public init (`estimatedBytes`: String?, `estimatedRows`: String?, `oldestEntryTime`: String?) { self.`estimatedBytes` = `estimatedBytes` self.`estimatedRows` = `estimatedRows` self.`oldestEntryTime` = `oldestEntryTime` } public var `estimatedBytes` : String? public var `estimatedRows` : String? public var `oldestEntryTime` : String? } public struct Table : Codable { public init (`clustering`: Clustering?, `creationTime`: String?, `description`: String?, `encryptionConfiguration`: EncryptionConfiguration?, `etag`: String?, `expirationTime`: String?, `externalDataConfiguration`: ExternalDataConfiguration?, `friendlyName`: String?, `id`: String?, `kind`: String?, `labels`: Object?, `lastModifiedTime`: String?, `location`: String?, `materializedView`: MaterializedViewDefinition?, `model`: ModelDefinition?, `numBytes`: String?, `numLongTermBytes`: String?, `numPhysicalBytes`: String?, `numRows`: String?, `rangePartitioning`: RangePartitioning?, `requirePartitionFilter`: Bool?, `schema`: TableSchema?, `selfLink`: String?, `streamingBuffer`: Streamingbuffer?, `tableReference`: TableReference?, `timePartitioning`: TimePartitioning?, `type`: String?, `view`: ViewDefinition?) { self.`clustering` = `clustering` self.`creationTime` = `creationTime` self.`description` = `description` self.`encryptionConfiguration` = `encryptionConfiguration` self.`etag` = `etag` self.`expirationTime` = `expirationTime` self.`externalDataConfiguration` = `externalDataConfiguration` self.`friendlyName` = `friendlyName` self.`id` = `id` self.`kind` = `kind` self.`labels` = `labels` self.`lastModifiedTime` = `lastModifiedTime` self.`location` = `location` self.`materializedView` = `materializedView` self.`model` = `model` self.`numBytes` = `numBytes` self.`numLongTermBytes` = `numLongTermBytes` self.`numPhysicalBytes` = `numPhysicalBytes` self.`numRows` = `numRows` self.`rangePartitioning` = `rangePartitioning` self.`requirePartitionFilter` = `requirePartitionFilter` self.`schema` = `schema` self.`selfLink` = `selfLink` self.`streamingBuffer` = `streamingBuffer` self.`tableReference` = `tableReference` self.`timePartitioning` = `timePartitioning` self.`type` = `type` self.`view` = `view` } public var `clustering` : Clustering? public var `creationTime` : String? public var `description` : String? public var `encryptionConfiguration` : EncryptionConfiguration? public var `etag` : String? public var `expirationTime` : String? public var `externalDataConfiguration` : ExternalDataConfiguration? public var `friendlyName` : String? public var `id` : String? public var `kind` : String? public var `labels` : Object? public var `lastModifiedTime` : String? public var `location` : String? public var `materializedView` : MaterializedViewDefinition? public var `model` : ModelDefinition? public var `numBytes` : String? public var `numLongTermBytes` : String? public var `numPhysicalBytes` : String? public var `numRows` : String? public var `rangePartitioning` : RangePartitioning? public var `requirePartitionFilter` : Bool? public var `schema` : TableSchema? public var `selfLink` : String? public var `streamingBuffer` : Streamingbuffer? public var `tableReference` : TableReference? public var `timePartitioning` : TimePartitioning? public var `type` : String? public var `view` : ViewDefinition? } public struct TableCell : Codable { public init (`v`: JSONAny?) { self.`v` = `v` } public var `v` : JSONAny? } public struct TableDataInsertAllRequest : Codable { public init (`ignoreUnknownValues`: Bool?, `kind`: String?, `rows`: [Object]?, `skipInvalidRows`: Bool?, `templateSuffix`: String?) { self.`ignoreUnknownValues` = `ignoreUnknownValues` self.`kind` = `kind` self.`rows` = `rows` self.`skipInvalidRows` = `skipInvalidRows` self.`templateSuffix` = `templateSuffix` } public var `ignoreUnknownValues` : Bool? public var `kind` : String? public var `rows` : [Object]? public var `skipInvalidRows` : Bool? public var `templateSuffix` : String? } public struct TableDataInsertAllResponse : Codable { public init (`insertErrors`: [Object]?, `kind`: String?) { self.`insertErrors` = `insertErrors` self.`kind` = `kind` } public var `insertErrors` : [Object]? public var `kind` : String? } public struct TableDataList : Codable { public init (`etag`: String?, `kind`: String?, `pageToken`: String?, `rows`: [TableRow]?, `totalRows`: String?) { self.`etag` = `etag` self.`kind` = `kind` self.`pageToken` = `pageToken` self.`rows` = `rows` self.`totalRows` = `totalRows` } public var `etag` : String? public var `kind` : String? public var `pageToken` : String? public var `rows` : [TableRow]? public var `totalRows` : String? } public struct TableFieldSchema : Codable { public init (`categories`: Object?, `description`: String?, `fields`: [TableFieldSchema]?, `mode`: String?, `name`: String?, `policyTags`: Object?, `type`: String?) { self.`categories` = `categories` self.`description` = `description` self.`fields` = `fields` self.`mode` = `mode` self.`name` = `name` self.`policyTags` = `policyTags` self.`type` = `type` } public var `categories` : Object? public var `description` : String? public var `fields` : [TableFieldSchema]? public var `mode` : String? public var `name` : String? public var `policyTags` : Object? public var `type` : String? } public struct TableList : Codable { public init (`etag`: String?, `kind`: String?, `nextPageToken`: String?, `tables`: [Object]?, `totalItems`: Int?) { self.`etag` = `etag` self.`kind` = `kind` self.`nextPageToken` = `nextPageToken` self.`tables` = `tables` self.`totalItems` = `totalItems` } public var `etag` : String? public var `kind` : String? public var `nextPageToken` : String? public var `tables` : [Object]? public var `totalItems` : Int? } public struct TableReference : Codable { public init (`datasetId`: String?, `projectId`: String?, `tableId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`tableId` = `tableId` } public var `datasetId` : String? public var `projectId` : String? public var `tableId` : String? } public struct TableRow : Codable { public init (`f`: [TableCell]?) { self.`f` = `f` } public var `f` : [TableCell]? } public struct TableSchema : Codable { public init (`fields`: [TableFieldSchema]?) { self.`fields` = `fields` } public var `fields` : [TableFieldSchema]? } public struct TimePartitioning : Codable { public init (`expirationMs`: String?, `field`: String?, `requirePartitionFilter`: Bool?, `type`: String?) { self.`expirationMs` = `expirationMs` self.`field` = `field` self.`requirePartitionFilter` = `requirePartitionFilter` self.`type` = `type` } public var `expirationMs` : String? public var `field` : String? public var `requirePartitionFilter` : Bool? public var `type` : String? } public struct TrainingOptions : Codable { public init (`dataSplitColumn`: String?, `dataSplitEvalFraction`: Double?, `dataSplitMethod`: String?, `distanceType`: String?, `earlyStop`: Bool?, `initialLearnRate`: Double?, `inputLabelColumns`: [String]?, `kmeansInitializationColumn`: String?, `kmeansInitializationMethod`: String?, `l1Regularization`: Double?, `l2Regularization`: Double?, `labelClassWeights`: Object?, `learnRate`: Double?, `learnRateStrategy`: String?, `lossType`: String?, `maxIterations`: String?, `minRelativeProgress`: Double?, `modelUri`: String?, `numClusters`: String?, `optimizationStrategy`: String?, `warmStart`: Bool?) { self.`dataSplitColumn` = `dataSplitColumn` self.`dataSplitEvalFraction` = `dataSplitEvalFraction` self.`dataSplitMethod` = `dataSplitMethod` self.`distanceType` = `distanceType` self.`earlyStop` = `earlyStop` self.`initialLearnRate` = `initialLearnRate` self.`inputLabelColumns` = `inputLabelColumns` self.`kmeansInitializationColumn` = `kmeansInitializationColumn` self.`kmeansInitializationMethod` = `kmeansInitializationMethod` self.`l1Regularization` = `l1Regularization` self.`l2Regularization` = `l2Regularization` self.`labelClassWeights` = `labelClassWeights` self.`learnRate` = `learnRate` self.`learnRateStrategy` = `learnRateStrategy` self.`lossType` = `lossType` self.`maxIterations` = `maxIterations` self.`minRelativeProgress` = `minRelativeProgress` self.`modelUri` = `modelUri` self.`numClusters` = `numClusters` self.`optimizationStrategy` = `optimizationStrategy` self.`warmStart` = `warmStart` } public var `dataSplitColumn` : String? public var `dataSplitEvalFraction` : Double? public var `dataSplitMethod` : String? public var `distanceType` : String? public var `earlyStop` : Bool? public var `initialLearnRate` : Double? public var `inputLabelColumns` : [String]? public var `kmeansInitializationColumn` : String? public var `kmeansInitializationMethod` : String? public var `l1Regularization` : Double? public var `l2Regularization` : Double? public var `labelClassWeights` : Object? public var `learnRate` : Double? public var `learnRateStrategy` : String? public var `lossType` : String? public var `maxIterations` : String? public var `minRelativeProgress` : Double? public var `modelUri` : String? public var `numClusters` : String? public var `optimizationStrategy` : String? public var `warmStart` : Bool? } public struct TrainingRun : Codable { public init (`dataSplitResult`: DataSplitResult?, `evaluationMetrics`: EvaluationMetrics?, `results`: [IterationResult]?, `startTime`: String?, `trainingOptions`: TrainingOptions?) { self.`dataSplitResult` = `dataSplitResult` self.`evaluationMetrics` = `evaluationMetrics` self.`results` = `results` self.`startTime` = `startTime` self.`trainingOptions` = `trainingOptions` } public var `dataSplitResult` : DataSplitResult? public var `evaluationMetrics` : EvaluationMetrics? public var `results` : [IterationResult]? public var `startTime` : String? public var `trainingOptions` : TrainingOptions? } public struct UserDefinedFunctionResource : Codable { public init (`inlineCode`: String?, `resourceUri`: String?) { self.`inlineCode` = `inlineCode` self.`resourceUri` = `resourceUri` } public var `inlineCode` : String? public var `resourceUri` : String? } public struct ViewDefinition : Codable { public init (`query`: String?, `useLegacySql`: Bool?, `userDefinedFunctionResources`: [UserDefinedFunctionResource]?) { self.`query` = `query` self.`useLegacySql` = `useLegacySql` self.`userDefinedFunctionResources` = `userDefinedFunctionResources` } public var `query` : String? public var `useLegacySql` : Bool? public var `userDefinedFunctionResources` : [UserDefinedFunctionResource]? } public struct DatasetsDeleteParameters : Parameterizable { public init (`datasetId`: String?, `deleteContents`: Bool?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`deleteContents` = `deleteContents` self.`projectId` = `projectId` } public var datasetId : String? public var deleteContents : Bool? public var projectId : String? public func queryParameters() -> [String] { return ["deleteContents"] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func datasets_delete ( parameters: DatasetsDeleteParameters, completion: @escaping (Error?) -> ()) throws { try perform( method: "DELETE", path: "projects/{projectId}/datasets/{datasetId}", parameters: parameters, completion: completion) } public struct DatasetsGetParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` } public var datasetId : String? public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func datasets_get ( parameters: DatasetsGetParameters, completion: @escaping (Dataset?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/datasets/{datasetId}", parameters: parameters, completion: completion) } public struct DatasetsInsertParameters : Parameterizable { public init (`projectId`: String?) { self.`projectId` = `projectId` } public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["projectId"] } } public func datasets_insert ( request: Dataset, parameters: DatasetsInsertParameters, completion: @escaping (Dataset?, Error?) -> ()) throws { try perform( method: "POST", path: "projects/{projectId}/datasets", request: request, parameters: parameters, completion: completion) } public struct DatasetsListParameters : Parameterizable { public init (`all`: Bool?, `filter`: String?, `maxResults`: Int?, `pageToken`: String?, `projectId`: String?) { self.`all` = `all` self.`filter` = `filter` self.`maxResults` = `maxResults` self.`pageToken` = `pageToken` self.`projectId` = `projectId` } public var all : Bool? public var filter : String? public var maxResults : Int? public var pageToken : String? public var projectId : String? public func queryParameters() -> [String] { return ["all","filter","maxResults","pageToken"] } public func pathParameters() -> [String] { return ["projectId"] } } public func datasets_list ( parameters: DatasetsListParameters, completion: @escaping (DatasetList?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/datasets", parameters: parameters, completion: completion) } public struct DatasetsPatchParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` } public var datasetId : String? public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func datasets_patch ( request: Dataset, parameters: DatasetsPatchParameters, completion: @escaping (Dataset?, Error?) -> ()) throws { try perform( method: "PATCH", path: "projects/{projectId}/datasets/{datasetId}", request: request, parameters: parameters, completion: completion) } public struct DatasetsUpdateParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` } public var datasetId : String? public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func datasets_update ( request: Dataset, parameters: DatasetsUpdateParameters, completion: @escaping (Dataset?, Error?) -> ()) throws { try perform( method: "PUT", path: "projects/{projectId}/datasets/{datasetId}", request: request, parameters: parameters, completion: completion) } public struct JobsCancelParameters : Parameterizable { public init (`jobId`: String?, `location`: String?, `projectId`: String?) { self.`jobId` = `jobId` self.`location` = `location` self.`projectId` = `projectId` } public var jobId : String? public var location : String? public var projectId : String? public func queryParameters() -> [String] { return ["location"] } public func pathParameters() -> [String] { return ["jobId","projectId"] } } public func jobs_cancel ( parameters: JobsCancelParameters, completion: @escaping (JobCancelResponse?, Error?) -> ()) throws { try perform( method: "POST", path: "projects/{projectId}/jobs/{jobId}/cancel", parameters: parameters, completion: completion) } public struct JobsGetParameters : Parameterizable { public init (`jobId`: String?, `location`: String?, `projectId`: String?) { self.`jobId` = `jobId` self.`location` = `location` self.`projectId` = `projectId` } public var jobId : String? public var location : String? public var projectId : String? public func queryParameters() -> [String] { return ["location"] } public func pathParameters() -> [String] { return ["jobId","projectId"] } } public func jobs_get ( parameters: JobsGetParameters, completion: @escaping (Job?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/jobs/{jobId}", parameters: parameters, completion: completion) } public struct JobsGetQueryResultsParameters : Parameterizable { public init (`jobId`: String?, `location`: String?, `maxResults`: Int?, `pageToken`: String?, `projectId`: String?, `startIndex`: String?, `timeoutMs`: Int?) { self.`jobId` = `jobId` self.`location` = `location` self.`maxResults` = `maxResults` self.`pageToken` = `pageToken` self.`projectId` = `projectId` self.`startIndex` = `startIndex` self.`timeoutMs` = `timeoutMs` } public var jobId : String? public var location : String? public var maxResults : Int? public var pageToken : String? public var projectId : String? public var startIndex : String? public var timeoutMs : Int? public func queryParameters() -> [String] { return ["location","maxResults","pageToken","startIndex","timeoutMs"] } public func pathParameters() -> [String] { return ["jobId","projectId"] } } public func jobs_getQueryResults ( parameters: JobsGetQueryResultsParameters, completion: @escaping (GetQueryResultsResponse?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/queries/{jobId}", parameters: parameters, completion: completion) } public struct JobsInsertParameters : Parameterizable { public init (`projectId`: String?) { self.`projectId` = `projectId` } public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["projectId"] } } public func jobs_insert ( request: Job, parameters: JobsInsertParameters, completion: @escaping (Job?, Error?) -> ()) throws { try perform( method: "POST", path: "projects/{projectId}/jobs", request: request, parameters: parameters, completion: completion) } public struct JobsListParameters : Parameterizable { public init (`allUsers`: Bool?, `maxCreationTime`: String?, `maxResults`: Int?, `minCreationTime`: String?, `pageToken`: String?, `parentJobId`: String?, `projectId`: String?, `projection`: String?, `stateFilter`: String?) { self.`allUsers` = `allUsers` self.`maxCreationTime` = `maxCreationTime` self.`maxResults` = `maxResults` self.`minCreationTime` = `minCreationTime` self.`pageToken` = `pageToken` self.`parentJobId` = `parentJobId` self.`projectId` = `projectId` self.`projection` = `projection` self.`stateFilter` = `stateFilter` } public var allUsers : Bool? public var maxCreationTime : String? public var maxResults : Int? public var minCreationTime : String? public var pageToken : String? public var parentJobId : String? public var projectId : String? public var projection : String? public var stateFilter : String? public func queryParameters() -> [String] { return ["allUsers","maxCreationTime","maxResults","minCreationTime","pageToken","parentJobId","projection","stateFilter"] } public func pathParameters() -> [String] { return ["projectId"] } } public func jobs_list ( parameters: JobsListParameters, completion: @escaping (JobList?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/jobs", parameters: parameters, completion: completion) } public struct JobsQueryParameters : Parameterizable { public init (`projectId`: String?) { self.`projectId` = `projectId` } public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["projectId"] } } public func jobs_query ( request: QueryRequest, parameters: JobsQueryParameters, completion: @escaping (QueryResponse?, Error?) -> ()) throws { try perform( method: "POST", path: "projects/{projectId}/queries", request: request, parameters: parameters, completion: completion) } public struct ModelsDeleteParameters : Parameterizable { public init (`datasetId`: String?, `modelId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`modelId` = `modelId` self.`projectId` = `projectId` } public var datasetId : String? public var modelId : String? public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","modelId","projectId"] } } public func models_delete ( parameters: ModelsDeleteParameters, completion: @escaping (Error?) -> ()) throws { try perform( method: "DELETE", path: "projects/{+projectId}/datasets/{+datasetId}/models/{+modelId}", parameters: parameters, completion: completion) } public struct ModelsGetParameters : Parameterizable { public init (`datasetId`: String?, `modelId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`modelId` = `modelId` self.`projectId` = `projectId` } public var datasetId : String? public var modelId : String? public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","modelId","projectId"] } } public func models_get ( parameters: ModelsGetParameters, completion: @escaping (Model?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{+projectId}/datasets/{+datasetId}/models/{+modelId}", parameters: parameters, completion: completion) } public struct ModelsListParameters : Parameterizable { public init (`datasetId`: String?, `maxResults`: Int?, `pageToken`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`maxResults` = `maxResults` self.`pageToken` = `pageToken` self.`projectId` = `projectId` } public var datasetId : String? public var maxResults : Int? public var pageToken : String? public var projectId : String? public func queryParameters() -> [String] { return ["maxResults","pageToken"] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func models_list ( parameters: ModelsListParameters, completion: @escaping (ListModelsResponse?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{+projectId}/datasets/{+datasetId}/models", parameters: parameters, completion: completion) } public struct ModelsPatchParameters : Parameterizable { public init (`datasetId`: String?, `modelId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`modelId` = `modelId` self.`projectId` = `projectId` } public var datasetId : String? public var modelId : String? public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","modelId","projectId"] } } public func models_patch ( request: Model, parameters: ModelsPatchParameters, completion: @escaping (Model?, Error?) -> ()) throws { try perform( method: "PATCH", path: "projects/{+projectId}/datasets/{+datasetId}/models/{+modelId}", request: request, parameters: parameters, completion: completion) } public struct ProjectsGetServiceAccountParameters : Parameterizable { public init (`projectId`: String?) { self.`projectId` = `projectId` } public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["projectId"] } } public func projects_getServiceAccount ( parameters: ProjectsGetServiceAccountParameters, completion: @escaping (GetServiceAccountResponse?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/serviceAccount", parameters: parameters, completion: completion) } public struct ProjectsListParameters : Parameterizable { public init (`maxResults`: Int?, `pageToken`: String?) { self.`maxResults` = `maxResults` self.`pageToken` = `pageToken` } public var maxResults : Int? public var pageToken : String? public func queryParameters() -> [String] { return ["maxResults","pageToken"] } public func pathParameters() -> [String] { return [] } } public func projects_list ( parameters: ProjectsListParameters, completion: @escaping (ProjectList?, Error?) -> ()) throws { try perform( method: "GET", path: "projects", parameters: parameters, completion: completion) } public struct RoutinesDeleteParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?, `routineId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`routineId` = `routineId` } public var datasetId : String? public var projectId : String? public var routineId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId","routineId"] } } public func routines_delete ( parameters: RoutinesDeleteParameters, completion: @escaping (Error?) -> ()) throws { try perform( method: "DELETE", path: "projects/{+projectId}/datasets/{+datasetId}/routines/{+routineId}", parameters: parameters, completion: completion) } public struct RoutinesGetParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?, `readMask`: String?, `routineId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`readMask` = `readMask` self.`routineId` = `routineId` } public var datasetId : String? public var projectId : String? public var readMask : String? public var routineId : String? public func queryParameters() -> [String] { return ["readMask"] } public func pathParameters() -> [String] { return ["datasetId","projectId","routineId"] } } public func routines_get ( parameters: RoutinesGetParameters, completion: @escaping (Routine?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{+projectId}/datasets/{+datasetId}/routines/{+routineId}", parameters: parameters, completion: completion) } public struct RoutinesInsertParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` } public var datasetId : String? public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func routines_insert ( request: Routine, parameters: RoutinesInsertParameters, completion: @escaping (Routine?, Error?) -> ()) throws { try perform( method: "POST", path: "projects/{+projectId}/datasets/{+datasetId}/routines", request: request, parameters: parameters, completion: completion) } public struct RoutinesListParameters : Parameterizable { public init (`datasetId`: String?, `filter`: String?, `maxResults`: Int?, `pageToken`: String?, `projectId`: String?, `readMask`: String?) { self.`datasetId` = `datasetId` self.`filter` = `filter` self.`maxResults` = `maxResults` self.`pageToken` = `pageToken` self.`projectId` = `projectId` self.`readMask` = `readMask` } public var datasetId : String? public var filter : String? public var maxResults : Int? public var pageToken : String? public var projectId : String? public var readMask : String? public func queryParameters() -> [String] { return ["filter","maxResults","pageToken","readMask"] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func routines_list ( parameters: RoutinesListParameters, completion: @escaping (ListRoutinesResponse?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{+projectId}/datasets/{+datasetId}/routines", parameters: parameters, completion: completion) } public struct RoutinesUpdateParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?, `routineId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`routineId` = `routineId` } public var datasetId : String? public var projectId : String? public var routineId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId","routineId"] } } public func routines_update ( request: Routine, parameters: RoutinesUpdateParameters, completion: @escaping (Routine?, Error?) -> ()) throws { try perform( method: "PUT", path: "projects/{+projectId}/datasets/{+datasetId}/routines/{+routineId}", request: request, parameters: parameters, completion: completion) } public struct TabledataInsertAllParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?, `tableId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`tableId` = `tableId` } public var datasetId : String? public var projectId : String? public var tableId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId","tableId"] } } public func tabledata_insertAll ( request: TableDataInsertAllRequest, parameters: TabledataInsertAllParameters, completion: @escaping (TableDataInsertAllResponse?, Error?) -> ()) throws { try perform( method: "POST", path: "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/insertAll", request: request, parameters: parameters, completion: completion) } public struct TabledataListParameters : Parameterizable { public init (`datasetId`: String?, `maxResults`: Int?, `pageToken`: String?, `projectId`: String?, `selectedFields`: String?, `startIndex`: String?, `tableId`: String?) { self.`datasetId` = `datasetId` self.`maxResults` = `maxResults` self.`pageToken` = `pageToken` self.`projectId` = `projectId` self.`selectedFields` = `selectedFields` self.`startIndex` = `startIndex` self.`tableId` = `tableId` } public var datasetId : String? public var maxResults : Int? public var pageToken : String? public var projectId : String? public var selectedFields : String? public var startIndex : String? public var tableId : String? public func queryParameters() -> [String] { return ["maxResults","pageToken","selectedFields","startIndex"] } public func pathParameters() -> [String] { return ["datasetId","projectId","tableId"] } } public func tabledata_list ( parameters: TabledataListParameters, completion: @escaping (TableDataList?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/data", parameters: parameters, completion: completion) } public struct TablesDeleteParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?, `tableId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`tableId` = `tableId` } public var datasetId : String? public var projectId : String? public var tableId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId","tableId"] } } public func tables_delete ( parameters: TablesDeleteParameters, completion: @escaping (Error?) -> ()) throws { try perform( method: "DELETE", path: "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", parameters: parameters, completion: completion) } public struct TablesGetParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?, `selectedFields`: String?, `tableId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`selectedFields` = `selectedFields` self.`tableId` = `tableId` } public var datasetId : String? public var projectId : String? public var selectedFields : String? public var tableId : String? public func queryParameters() -> [String] { return ["selectedFields"] } public func pathParameters() -> [String] { return ["datasetId","projectId","tableId"] } } public func tables_get ( parameters: TablesGetParameters, completion: @escaping (Table?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", parameters: parameters, completion: completion) } public struct TablesInsertParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` } public var datasetId : String? public var projectId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func tables_insert ( request: Table, parameters: TablesInsertParameters, completion: @escaping (Table?, Error?) -> ()) throws { try perform( method: "POST", path: "projects/{projectId}/datasets/{datasetId}/tables", request: request, parameters: parameters, completion: completion) } public struct TablesListParameters : Parameterizable { public init (`datasetId`: String?, `maxResults`: Int?, `pageToken`: String?, `projectId`: String?) { self.`datasetId` = `datasetId` self.`maxResults` = `maxResults` self.`pageToken` = `pageToken` self.`projectId` = `projectId` } public var datasetId : String? public var maxResults : Int? public var pageToken : String? public var projectId : String? public func queryParameters() -> [String] { return ["maxResults","pageToken"] } public func pathParameters() -> [String] { return ["datasetId","projectId"] } } public func tables_list ( parameters: TablesListParameters, completion: @escaping (TableList?, Error?) -> ()) throws { try perform( method: "GET", path: "projects/{projectId}/datasets/{datasetId}/tables", parameters: parameters, completion: completion) } public struct TablesPatchParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?, `tableId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`tableId` = `tableId` } public var datasetId : String? public var projectId : String? public var tableId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId","tableId"] } } public func tables_patch ( request: Table, parameters: TablesPatchParameters, completion: @escaping (Table?, Error?) -> ()) throws { try perform( method: "PATCH", path: "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", request: request, parameters: parameters, completion: completion) } public struct TablesUpdateParameters : Parameterizable { public init (`datasetId`: String?, `projectId`: String?, `tableId`: String?) { self.`datasetId` = `datasetId` self.`projectId` = `projectId` self.`tableId` = `tableId` } public var datasetId : String? public var projectId : String? public var tableId : String? public func queryParameters() -> [String] { return [] } public func pathParameters() -> [String] { return ["datasetId","projectId","tableId"] } } public func tables_update ( request: Table, parameters: TablesUpdateParameters, completion: @escaping (Table?, Error?) -> ()) throws { try perform( method: "PUT", path: "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", request: request, parameters: parameters, completion: completion) } }
38.936944
899
0.660905
215ee8f22519ff132a44102dbf1b5cd7f8105084
13,059
/* file: listed_string_data.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY listed_string_data SUBTYPE OF ( explicit_table_function, generic_literal ); values : LIST [1 : ?] OF STRING; DERIVE SELF\explicit_table_function.shape : LIST [1 : ?] OF positive_integer := [SIZEOF( values )]; END_ENTITY; -- listed_string_data (line:19210 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) generic_expression (no local attributes) SUPER- ENTITY(2) maths_function ATTR: domain, TYPE: tuple_space -- DERIVED := derive_function_domain( SELF ) ATTR: range, TYPE: tuple_space -- DERIVED := derive_function_range( SELF ) SUPER- ENTITY(3) explicit_table_function ATTR: index_base, TYPE: zero_or_one -- EXPLICIT ATTR: shape, TYPE: LIST [1 : ?] OF positive_integer -- EXPLICIT (DYNAMIC) -- possibly overriden by ENTITY: listed_integer_data, TYPE: LIST [1 : ?] OF positive_integer (as DERIVED) ENTITY: listed_data, TYPE: LIST [1 : ?] OF positive_integer (as DERIVED) *** ENTITY: listed_string_data, TYPE: LIST [1 : ?] OF positive_integer (as DERIVED) ENTITY: listed_logical_data, TYPE: LIST [1 : ?] OF positive_integer (as DERIVED) ENTITY: listed_complex_number_data, TYPE: LIST [1 : ?] OF positive_integer (as DERIVED) ENTITY: listed_real_data, TYPE: LIST [1 : ?] OF positive_integer (as DERIVED) SUPER- ENTITY(4) simple_generic_expression (no local attributes) SUPER- ENTITY(5) generic_literal (no local attributes) ENTITY(SELF) listed_string_data ATTR: values, TYPE: LIST [1 : ?] OF STRING -- EXPLICIT REDCR: shape, TYPE: LIST [1 : ?] OF positive_integer -- DERIVED (DYNAMIC) := [SIZEOF( values )] -- OVERRIDING ENTITY: explicit_table_function */ //MARK: - Partial Entity public final class _listed_string_data : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eLISTED_STRING_DATA.self } //ATTRIBUTES /// EXPLICIT ATTRIBUTE public internal(set) var _values: SDAI.LIST<SDAI.STRING>/*[1:nil]*/ // PLAIN EXPLICIT ATTRIBUTE /// DERIVE ATTRIBUTE REDEFINITION(origin: eEXPLICIT_TABLE_FUNCTION) /// - attribute value provider protocol conformance wrapper internal func _shape__getter(complex: SDAI.ComplexEntity) -> SDAI.LIST<tPOSITIVE_INTEGER>/*[1:nil]*/ { let SELF = complex.entityReference( eLISTED_STRING_DATA.self )! return SDAI.UNWRAP( SDAI.LIST<tPOSITIVE_INTEGER>(SELF.SHAPE) ) } /// DERIVE ATTRIBUTE REDEFINITION(origin: eEXPLICIT_TABLE_FUNCTION) /// - gut of derived attribute logic internal func _shape__getter(SELF: eLISTED_STRING_DATA) -> SDAI.LIST<tPOSITIVE_INTEGER>/*[1:nil]*/ { let _TEMP1 = SDAI.SIZEOF(SELF.VALUES) let _TEMP2 = SDAI.LIST<tPOSITIVE_INTEGER>(bound1: SDAI.UNWRAP(SDAI.INTEGER(1)), bound2: (nil as SDAI.INTEGER?), ([SDAI.AIE(tPOSITIVE_INTEGER(/*SDAI.INTEGER*/_TEMP1))] as [SDAI.AggregationInitializerElement< tPOSITIVE_INTEGER>])) let value = _TEMP2 return SDAI.UNWRAP( value ) } public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) self._values.value.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } if let comp = self._values.value.isValueEqualOptionally(to: rhs._values.value, visited: &comppairs) { if !comp { return false } } else { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } if let comp = self._values.value.isValueEqualOptionally(to: rhs._values.value, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init(VALUES: SDAI.LIST<SDAI.STRING>/*[1:nil]*/ ) { self._values = VALUES super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 1 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } guard case .success(let p0) = exchangeStructure.recoverRequiredParameter(as: SDAI.LIST<SDAI.STRING>.self, from: parameters[0]) else { exchangeStructure.add(errorContext: "while recovering parameter #0 for entity(\(Self.entityName)) constructor"); return nil } self.init( VALUES: p0 ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY listed_string_data SUBTYPE OF ( explicit_table_function, generic_literal ); values : LIST [1 : ?] OF STRING; DERIVE SELF\explicit_table_function.shape : LIST [1 : ?] OF positive_integer := [SIZEOF( values )]; END_ENTITY; -- listed_string_data (line:19210 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eLISTED_STRING_DATA : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _listed_string_data.self } public let partialEntity: _listed_string_data //MARK: SUPERTYPES public let super_eGENERIC_EXPRESSION: eGENERIC_EXPRESSION // [1] public let super_eMATHS_FUNCTION: eMATHS_FUNCTION // [2] public let super_eEXPLICIT_TABLE_FUNCTION: eEXPLICIT_TABLE_FUNCTION // [3] public let super_eSIMPLE_GENERIC_EXPRESSION: eSIMPLE_GENERIC_EXPRESSION // [4] public let super_eGENERIC_LITERAL: eGENERIC_LITERAL // [5] public var super_eLISTED_STRING_DATA: eLISTED_STRING_DATA { return self } // [6] //MARK: SUBTYPES //MARK: ATTRIBUTES /// __EXPLICIT REDEF(DERIVE)__ attribute /// - origin: SELF( ``eLISTED_STRING_DATA`` ) public var SHAPE: SDAI.LIST<tPOSITIVE_INTEGER>/*[1:nil]*/ { get { if let cached = cachedValue(derivedAttributeName:"SHAPE") { return cached.value as! SDAI.LIST<tPOSITIVE_INTEGER>/*[1:nil]*/ } let origin = self let value = SDAI.UNWRAP( origin.partialEntity._shape__getter(SELF: origin) ) updateCache(derivedAttributeName:"SHAPE", value:value) return value } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``eEXPLICIT_TABLE_FUNCTION`` ) public var INDEX_BASE: tZERO_OR_ONE { get { return SDAI.UNWRAP( super_eEXPLICIT_TABLE_FUNCTION.partialEntity._index_base ) } set(newValue) { let partial = super_eEXPLICIT_TABLE_FUNCTION.partialEntity partial._index_base = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SELF( ``eLISTED_STRING_DATA`` ) public var VALUES: SDAI.LIST<SDAI.STRING>/*[1:nil]*/ { get { return SDAI.UNWRAP( self.partialEntity._values ) } set(newValue) { let partial = self.partialEntity partial._values = SDAI.UNWRAP(newValue) } } /// __DERIVE__ attribute /// - origin: SUPER( ``eMATHS_FUNCTION`` ) public var DOMAIN: sTUPLE_SPACE? { get { if let cached = cachedValue(derivedAttributeName:"DOMAIN") { return cached.value as! sTUPLE_SPACE? } let origin = super_eMATHS_FUNCTION let value = sTUPLE_SPACE(origin.partialEntity._domain__getter(SELF: origin)) updateCache(derivedAttributeName:"DOMAIN", value:value) return value } } /// __DERIVE__ attribute /// - origin: SUPER( ``eMATHS_FUNCTION`` ) public var RANGE: sTUPLE_SPACE? { get { if let cached = cachedValue(derivedAttributeName:"RANGE") { return cached.value as! sTUPLE_SPACE? } let origin = super_eMATHS_FUNCTION let value = sTUPLE_SPACE(origin.partialEntity._range__getter(SELF: origin)) updateCache(derivedAttributeName:"RANGE", value:value) return value } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_listed_string_data.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eGENERIC_EXPRESSION.self) else { return nil } self.super_eGENERIC_EXPRESSION = super1 guard let super2 = complexEntity?.entityReference(eMATHS_FUNCTION.self) else { return nil } self.super_eMATHS_FUNCTION = super2 guard let super3 = complexEntity?.entityReference(eEXPLICIT_TABLE_FUNCTION.self) else { return nil } self.super_eEXPLICIT_TABLE_FUNCTION = super3 guard let super4 = complexEntity?.entityReference(eSIMPLE_GENERIC_EXPRESSION.self) else { return nil } self.super_eSIMPLE_GENERIC_EXPRESSION = super4 guard let super5 = complexEntity?.entityReference(eGENERIC_LITERAL.self) else { return nil } self.super_eGENERIC_LITERAL = super5 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "LISTED_STRING_DATA", type: self, explicitAttributeCount: 1) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eGENERIC_EXPRESSION.self) entityDef.add(supertype: eMATHS_FUNCTION.self) entityDef.add(supertype: eEXPLICIT_TABLE_FUNCTION.self) entityDef.add(supertype: eSIMPLE_GENERIC_EXPRESSION.self) entityDef.add(supertype: eGENERIC_LITERAL.self) entityDef.add(supertype: eLISTED_STRING_DATA.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "SHAPE", keyPath: \eLISTED_STRING_DATA.SHAPE, kind: .derivedRedeclaring, source: .thisEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "INDEX_BASE", keyPath: \eLISTED_STRING_DATA.INDEX_BASE, kind: .explicit, source: .superEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "VALUES", keyPath: \eLISTED_STRING_DATA.VALUES, kind: .explicit, source: .thisEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "DOMAIN", keyPath: \eLISTED_STRING_DATA.DOMAIN, kind: .derived, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "RANGE", keyPath: \eLISTED_STRING_DATA.RANGE, kind: .derived, source: .superEntity, mayYieldEntityReference: true) return entityDef } } } //MARK: - partial Entity Dynamic Attribute Protocol Conformances extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF._listed_string_data : eEXPLICIT_TABLE_FUNCTION__SHAPE__provider {}
39.572727
185
0.701202
3975e6f3090e6a3f962a3c399d5cf2b0435b6a48
1,288
// // TSQueue.swift // Pods // // Created by Andrew Sowers on 2/29/16. // // typealias b = String typealias e = String typealias i = String typealias small = String typealias s = String typealias u = String typealias color = String enum Element: String { case b = "b" case e = "e" case i = "i" case small = "small" case s = "s" case u = "u" case color = "color" } class QNode<T> { var value: T var next: QNode? init(item:T) { value = item } } public struct TSQueue<T> { private var top: QNode<T>! private var bottom: QNode<T>! public init() { top = nil bottom = nil } public mutating func enQueue(item: T) { let newNode:QNode<T> = QNode(item: item) if top == nil { top = newNode bottom = top return } bottom.next = newNode bottom = newNode } public mutating func deQueue() -> T? { let topItem: T? = top?.value if topItem == nil { return nil } if let nextItem = top.next { top = nextItem } else { top = nil bottom = nil } return topItem } public func isEmpty() -> Bool { return top == nil ? true : false } public func peek() -> T? { return top?.value } }
14.804598
44
0.541149
26aa4912cda74b79ddb057023aa0ce271fca094c
8,469
/* Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import ProgressHUD import UITextView_Placeholder import NCMB class DataStoreViewController: UIViewController { var currentObbjecId:String = "" @IBOutlet weak var menuButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Datastore" if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } @IBAction func btnQuickStartClick(_ sender: Any) { ProgressHUD.show("Please wait...") // クラスのNCMBObjectを作成 let object : NCMBObject = NCMBObject(className: "TestClass") // オブジェクトに値を設定 object["message"] = "Hello, NCMB!" // データストアへの登録 object.saveInBackground(callback: { result in DispatchQueue.main.async { ProgressHUD.dismiss() switch result { case .success: // 保存に成功した場合の処理 print("保存に成功しました") Utils.showAlert(self, title: "Alert", message: "保存に成功しました") case let .failure(error): // 保存に失敗した場合の処理 print("保存に失敗しました: \(error)") Utils.showAlert(self, title: "Alert", message: "保存に失敗しました: \(error)") } } }) } @IBAction func btnSaveClick(_ sender: Any) { ProgressHUD.show("Please wait...") // testクラスのNCMBObjectを作成 let object : NCMBObject = NCMBObject(className: "test") // オブジェクトに値を設定 object["fieldA"] = "Hello, NCMB!" object["fieldB"] = "日本語の内容" object["fieldC"] = 42 object["fieldD"] = ["abcd", "efgh", "ijkl"] // データストアへの登録を実施 object.saveInBackground(callback: { result in ProgressHUD.dismiss() switch result { case .success: // 保存に成功した場合の処理 print("保存に成功しました") DispatchQueue.main.async { Utils.showAlert(self, title: "Alert", message: "保存に成功しました") } self.currentObbjecId = object.objectId! case let .failure(error): // 保存に失敗した場合の処理 print("保存に失敗しました: \(error)") DispatchQueue.main.async { Utils.showAlert(self, title: "Alert", message: "保存に失敗しました: \(error)") } } }) } @IBAction func btnGetClick(_ sender: Any) { if (self.currentObbjecId != "") { ProgressHUD.show("Please wait...") let object : NCMBObject = NCMBObject(className: "test") // objectIdプロパティを設定 object.objectId = currentObbjecId object.fetchInBackground(callback: { result in DispatchQueue.main.async { ProgressHUD.dismiss() switch result { case .success: // 取得に成功した場合の処理 print("取得に成功しました") Utils.showAlert(self, title: "Alert", message: "取得に成功しました") if let fieldB : String = object["fieldB"] { print("fieldB value: \(fieldB)") } case let .failure(error): // 取得に失敗した場合の処理 print("取得に失敗しました: \(error)") Utils.showAlert(self, title: "Alert", message: "取得に失敗しました: \(error)") } } }) } else { print("There are no currentObjectId"); } } @IBAction func btnUpdateClick(_ sender: Any) { if (currentObbjecId != "") { ProgressHUD.show("Please wait...") let object : NCMBObject = NCMBObject(className: "test") // objectIdプロパティを設定 object.objectId = currentObbjecId object["fieldC"] = NCMBIncrementOperator(amount: 1) object.saveInBackground(callback: { result in DispatchQueue.main.async { ProgressHUD.dismiss() switch result { case .success: print("保存に成功しました") Utils.showAlert(self, title: "Alert", message: "保存に成功しました") case let .failure(error): print("保存に失敗しました: \(error)") Utils.showAlert(self, title: "Alert", message: "保存に失敗しました: \(error)") } } }) } else { print("There are no currentObjectId"); } } @IBAction func btnDeleteClick(_ sender: Any) { if (currentObbjecId != "") { ProgressHUD.show("Please wait...") let object : NCMBObject = NCMBObject(className: "test") object.objectId = currentObbjecId object.deleteInBackground(callback: { result in DispatchQueue.main.async { ProgressHUD.dismiss() switch result { case .success: self.currentObbjecId = "" print("削除に成功しました") Utils.showAlert(self, title: "Alert", message: "削除に成功しました") case let .failure(error): print("削除に失敗しました: \(error)") Utils.showAlert(self, title: "Alert", message: "削除に失敗しました: \(error)") } } }) } else { print("There are no currentObjectId"); } } @IBAction func btnRankingClick(_ sender: Any) { ProgressHUD.show("Please wait...") var query = NCMBQuery.getQuery(className: "HighScore") //Scoreの降順でデータを取得するように設定 query.order = ["Score"] //検索件数を5件に設定 query.limit = 5; //データストアでの検索を行う query.findInBackground(callback: { result in DispatchQueue.main.async { ProgressHUD.dismiss() switch result { case let .success(array): print("取得に成功しました 件数: \(array.count)") Utils.showAlert(self, title: "Alert", message: "取得に成功しました 件数: \(array.count)") case let .failure(error): print("取得に失敗しました: \(error)") Utils.showAlert(self, title: "Alert", message: "取得に失敗しました: \(error)") } } }) } @IBAction func btnAclClick(_ sender: Any) { ProgressHUD.show("Please wait...") let sharedNote : NCMBObject = NCMBObject(className: "Note") sharedNote["content"] = "This note is shared!" //NCMBACLのインスタンスを作成 var acl : NCMBACL = NCMBACL.empty //引数で渡された会員userへの読み込みと書き込み権限を設定する acl.put(key: "user1", readable: true, writable: true) //ACLをオブジェクトに設定する sharedNote.acl = acl sharedNote.saveInBackground(callback: { result in DispatchQueue.main.async { ProgressHUD.dismiss() switch result { case .success: print("保存に成功しました") Utils.showAlert(self, title: "Alert", message: "保存に成功しました") case let .failure(error): print("保存に失敗しました: \(error)") Utils.showAlert(self, title: "Alert", message: "保存に失敗しました: \(error)") } } }) } }
36.821739
98
0.514346
8a2af861ee6c4294ea386af8746f4cb2b41e71ca
2,176
// // CreateHabitView.swift // HabitTracker // // Created by Bogdan on 2/18/20. // Copyright © 2020 Codeswiftr. All rights reserved. // import SwiftUI struct CreateHabitView: View { @State var habitName : String = "" @State var placeHolder : String = "Enter habit name" @State var showField: Bool = true var body: some View { VStack{ ZStack(alignment: .leading) { TextField(self.placeHolder, text: self.$habitName){ print(self.habitName) } .padding(.all, 10) .frame(width: UIScreen.main.bounds.width - 50 , height: 50 ) .background(Color("darkGrey")) .cornerRadius(30) .foregroundColor(.white) .shadow(color: Color("orange"), radius: 10, x: 0, y: 10) .offset(x: self.showField ? 0 : (-UIScreen.main.bounds.width / 2 - 180)) .animation(.spring()) Image(systemName: "plus.circle") .resizable() .frame(width: 40, height: 40) .foregroundColor(.orange) .offset(x: self.showField ? (UIScreen.main.bounds.width - 90) : -30) .animation(.spring()) .onTapGesture { self.showField.toggle() // self.showView.toggle() } } .padding(.bottom, 20) .padding(.leading, 2) // TextField(self.$habitName,placeholder: Text( "What would you do?"), onEditingChanged: { // (changed) in // print(changed) // }) TemplateListView() } } } struct CreateHabitView_Previews: PreviewProvider { static var previews: some View { CreateHabitView() } }
36.881356
113
0.430147
e82764b35b5e9ea5bffc9f74bb92f4bde5b950ea
498
// // AppDelegate.swift // 5623_17_code // // Created by Stuart Grimshaw on 3/10/16. // Copyright © 2016 Stuart Grimshaw. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
18.444444
69
0.738956
9cdc2e8dcb97c9ba7dca78e540e438a322c89413
7,535
// // Date+Formatting.swift // Swiftlier // // Created by Andrew J Wagner on 10/9/15. // Copyright © 2015 Drewag LLC. All rights reserved. // import Foundation private let dateAndTimeFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier:"en_US_POSIX") dateFormatter.dateFormat = "yyyy'-'MM'-'dd' at 'hh:mm a" return dateFormatter }() private let timeFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.timeStyle = .short return dateFormatter }() private let dateFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier:"en_US_POSIX") dateFormatter.dateFormat = "MMM. dd, yyyy" return dateFormatter }() private let shortDateFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.setLocalizedDateFormatFromTemplate("MMddyyyy") return dateFormatter }() private let shortestDateFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.dateStyle = .short return dateFormatter }() private let dayAndMonthFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.setLocalizedDateFormatFromTemplate("MMdd") return dateFormatter }() private let monthAndYearFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.setLocalizedDateFormatFromTemplate("MMyyyy") return dateFormatter }() private let longMonthAndYearFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.setLocalizedDateFormatFromTemplate("MMMMyyyy") return dateFormatter }() private let monthFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier:"en_US_POSIX") dateFormatter.dateFormat = "MMMM" return dateFormatter }() private let yearFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier:"en_US_POSIX") dateFormatter.dateFormat = "yyyy" return dateFormatter }() private let gmtDateTimeFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier:"en_US_POSIX") dateFormatter.timeZone = TimeZone(identifier: "GMT") dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss 'GMT'" return dateFormatter }() private let railsDateTimeFormatter: DateFormatter = { var dateFormatter = DateFormatter() let timeZone = TimeZone(identifier: "UTC") dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" dateFormatter.timeZone = timeZone return dateFormatter }() public let ISO8601DateTimeFormatters: [DateFormatter] = { var dateFormatter1 = DateFormatter() let timeZone = TimeZone(identifier: "UTC") dateFormatter1.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'S'Z'" dateFormatter1.timeZone = timeZone var dateFormatter2 = DateFormatter() dateFormatter2.dateFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss'.'S'Z'" dateFormatter2.timeZone = timeZone var dateFormatter3 = DateFormatter() dateFormatter3.dateFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss'.'SSSSSS'Z'" dateFormatter3.timeZone = timeZone var dateFormatter4 = DateFormatter() dateFormatter4.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSSSSS'Z'" dateFormatter4.timeZone = timeZone var dateFormatter5 = DateFormatter() dateFormatter5.dateFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss'Z'" dateFormatter5.timeZone = timeZone return [dateFormatter1, dateFormatter2, dateFormatter3, dateFormatter4, dateFormatter5] }() private let localIso8601DateTimeFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'S" return dateFormatter }() private let railsDateFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy'-'MM'-'dd" return dateFormatter }() private let authTokenDate: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.dateFormat = "ddMMyyyy" return dateFormatter }() private let preciseTimeFormatter: DateFormatter = { var dateFormatter = DateFormatter() let timeZone = TimeZone(identifier: "UTC") dateFormatter.dateFormat = "HH':'mm':'ss" dateFormatter.timeZone = timeZone return dateFormatter }() extension Date { public var dateAndTime: String { return dateAndTimeFormatter.string(from: self) } public var date: String { return dateFormatter.string(from: self) } public var time: String { return timeFormatter.string(from: self) } public var shortDate: String { return shortDateFormatter.string(from: self) } public var shortestDate: String { return shortestDateFormatter.string(from: self) } public var dayAndMonth: String { return dayAndMonthFormatter.string(from: self) } public var monthAndYear: String { return monthAndYearFormatter.string(from: self) } public var longMonthAndYear: String { return longMonthAndYearFormatter.string(from: self) } public var month: String { return monthFormatter.string(from: self) } public var year: String { return yearFormatter.string(from: self) } public var railsDateTime: String { return railsDateTimeFormatter.string(from: self) } public var gmtDateTime: String { return gmtDateTimeFormatter.string(from: self) } public var iso8601DateTime: String { return ISO8601DateTimeFormatters.first!.string(from: self) } public var localIso8601DateTime: String { return localIso8601DateTimeFormatter.string(from: self) } public var sqliteDateTime: String { return railsDateTimeFormatter.string(from: self) } public var railsDate: String { return railsDateFormatter.string(from: self) } public var sqliteDate: String { return railsDateFormatter.string(from: self) } public var authToken: String { return authTokenDate.string(from: self) } public var preciseTime: String { return preciseTimeFormatter.string(from: self) } } extension String: ErrorGenerating { public var railsDateTime: Date? { return railsDateTimeFormatter.date(from: self) } public var railsDate: Date? { return railsDateFormatter.date(from: self) } public var shortDate: Date? { return shortDateFormatter.date(from: self) } public var gmtDate: Date? { return gmtDateTimeFormatter.date(from: self) } public var iso8601DateTime: Date? { for formatter in ISO8601DateTimeFormatters { if let date = formatter.date(from: self) { return date } } return nil } public func asIso8601DateTime() throws -> Date { guard let date = self.iso8601DateTime else { throw self.error("parsing date", because: "the date is invalid") } return date } public var localIso8601DateTime: Date? { var finalString = self.replacingOccurrences(of: " ", with: "T") if !finalString.contains(".") { finalString += ".0" } return localIso8601DateTimeFormatter.date(from: finalString) } public var date: Date? { return dateFormatter.date(from: self) } }
28.433962
91
0.688388
766af8a430ee3700c489ce417ee01d1ae1e25198
253
// // TicksSequence.swift // Dukascopy // // Created by Vitali Kurlovich on 4/20/20. // import Foundation public protocol TicksSequence: Sequence where Self.Element == Tick { var range: Range<Date> { get } var bounds: Range<Date> { get } }
18.071429
68
0.671937
e610ff067feecef07392c815ee828b6749bb812a
2,182
// // TableView03.swift // BasicTableView // // Created by Giftbot on 2020/05/25. // Copyright © 2020 giftbot. All rights reserved. // import UIKit final class TableViewRefresh: UIViewController { override var description: String { "TableView - Refresh" } /*************************************************** 테이블뷰를 새로 불러올 때마다 숫자 목록을 반대로 뒤집어서 출력하기 ***************************************************/ let tableView = UITableView() var data = Array(1...40) override func viewDidLoad() { super.viewDidLoad() setupTableView() // 1) 버튼 만들어서 갱신 navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Refresh", style: .plain, target: self, action: #selector(reloadData) ) } func setupTableView() { tableView.frame = view.frame tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellId") view.addSubview(tableView) // 2) Pull to Refresh let refreshControl = UIRefreshControl() refreshControl.tintColor = .red refreshControl.attributedTitle = NSAttributedString(string: "Refreshing...") refreshControl.addTarget(self, action: #selector(reloadData), for: .valueChanged) tableView.refreshControl = refreshControl // let attrStr = NSAttributedString( // string: "Refreshing...", // attributes: [ // .font: UIFont.systemFont(ofSize: 25), // .foregroundColor: UIColor.red, // .kern: 6, // ]) // refreshControl.attributedTitle = attrStr // Row 높이 tableView.rowHeight = 60 } @objc func reloadData() { data.reverse() tableView.refreshControl?.endRefreshing() tableView.reloadData() } } // MARK: - UITableViewDataSource extension TableViewRefresh: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CellId", for: indexPath) cell.textLabel?.text = "\(data[indexPath.row])" return cell } }
27.620253
98
0.647113
4a4f87392eaa65b17580f37e3aa5aee4b43ef2ff
5,683
// // ArrayExtSpec.swift // Swiftz // // Created by Robert Widmann on 1/19/15. // Copyright (c) 2015-2016 TypeLift. All rights reserved. // import XCTest import Swiftz import SwiftCheck #if SWIFT_PACKAGE import Operadics import Swiftx #endif class ArrayExtSpec : XCTestCase { func testProperties() { property("mapFlatten is the same as removing the optionals from an array and forcing") <- forAll { (xs0 : Array<Int?>) in return mapFlatten(xs0) == xs0.filter({ $0 != nil }).map({ $0! }) } property("indexArray is safe") <- forAll { (l : [Int]) in if l.isEmpty { return l.safeIndex(0) == nil } return l.safeIndex(0) != nil } property("Array fmap is the same as map") <- forAll { (xs : [Int]) in return ({ $0 + 1 } <^> xs) == xs.map({ $0 + 1 }) } property("Array pure give a singleton array") <- forAll { (x : Int) in return Array.pure(x) == [x] } property("Array bind works like a map then a concat") <- forAll { (xs : [Int]) in func fs(_ x : Int) -> [Int] { return [x, x+1, x+2] } return (xs >>- fs) == xs.map(fs).reduce([], +) } property("Array obeys the Functor identity law") <- forAll { (x : [Int]) in return (x.map(identity)) == identity(x) } property("Array obeys the Functor composition law") <- forAll { (_ f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>) in return forAll { (x : [Int]) in return ((f.getArrow • g.getArrow) <^> x) == (x.map(g.getArrow).map(f.getArrow)) } } property("Array obeys the Applicative identity law") <- forAll { (x : [Int]) in return (Array.pure(identity) <*> x) == x } property("Array obeys the Applicative homomorphism law") <- forAll { (_ f : ArrowOf<Int, Int>, x : Int) in return (Array.pure(f.getArrow) <*> Array.pure(x)) == Array.pure(f.getArrow(x)) } property("Array obeys the Applicative interchange law") <- forAll { (fu : Array<ArrowOf<Int, Int>>) in return forAll { (y : Int) in let u = fu.fmap { $0.getArrow } return (u <*> Array.pure(y)) == (Array.pure({ f in f(y) }) <*> u) } } property("Array obeys the first Applicative composition law") <- forAll { (fl : Array<ArrowOf<Int8, Int8>>, gl : Array<ArrowOf<Int8, Int8>>, x : Array<Int8>) in let f = fl.map({ $0.getArrow }) let g = gl.map({ $0.getArrow }) return (curry(•) <^> f <*> g <*> x) == (f <*> (g <*> x)) } property("Array obeys the second Applicative composition law") <- forAll { (fl : Array<ArrowOf<Int8, Int8>>, gl : Array<ArrowOf<Int8, Int8>>, x : Array<Int8>) in let f = fl.map({ $0.getArrow }) let g = gl.map({ $0.getArrow }) let lhs = Array.pure(curry(•)) <*> f <*> g <*> x let rhs = f <*> (g <*> x) return (lhs == rhs) // broken up as 'too complex' for compiler } property("Array obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, [Int]>) in let f = fa.getArrow return (Array.pure(a) >>- f) == f(a) } property("Array obeys the Monad right identity law") <- forAll { (m : [Int]) in return (m >>- Array.pure) == m } property("Array obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, [Int]>, ga : ArrowOf<Int, [Int]>) in let f = fa.getArrow let g = ga.getArrow return forAll { (m : [Int]) in return ((m >>- f) >>- g) == (m >>- { x in f(x) >>- g }) } } property("Array obeys the Monoidal left identity law") <- forAll { (x : Array<Int8>) in return (x <> []) == x } property("Array obeys the Monoidal right identity law") <- forAll { (x : Array<Int8>) in return ([] <> x) == x } property("scanl behaves") <- forAll { (withArray : [Int]) in let scanned = withArray.scanl(0, +) if withArray.isEmpty { return scanned == [0] } return scanned == [0] + [Int](withArray[1..<withArray.count]).scanl(0 + withArray.first!, +) } property("intersperse behaves") <- forAll { (withArray : [Int]) in let inter = withArray.intersperse(1) if withArray.isEmpty { return inter.isEmpty } return TestResult.succeeded // TODO: Test non-empty case } property("span behaves") <- forAll { (xs : [Int]) in return forAll { (pred : ArrowOf<Int, Bool>) in let p = xs.span(pred.getArrow) let t = (xs.takeWhile(pred.getArrow), xs.dropWhile(pred.getArrow)) return p.0 == t.0 && p.1 == t.1 } } property("extreme behaves") <- forAll { (xs : [Int]) in return forAll { (pred : ArrowOf<Int, Bool>) in let p = xs.extreme(pred.getArrow) let t = xs.span((!) • pred.getArrow) return p.0 == t.0 && p.1 == t.1 } } property("intercalate behaves") <- forAll { (xs : [Int], xxs : Array<[Int]>) in return intercalate(xs, nested: xxs) == concat(xxs.intersperse(xs)) } /* property("group for Equatable things is the same as groupBy(==)") <- forAll { (xs : [Int]) in return xs.group == xs.groupBy { $0 == $1 } } */ property("isPrefixOf behaves") <- forAll { (s1 : [Int], s2 : [Int]) in if s1.isPrefixOf(s2) { return s1.stripPrefix(s2) != nil } if s2.isPrefixOf(s1) { return s2.stripPrefix(s1) != nil } return Discard() } property("isSuffixOf behaves") <- forAll { (s1 : [Int], s2 : [Int]) in if s1.isSuffixOf(s2) { return s1.stripSuffix(s2) != nil } if s2.isSuffixOf(s1) { return s2.stripSuffix(s1) != nil } return Discard() } property("sequence occurs in order") <- forAll { (xs : [Int]) in let seq = sequence(xs.map(Array.pure)) return forAllNoShrink(Gen.pure(seq)) { ss in return (ss.first ?? []) == xs } } } #if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) static var allTests = testCase([ ("testProperties", testProperties) ]) #endif }
29.753927
163
0.588246
e03f2869178c97ac224ee5588eb35ea0569fde48
13,323
//------------------------------------------------------------------------------ // Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: test.fbe // FBE version: 1.10.0.0 //------------------------------------------------------------------------------ import Foundation import ChronoxorFbe import ChronoxorProto // Fast Binary Encoding StructArray field model public class FieldModelStructArray: FieldModel { public var _buffer: Buffer public var _offset: Int let f1: FieldModelArrayUInt8 let f2: FieldModelArrayOptionalUInt8 let f3: FieldModelArrayData let f4: FieldModelArrayOptionalData let f5: FieldModelArrayEnumSimple let f6: FieldModelArrayOptionalEnumSimple let f7: FieldModelArrayFlagsSimple let f8: FieldModelArrayOptionalFlagsSimple let f9: FieldModelArrayStructSimple let f10: FieldModelArrayOptionalStructSimple // Field size public let fbeSize: Int = 4 // Field body size public let fbeBody: Int // Set the struct value (end phase) public required init() { let buffer = Buffer() let offset = 0 _buffer = buffer _offset = offset f1 = FieldModelArrayUInt8(buffer: buffer, offset: 4 + 4, size: 2) f2 = FieldModelArrayOptionalUInt8(buffer: buffer, offset: f1.fbeOffset + f1.fbeSize, size: 2) f3 = FieldModelArrayData(buffer: buffer, offset: f2.fbeOffset + f2.fbeSize, size: 2) f4 = FieldModelArrayOptionalData(buffer: buffer, offset: f3.fbeOffset + f3.fbeSize, size: 2) f5 = FieldModelArrayEnumSimple(buffer: buffer, offset: f4.fbeOffset + f4.fbeSize, size: 2) f6 = FieldModelArrayOptionalEnumSimple(buffer: buffer, offset: f5.fbeOffset + f5.fbeSize, size: 2) f7 = FieldModelArrayFlagsSimple(buffer: buffer, offset: f6.fbeOffset + f6.fbeSize, size: 2) f8 = FieldModelArrayOptionalFlagsSimple(buffer: buffer, offset: f7.fbeOffset + f7.fbeSize, size: 2) f9 = FieldModelArrayStructSimple(buffer: buffer, offset: f8.fbeOffset + f8.fbeSize, size: 2) f10 = FieldModelArrayOptionalStructSimple(buffer: buffer, offset: f9.fbeOffset + f9.fbeSize, size: 2) var fbeBody = (4 + 4) fbeBody += f1.fbeSize fbeBody += f2.fbeSize fbeBody += f3.fbeSize fbeBody += f4.fbeSize fbeBody += f5.fbeSize fbeBody += f6.fbeSize fbeBody += f7.fbeSize fbeBody += f8.fbeSize fbeBody += f9.fbeSize fbeBody += f10.fbeSize self.fbeBody = fbeBody } // public required init(buffer: Buffer = Buffer(), offset: Int = 0) { _buffer = buffer _offset = offset f1 = FieldModelArrayUInt8(buffer: buffer, offset: 4 + 4, size: 2) f2 = FieldModelArrayOptionalUInt8(buffer: buffer, offset: f1.fbeOffset + f1.fbeSize, size: 2) f3 = FieldModelArrayData(buffer: buffer, offset: f2.fbeOffset + f2.fbeSize, size: 2) f4 = FieldModelArrayOptionalData(buffer: buffer, offset: f3.fbeOffset + f3.fbeSize, size: 2) f5 = FieldModelArrayEnumSimple(buffer: buffer, offset: f4.fbeOffset + f4.fbeSize, size: 2) f6 = FieldModelArrayOptionalEnumSimple(buffer: buffer, offset: f5.fbeOffset + f5.fbeSize, size: 2) f7 = FieldModelArrayFlagsSimple(buffer: buffer, offset: f6.fbeOffset + f6.fbeSize, size: 2) f8 = FieldModelArrayOptionalFlagsSimple(buffer: buffer, offset: f7.fbeOffset + f7.fbeSize, size: 2) f9 = FieldModelArrayStructSimple(buffer: buffer, offset: f8.fbeOffset + f8.fbeSize, size: 2) f10 = FieldModelArrayOptionalStructSimple(buffer: buffer, offset: f9.fbeOffset + f9.fbeSize, size: 2) var fbeBody = (4 + 4) fbeBody += f1.fbeSize fbeBody += f2.fbeSize fbeBody += f3.fbeSize fbeBody += f4.fbeSize fbeBody += f5.fbeSize fbeBody += f6.fbeSize fbeBody += f7.fbeSize fbeBody += f8.fbeSize fbeBody += f9.fbeSize fbeBody += f10.fbeSize self.fbeBody = fbeBody } // Field extra size public var fbeExtra: Int { if _buffer.offset + fbeOffset + fbeSize > _buffer.size { return 0 } let fbeStructOffset = Int(readUInt32(offset: fbeOffset)) if (fbeStructOffset == 0) || ((_buffer.offset + fbeStructOffset + 4) > _buffer.size) { return 0 } _buffer.shift(offset: fbeStructOffset) var fbeResult = fbeBody fbeResult += f1.fbeExtra fbeResult += f2.fbeExtra fbeResult += f3.fbeExtra fbeResult += f4.fbeExtra fbeResult += f5.fbeExtra fbeResult += f6.fbeExtra fbeResult += f7.fbeExtra fbeResult += f8.fbeExtra fbeResult += f9.fbeExtra fbeResult += f10.fbeExtra _buffer.unshift(offset: fbeStructOffset) return fbeResult } // Field type public var fbeType: Int = fbeTypeConst public static let fbeTypeConst: Int = 125 // Check if the struct value is valid func verify(fbeVerifyType: Bool = true) -> Bool { if (_buffer.offset + fbeOffset + fbeSize) > _buffer.size { return true } let fbeStructOffset = Int(readUInt32(offset: fbeOffset)) if (fbeStructOffset == 0) || ((_buffer.offset + fbeStructOffset + 4 + 4) > _buffer.size) { return false } let fbeStructSize = Int(readUInt32(offset: fbeStructOffset)) if fbeStructSize < (4 + 4) { return false } let fbeStructType = Int(readUInt32(offset: fbeStructOffset + 4)) if fbeVerifyType && (fbeStructType != fbeType) { return false } _buffer.shift(offset: fbeStructOffset) let fbeResult = verifyFields(fbeStructSize: fbeStructSize) _buffer.unshift(offset: fbeStructOffset) return fbeResult } // Check if the struct fields are valid public func verifyFields(fbeStructSize: Int) -> Bool { var fbeCurrentSize = 4 + 4 if (fbeCurrentSize + f1.fbeSize) > fbeStructSize { return true } if !f1.verify() { return false } fbeCurrentSize += f1.fbeSize if (fbeCurrentSize + f2.fbeSize) > fbeStructSize { return true } if !f2.verify() { return false } fbeCurrentSize += f2.fbeSize if (fbeCurrentSize + f3.fbeSize) > fbeStructSize { return true } if !f3.verify() { return false } fbeCurrentSize += f3.fbeSize if (fbeCurrentSize + f4.fbeSize) > fbeStructSize { return true } if !f4.verify() { return false } fbeCurrentSize += f4.fbeSize if (fbeCurrentSize + f5.fbeSize) > fbeStructSize { return true } if !f5.verify() { return false } fbeCurrentSize += f5.fbeSize if (fbeCurrentSize + f6.fbeSize) > fbeStructSize { return true } if !f6.verify() { return false } fbeCurrentSize += f6.fbeSize if (fbeCurrentSize + f7.fbeSize) > fbeStructSize { return true } if !f7.verify() { return false } fbeCurrentSize += f7.fbeSize if (fbeCurrentSize + f8.fbeSize) > fbeStructSize { return true } if !f8.verify() { return false } fbeCurrentSize += f8.fbeSize if (fbeCurrentSize + f9.fbeSize) > fbeStructSize { return true } if !f9.verify() { return false } fbeCurrentSize += f9.fbeSize if (fbeCurrentSize + f10.fbeSize) > fbeStructSize { return true } if !f10.verify() { return false } fbeCurrentSize += f10.fbeSize return true } // Get the struct value (begin phase) func getBegin() -> Int { if _buffer.offset + fbeOffset + fbeSize > _buffer.size { return 0 } let fbeStructOffset = Int(readUInt32(offset: fbeOffset)) if (fbeStructOffset == 0) || ((_buffer.offset + fbeStructOffset + 4 + 4) > _buffer.size) { assertionFailure("Model is broken!") return 0 } let fbeStructSize = Int(readUInt32(offset: fbeStructOffset)) if fbeStructSize < 4 + 4 { assertionFailure("Model is broken!") return 0 } _buffer.shift(offset: fbeStructOffset) return fbeStructOffset } // Get the struct value (end phase) func getEnd(fbeBegin: Int) { _buffer.unshift(offset: fbeBegin) } // Get the struct value public func get() -> StructArray { var fbeValue = StructArray() return get(fbeValue: &fbeValue) } public func get(fbeValue: inout StructArray) -> StructArray { let fbeBegin = getBegin() if fbeBegin == 0 { return fbeValue } let fbeStructSize = Int(readUInt32(offset: 0)) getFields(fbeValue: &fbeValue, fbeStructSize: fbeStructSize) getEnd(fbeBegin: fbeBegin) return fbeValue } // Get the struct fields values public func getFields(fbeValue: inout StructArray, fbeStructSize: Int) { var fbeCurrentSize = 4 + 4 if fbeCurrentSize + f1.fbeSize <= fbeStructSize { f1.get(values: &fbeValue.f1) } else { fbeValue.f1 = Array() } fbeCurrentSize += f1.fbeSize if fbeCurrentSize + f2.fbeSize <= fbeStructSize { f2.get(values: &fbeValue.f2) } else { fbeValue.f2 = Array() } fbeCurrentSize += f2.fbeSize if fbeCurrentSize + f3.fbeSize <= fbeStructSize { f3.get(values: &fbeValue.f3) } else { fbeValue.f3 = Array() } fbeCurrentSize += f3.fbeSize if fbeCurrentSize + f4.fbeSize <= fbeStructSize { f4.get(values: &fbeValue.f4) } else { fbeValue.f4 = Array() } fbeCurrentSize += f4.fbeSize if fbeCurrentSize + f5.fbeSize <= fbeStructSize { f5.get(values: &fbeValue.f5) } else { fbeValue.f5 = Array() } fbeCurrentSize += f5.fbeSize if fbeCurrentSize + f6.fbeSize <= fbeStructSize { f6.get(values: &fbeValue.f6) } else { fbeValue.f6 = Array() } fbeCurrentSize += f6.fbeSize if fbeCurrentSize + f7.fbeSize <= fbeStructSize { f7.get(values: &fbeValue.f7) } else { fbeValue.f7 = Array() } fbeCurrentSize += f7.fbeSize if fbeCurrentSize + f8.fbeSize <= fbeStructSize { f8.get(values: &fbeValue.f8) } else { fbeValue.f8 = Array() } fbeCurrentSize += f8.fbeSize if fbeCurrentSize + f9.fbeSize <= fbeStructSize { f9.get(values: &fbeValue.f9) } else { fbeValue.f9 = Array() } fbeCurrentSize += f9.fbeSize if fbeCurrentSize + f10.fbeSize <= fbeStructSize { f10.get(values: &fbeValue.f10) } else { fbeValue.f10 = Array() } fbeCurrentSize += f10.fbeSize } // Set the struct value (begin phase) func setBegin() throws -> Int { if (_buffer.offset + fbeOffset + fbeSize) > _buffer.size { assertionFailure("Model is broken!") return 0 } let fbeStructSize = fbeBody let fbeStructOffset = try _buffer.allocate(size: fbeStructSize) - _buffer.offset if (fbeStructOffset <= 0) || ((_buffer.offset + fbeStructOffset + fbeStructSize) > _buffer.size) { assertionFailure("Model is broken!") return 0 } write(offset: fbeOffset, value: UInt32(fbeStructOffset)) write(offset: fbeStructOffset, value: UInt32(fbeStructSize)) write(offset: fbeStructOffset + 4, value: UInt32(fbeType)) _buffer.shift(offset: fbeStructOffset) return fbeStructOffset } // Set the struct value (end phase) public func setEnd(fbeBegin: Int) { _buffer.unshift(offset: fbeBegin) } // Set the struct value public func set(value fbeValue: StructArray) throws { let fbeBegin = try setBegin() if fbeBegin == 0 { return } try setFields(fbeValue: fbeValue) setEnd(fbeBegin: fbeBegin) } // Set the struct fields values public func setFields(fbeValue: StructArray) throws { try f1.set(value: fbeValue.f1) try f2.set(value: fbeValue.f2) try f3.set(value: fbeValue.f3) try f4.set(value: fbeValue.f4) try f5.set(value: fbeValue.f5) try f6.set(value: fbeValue.f6) try f7.set(value: fbeValue.f7) try f8.set(value: fbeValue.f8) try f9.set(value: fbeValue.f9) try f10.set(value: fbeValue.f10) } }
31.873206
109
0.578548
5bb0dd0ebd54e1b013fbf2d8fd94933240e27fa0
2,385
/** * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import IBMMobileFirstPlatformFoundation protocol LoginViewControllerDelegate { func LoginViewControllerResponse(userName: String) } class LoginViewController: UIViewController { @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var errorLabel: UILabel! var delegate: LoginViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.setHidesBackButton(true, animated:true); self.navigationItem.title = "Enrollment" NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(popLoginPage(_:)), name: ACTION_USERLOGIN_CHALLENGE_SUCCESS, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showError(_:)), name: ACTION_USERLOGIN_CHALLENGE_RECEIVED, object: nil) } @IBAction func login(sender: AnyObject) { if(self.username.text != "" && self.password.text != ""){ NSNotificationCenter.defaultCenter().postNotificationName(ACTION_USERLOGIN_SUBMIT_ANSWER, object: self, userInfo: ["username": username.text!, "password": password.text!]) } else { errorLabel.text = "Username and password are required" } } func popLoginPage(notification: NSNotification){ self.delegate?.LoginViewControllerResponse(notification.userInfo!["displayName"] as! String) self.navigationController?.popViewControllerAnimated(true) } func showError(notification: NSNotification){ self.errorLabel.text = notification.userInfo!["errorMsg"] as? String } override func viewDidDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self) } }
38.467742
183
0.72327