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
fbec37451f7accb4f7f70f18a763ef524a93f3c6
5,676
// // JNHorizontalGroupAvatarCollectionView.swift // JNHorizontalGroupAvatarCollectionView // // Created by JNDisrupter on 2/22/18. // import UIKit import JNGroupAvatarImageView /// JNHorizontal Group Avatar Collection View open class JNHorizontalGroupAvatarCollectionView: UIView, UICollectionViewDataSource { /// Collection view @IBOutlet private weak var collectionView: UICollectionView! /// Harri custom selection view Delegate public var delegate: JNHorizontalGroupAvatarCollectionViewDelegate? /// Cell padding public var cellPadding: CGFloat = 20 /// Images Layout Direction public var imagesLayoutDirection: ImagesLayoutDirection = ImagesLayoutDirection.rightToLeft /// Avatars Margin public var avatarsMargin: CGFloat = 0.0 /// Avatars Separator Color public var separatorColor: UIColor = UIColor.gray /// Avatars Place Holder Image public var placeHolderImage: UIImage! = nil /// Show Initails public var showInitails: Bool = true /// Initials Font public var initialsFont: UIFont = UIFont.systemFont(ofSize: 14) /// Initial Text Color public var initialTextColor: UIColor = UIColor.black /** Initializer */ convenience public init() { self.init(frame: CGRect.zero) } /** Initializer */ override public init(frame: CGRect) { super.init(frame: frame) // Initialize view self.initView() } /** Initializer */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Initialize view self.initView() } /** Awake from Nib */ override open func awakeFromNib() { super.awakeFromNib() // Set collection data source and delegate self.collectionView.dataSource = self self.collectionView.showsHorizontalScrollIndicator = false // Register cell let bundle = Bundle(for: AvatarCollectionViewCell.self) let nib = UINib(nibName: "AvatarCollectionViewCell", bundle: bundle) self.collectionView.register(nib, forCellWithReuseIdentifier: AvatarCollectionViewCell.getReuseIdentifier()) // Set collection ayout let layout = AvatarsCollectionViewFlowLayout() layout.cellPadding = self.cellPadding self.collectionView.collectionViewLayout = layout } /** Did click clear */ @IBAction private func didClickClear(_ sender: UIButton) { // Call delegate self.delegate?.horizontalGroupAvatarCollectionViewDidClearData() } /** Reload data */ public func reloadData() { self.collectionView.reloadData() } /** Initialize the sub views */ private func initView() { let bundle = Bundle(for: JNHorizontalGroupAvatarCollectionView.self) let nib = UINib(nibName: "JNHorizontalGroupAvatarCollectionView", bundle: bundle) // Instantiate view from nib if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView { view.translatesAutoresizingMaskIntoConstraints = false self.addSubview(view) // Add View constraints view.topAnchor.constraint(equalTo: self.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true view.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true view.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true } } // MARK: - UICollectionViewDataSource /** Number of sections */ public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } /** Number of items in section */ public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.delegate?.horizontalGroupAvatarCollectionViewNumberOfItems() ?? 0 } /** Cell for item at index */ public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // Get cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AvatarCollectionViewCell.getReuseIdentifier(), for: indexPath) as! AvatarCollectionViewCell if let cellData = self.delegate?.horizontalGroupAvatarCollectionView(dataForItemAt: indexPath.row) { // Setup cell cell.setup(avatars: cellData, imagesLayoutDirection: self.imagesLayoutDirection, avatarsMargin: self.avatarsMargin, separatorColor: self.separatorColor, placeHolderImage: self.placeHolderImage, showInitails: self.showInitails, initialsFont: self.initialsFont, initialTextColor: self.initialTextColor) } return cell } } /// JN horizontal group avatar collection view Delegate public protocol JNHorizontalGroupAvatarCollectionViewDelegate { /** Number of items - Returns: The number of items in collection view */ func horizontalGroupAvatarCollectionViewNumberOfItems() -> Int /** Data for item at index - Parameter index: The item index - Returns: The data for the item */ func horizontalGroupAvatarCollectionView(dataForItemAt index: Int) -> [JNGroupAvatar] /** Did clear data */ func horizontalGroupAvatarCollectionViewDidClearData() }
30.681081
312
0.659619
23c9dc6ecaaf66815e0feb9f5df26813444ddf4c
3,754
// // ApiClient.swift // virtual-tourist // // Created by Ischuk Alexander on 01.06.2020. // Copyright © 2020 Ischuk Alexander. All rights reserved. // import Foundation class ApiClient { let dataController: DataController! init(dataController: DataController) { self.dataController = dataController } enum ApiEndpoint { static let baseUrl = "https://api.flickr.com/services/rest/?" static let apiKey = "7344c51b882809d943e3a633518bb25b" case list(latitude: Double, longitude: Double, page: Int) case detail(farmId: String, serverId:String, photoId: String, secret: String) } enum ApiError: Error { case networkError case decodingError } func getUrl(for endpoint: ApiEndpoint) -> String { switch endpoint { case .list(let latitude, let longitude, let page): return "\(ApiEndpoint.baseUrl)method=flickr.photos.search&api_key=\(ApiEndpoint.apiKey)&format=json&privacy_filter=1&lat=\(latitude)&lon=\(longitude)&nojsoncallback=1&per_page=50&page=\(page)" case .detail(let farmId, let serverId, let photoId, let secret): return "https://farm\(farmId).staticflickr.com/\(serverId)/\(photoId)_\(secret)_s.jpg" } } func loadList(latitude: Double, longitude: Double, page: Int, result: @escaping (PhotosWithPagesCount?, ApiError?) -> Void) { makeGETRequest(endpoint: .list(latitude: latitude, longitude: longitude, page: page)) { (photosResponse: PhotosResponse?, error) in guard error == nil else {result(nil, error); return} let items = photosResponse!.photos.photo.map { (photoResponse) -> Photo in let photo = Photo(context: self.dataController.viewContext) photo.id = photoResponse.id photo.farmId = "\(photoResponse.farm)" photo.serverId = photoResponse.server photo.secret = photoResponse.secret return photo } try? self.dataController.viewContext.save() let photosWithPagesCount = PhotosWithPagesCount(pages: photosResponse!.photos.pages, photos: items) result(photosWithPagesCount, nil) } } func loadPhoto(photo: Photo, result: @escaping (Data?, ApiError?) -> Void) { let request = URLRequest(url: URL(string: getUrl(for: .detail(farmId: photo.farmId!, serverId: photo.serverId!, photoId: photo.id!, secret: photo.secret!)))!) URLSession.shared.dataTask(with: request) {data, response, error in if error != nil { result(nil, .networkError) return } result(data, nil) }.resume() } func makeGETRequest<ResponseType: Decodable>(endpoint: ApiEndpoint, result: @escaping (ResponseType?, ApiError?) -> Void) { let request = URLRequest(url: URL(string: getUrl(for: endpoint))!) let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if error != nil { result(nil, .networkError) return } let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase guard data != nil else { result(nil, .networkError) return } guard let decoded = try? decoder.decode(ResponseType.self, from: data!) else { result(nil, .decodingError) return } result(decoded, nil) } task.resume() } }
37.919192
204
0.591902
6900873da77e43c0ab773217f5f78a3507df24e3
535
// // FilterBuilder.swift // NasaPictures // // Created by mdt on 2.12.2021. // import UIKit final class FilterBuilder { static func make(with viewModel: FilterViewModelProtocol, mainModel: MainBuilderModel) -> FilterVC { let storyboard = UIStoryboard(name: "FilterVC", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "FilterVC") as! FilterVC viewController.viewModel = viewModel viewController.mainModel = mainModel return viewController } }
28.157895
106
0.714019
0eac8e3aac784834420951fcad165170b9bf1735
6,176
import Dispatch import Foundation import Numerics func fib(_ n: Int) -> Int { if n < 2 { return n } return fib(n-1) + fib(n-2) } func parse_integers(_ t: Int) { for _ in 1 ..< t { let n = Int.random(in: 0...((2 << 32) - 1)) let s = "\(n)" let m = Int(s) assert(m == n) } } func qsort_kernel(_ a: inout [Double], _ lo: Int, _ hi: Int) -> [Double] { var low = lo let high = hi var i = low var j = high while i < high { let pivot = a[(low + high) / 2] while i <= j { while a[i] < pivot { i += 1 } while a[j] > pivot { j -= 1 } if i <= j { let tmp = a[i] a[i] = a[j] a[j] = tmp i += 1 j -= 1 } } if low < j { a = qsort_kernel(&a, low, j) } low = i j = high } return a } // FIXME func randmatstat(_ t: Int) -> (Double, Double) { // let n = 5 // var v = [Double](count: t, repeatedValue: 0.0) // var w = [Double](count: t, repeatedValue: 0.0) for _ in 1...t { } // return (std(v)/mean(v), std(w)/mean(w)) return (0.75, 0.75) } // FIXME func randmatmul(_ n: Int) -> [[Int]] { return [[0]] } func abs2(_ z: Complex<Double>) -> Double { return z.real*z.real + z.imaginary*z.imaginary } func mandel(_ z: Complex<Double>) -> Int { let maxiter = 80 var y = z let c = z for n in 1...maxiter { if (abs2(y) > 4.0) { return n - 1 } y = y * y + c } return maxiter } func mandelperf() -> [Int] { let eps = 0.01 // stride will stop short due to numerical imprecision let r1 = stride(from: -2.0, to: 0.5 + eps, by: 0.1) let r2 = stride(from: -1.0, to: 1.0 + eps, by: 0.1) var mandelset = [Int]() for r in r1 { for i in r2 { mandelset.append(mandel(Complex(r, i))) } } return mandelset } func pisum() -> Double { var sum = 0.0 for _ in 1...500 { sum = 0.0 for k in stride(from: 1.0, to: 10000.0, by: 1.0) { sum += 1.0/(k*k) } } return sum } func printfd(_ n: Int) { let file_url = URL(fileURLWithPath: "/dev/null") let f = try! FileHandle(forWritingTo: file_url) for i in 1...n { let str = "\(i) \(i + 1)" let data = Data(str.utf8) f.write(data) } f.closeFile() } func print_perf(name: String, time: Double) { print("swift," + name + "," + String(time)) } // run tests func main() { let mintrials = 5 assert(fib(20) == 6765) var tmin = Double.greatestFiniteMagnitude for _ in 1...mintrials { let start_time = DispatchTime.now().uptimeNanoseconds _ = fib(20) let end_time = DispatchTime.now().uptimeNanoseconds let t = Double(end_time - start_time) / 1_000_000 if t < tmin {tmin = t} } print_perf(name: "recursion_fibonacci", time: tmin) tmin = Double.greatestFiniteMagnitude for _ in 1...mintrials { let start_time = DispatchTime.now().uptimeNanoseconds parse_integers(1000) let end_time = DispatchTime.now().uptimeNanoseconds let t = Double(end_time - start_time) / 1_000_000 if t < tmin {tmin = t} } print_perf(name: "parse_integers", time: tmin) // mandelperf has numerical errors workaround true assert value // assert(mandelperf().reduce(0, +) == 14791) assert(mandelperf().reduce(0, +) == 14643) tmin = Double.greatestFiniteMagnitude for _ in 1...mintrials { let start_time = DispatchTime.now().uptimeNanoseconds _ = mandelperf() let end_time = DispatchTime.now().uptimeNanoseconds let t = Double(end_time - start_time) / 1_000_000 if t < tmin {tmin = t} } print_perf(name: "userfunc_mandelbrot", time: tmin) tmin = Double.greatestFiniteMagnitude for _ in 1...mintrials { var lst = [Double]() for _ in 0 ..< 50000 { let random_double = Double.random(in: 0..<1) lst.append(random_double) } let start_time = DispatchTime.now().uptimeNanoseconds _ = qsort_kernel(&lst, 0, lst.count-1) let end_time = DispatchTime.now().uptimeNanoseconds let t = Double(end_time - start_time) / 1_000_000 if t < tmin {tmin = t} } print_perf(name: "recursion_quicksort", time: tmin) assert(abs(pisum()-1.644834071848065) < 1e-6) tmin = Double.greatestFiniteMagnitude for _ in 1...mintrials { let start_time = DispatchTime.now().uptimeNanoseconds _ = pisum() let end_time = DispatchTime.now().uptimeNanoseconds let t = Double(end_time - start_time) / 1_000_000 if t < tmin {tmin = t} } print_perf(name: "iteration_pi_sum", time: tmin) let (s1, s2) = randmatstat(1000) assert(s1 > 0.5 && s2 < 1.0) tmin = Double.greatestFiniteMagnitude for _ in 1...mintrials { let start_time = DispatchTime.now().uptimeNanoseconds _ = randmatstat(100) let end_time = DispatchTime.now().uptimeNanoseconds let t = Double(end_time - start_time) / 1_000_000 if t < tmin {tmin = t} } print_perf(name: "matrix_statistics", time: tmin) tmin = Double.greatestFiniteMagnitude for _ in 1...mintrials { let start_time = DispatchTime.now().uptimeNanoseconds let C = randmatmul(1000) assert(C[0][0] >= 0) let end_time = DispatchTime.now().uptimeNanoseconds let t = Double(end_time - start_time) / 1_000_000 if t < tmin {tmin = t} } print_perf(name: "matrix_multiply", time: tmin) tmin = Double.greatestFiniteMagnitude for _ in 1...mintrials { let start_time = DispatchTime.now().uptimeNanoseconds printfd(100000) let end_time = DispatchTime.now().uptimeNanoseconds let t = Double(end_time - start_time) / 1_000_000 if t < tmin {tmin = t} } print_perf(name: "print_to_file", time: tmin) } main()
27.695067
74
0.554242
29baff5e463eb3219face480e18491a839b35bb3
133
import Basic import Foundation import PathKit extension AbsolutePath { var path: Path { return Path(pathString) } }
13.3
31
0.691729
4a5238c481dc9522e128fa2aebf489172997688a
2,455
/* MIT License Copyright (c) 2017-2019 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit internal extension UIColor { private static func colorFromAssetBundle(named: String) -> UIColor { // guard let color = UIColor.red else { // fatalError(MessageKitError.couldNotFindColorAsset) // } return UIColor.red } static var incomingMessageBackground: UIColor { colorFromAssetBundle(named: "incomingMessageBackground") } static var outgoingMessageBackground: UIColor { colorFromAssetBundle(named: "outgoingMessageBackground") } static var incomingMessageLabel: UIColor { colorFromAssetBundle(named: "incomingMessageLabel") } static var outgoingMessageLabel: UIColor { colorFromAssetBundle(named: "outgoingMessageLabel") } static var incomingAudioMessageTint: UIColor { colorFromAssetBundle(named: "incomingAudioMessageTint") } static var outgoingAudioMessageTint: UIColor { colorFromAssetBundle(named: "outgoingAudioMessageTint") } static var collectionViewBackground: UIColor { colorFromAssetBundle(named: "collectionViewBackground") } static var typingIndicatorDot: UIColor { colorFromAssetBundle(named: "typingIndicatorDot") } static var label: UIColor { colorFromAssetBundle(named: "label") } static var avatarViewBackground: UIColor { colorFromAssetBundle(named: "avatarViewBackground") } }
42.327586
111
0.765784
67046b439aa04c314234a973dc2fa057b690a969
14,192
// // L10n+Views.swift // // // Created by Данис Тазетдинов on 12.02.2022. // import Foundation import Localization import UIKit extension L10n.Common { // edit button has shorter version on iPhone/iPad for Russian locale static var buttonEdit: L10n.Common { if UIDevice.current.userInterfaceIdiom == .mac { return .buttonEditMac } else { return .buttonEditPhone } } } extension L10n { enum Category: String, Localizable { case sectionTitle = "category.section.title" // Category case createCategoryNamed = "category.create.named" // "Create category '\(trimmedTitle)'" case customIcon = "category.customIcon" // "Icon" case title = "category.title" // "Category" case categoryForItem = "category.tile.forItem" // "Category for %@" case unnamedCategory = "category.unnamed" // Unnamed } enum ConditionView: String, Localizable { case title = "condition.view.title" case conditionForItem = "condition.tile.forItem" } enum ItemAssignment: String, Localizable { case addItemToChecklistsTitle = "item.assignment.addToChecklists.title" // "Add \(item.title) to checklists" } enum ItemDetails: String, Localizable { case newItemTitle = "item.details.newItemTitle" // New item case itemTitlePlaceholder = "item.details.itemTitle.placeholder" // "Item title" case itemSectionTitle = "item.details.section.item.title" // "Item" case detailsPlaceholder = "item.details.itemDetails.placeholder" // "Item details" case detailsSectionTitle = "item.details.section.details.title" // "Details" case noPlaceIsSet = "item.details.noPlaceIsSet" // "No place is set" case shouldRemoveImage = "item.details.shouldRemoveImage" // "Remove image?" case showImageAccessibility = "item.details.showImageAccessibility" // "Show the image" case removeImageConfirmation = "item.details.removeImage.confirmation" // "Remove" case addPhotosTitle = "item.details.addPhotos.title" // "Add photos of the item" case takePhotoTitle = "item.details.takePhoto.title" // "Take photo..." case choosePhotosTitle = "item.details.choosePhotos.title" // "Choose from library..." case noCameraAccessTitle = "item.details.noCameraAccess.title" // "Camera access is not allowed" case buttonOpenSettings = "item.details.button.openSettings" // "Open settings" case imagesSectionTitle = "item.details.section.images.title" // "Images" case predictingTitle = "item.details.predicting.title" // "Predicting..." case fetchingImagesTitle = "item.details.fetchingImages.title" // "Fetching images..." case buttonAddToChecklist = "item.details.button.addToChecklist" //"Add to checklist" case itemNoLongerAvailable = "item.details.noLongerAvailable" // "Item is no longer available" } enum ItemWelcome: String, Localizable { case chooseExisting = "item.welcome.chooseExisting" // "Choose existing item" case orLabel = "item.welcome.or.label" case createNewButton = "item.welcome.createNew.button" // "Add new" } enum ItemsList: String, Localizable { case listTitle = "items.list.title" case addToChecklistsButton = "items.list.addToChecklists.button" // "Add to checklists..." case shouldDeleteItem = "items.list.shouldDeleteItem" // "Delete \(item.title)?" case searchPlaceholder = "items.list.searchPlaceholder" // "Search for items..." case addItemButton = "items.list.addItem.button" // "Add item" case menu = "items.list.menu" enum Grouping: String, Localizable { case byCategory = "items.list.group.byCategory" case byPlace = "items.list.group.byPlace" case byCondition = "items.list.group.byCondition" } } enum PlaceDetails: String, Localizable { case title = "place.details.title" // "Place" case placeNoLongerAvailable = "place.details.noLongerAvailable" // "Place is no longer available" case placeIsEmpty = "place.details.isEmpty" // "Place is empty" } enum PlacesList: String, Localizable { case listTitle = "places.list.title" // "Places" case searchPlaceholder = "places.list.searchPlaceholder" // "Search for places..." case noPlaceAssigned = "places.list.noPlaceAssigned" // "No place assigned" case placeItemsButton = "places.list.placeItems.button" // "Place items..." case shouldDeletePlace = "places.list.shouldDeletePlace" // "Delete \(item.title)?" case addPlaceButton = "places.list.addPlace.button" // "Add place" case placeItemsToTitle = "places.list.placeItemsTo.title" // "Place items to \(place.title)" case filterItemsPlaceholder = "places.list.filterItems.placeholder" // "Filter items..." case addNewPlaceButton = "places.list.addNewPlace.button" // "Add new place..." case placeForItem = "places.list.placeForItem" case menu = "places.list.menu" enum Sort: String, Localizable { case byTitle = "places.list.sort.byTitle" case byItemsCount = "places.list.sort.byItemsCount" } } enum PlaceWelcome: String, Localizable { case chooseExisting = "place.welcome.chooseExisting" // "Choose existing place" case orLabel = "place.welcome.or.label" case createNewButton = "place.welcome.createNew.button" // "Add new" } enum EditPlace: String, Localizable { case titlePlaceholder = "place.edit.title.placeholder" // "New place title" case titleSectionTitle = "place.edit.title.section.title" // "Title" case customIcon = "place.edit.customIcon" // "Icon" case title = "place.edit.title" // "New place" case unnamedPlace = "place.edit.unnamed.title" // "Unnamed place" } enum PhotoViewer: String, Localizable { case nextLong = "photoViewer.next.long" case previousLong = "photoViewer.previous.long" case nextShort = "photoViewer.next.short" case previousShort = "photoViewer.previous.short" static var next: PhotoViewer { UIDevice.current.isPhone ? .nextShort : .nextLong } static var previous: PhotoViewer { UIDevice.current.isPhone ? .previousShort : .previousLong } } enum ChecklistsList: String, Localizable { case searchPlaceholder = "checklists.list.searchPlaceholder" // "Search for checklists..." case listTitle = "checklists.list.title" // "Checklists" case addItemsButton = "checklists.list.addItems.button" // "Add items..." case shouldDeleteChecklist = "checklists.list.shouldDeleteChecklist" // "Delete \(item.title)?" case addChecklistButton = "checklists.list.addChecklist.button" // "Add checklist" case assignItemsToTitle = "checklists.list.assignItemsTo.title" // "Add items to case filterItemsPlaceholder = "checklists.list.filterItems.placeholder" // "Filter items..." case menu = "checklists.list.menu" enum Sort: String, Localizable { case byTitle = "checklists.list.sort.byTitle" case byLastModified = "checklists.list.sort.byLastModified" case byEntriesCount = "checklists.list.sort.byEntriesCount" } } enum ChecklistWelcome: String, Localizable { case chooseExisting = "checklist.welcome.chooseExisting" // "Choose existing checklist" case orLabel = "checklist.welcome.or.label" case createNewButton = "checklist.welcome.createNew.button" // "Add new" } enum EditChecklist: String, Localizable { case titlePlaceholder = "checklist.edit.title.placeholder" // "New checklist title" case titleSectionTitle = "checklist.edit.title.section.title" // "Title" case customIcon = "checklist.edit.customIcon" // "Icon" case title = "checklist.edit.title" // "New checklist" case unnamedChecklist = "checklist.edit.unnamed.title" // "Unnamed checklist" } enum NewChecklistEnty: String, Localizable { case titlePlaceholder = "checklist.entry.new.title.placeholder" // "Title" case titleSectionTitle = "checklist.entry.new.title.section.title" // "Title" case suggestedItemsSectionTitle = "checklist.entry.new.suggestedItems.section.title" // "Suggested items" case customIcon = "checklist.entry.new.customIcon" // "Icon" case title = "checklist.entry.new.title" // "Entry" } enum ChecklistDetails: String, Localizable { case checklistNoLongerAvailable = "checklist.details.noLongerAvailable" // "Checklist is no longer available" case checklistIsEmpty = "checklist.details.isEmpty" // "Checklist is empty" case itemDetailsButton = "checklist.details.itemDetails.button" // "Item details..." case markAsUnchecked = "checklist.details.markAsUnchecked" // "Mark as unchecked" case markAsChecked = "checklist.details.markAsChecked" // "Mark as checked" case sectionPending = "checklist.details.section.pending" // "Pending" case sectionChecked = "checklist.details.section.checked" // "Checked" case addEntryButton = "checklist.details.addEntry.button" // "Add entry" } enum Preferences: String, Localizable { case title = "preferences.title" // "Preferences" case exportImportTitle = "preferences.exportImport.title" // "Export and import" case exportTitle = "preferences.export.title" // "Export" case importTitle = "preferences.import.title" // "Import" case exportButtonTitle = "preferences.exportButton.title" // "Export..." case importButtonTitle = "preferences.importButton.title" // "Import..." case exportAction = "preferences.export.action" // "Export data for backup" case importAction = "preferences.import.action" // "Import previously exported data" case importingData = "preferences.importingData" // "Importing data..." case exportingData = "preferences.exportingData" // "Exporting data..." case importSuccessTitle = "preferences.import.success.title" case importSuccessDetails = "preferences.import.success.details" case importFailureTitle = "preferences.import.failure.title" case importFailureDetails = "preferences.import.failure.details" case exportFailureTitle = "preferences.export.failure.title" case exportFailureDetails = "preferences.export.failure.details" case versionFormat = "preferences.versionFormat" case managePINTitle = "preferences.manage.pin.title" case managePINMessage = "preferences.manage.pin.message" case managePINButtonSet = "preferences.manage.pin.button.set" case managePINButtonClear = "preferences.manage.pin.button.clear" case managePINButtonChange = "preferences.manage.pin.button.change" case managePasswordTitle = "preferences.manage.password.title" case managePasswordMessage = "preferences.manage.password.message" case managePasswordButton = "preferences.manage.password.button" } enum PINProtection: String, Localizable { case passwordPlaceholder = "pin.protection.password.placeholder" } enum ManagePassword: String, Localizable { case title = "manage.password.title" case existingPasswordPlaceholder = "manage.password.existingPassword.placeholder" case existingPasswordTitle = "manage.password.existingPassword.title" case password1Placeholder = "manage.password.password1.placeholder" case password2Placeholder = "manage.password.password2.placeholder" case newPasswordTitle = "manage.password.newPassword.title" case clearPasswordButton = "manage.password.clearPassword.button" case setPasswordButton = "manage.password.setPassword.button" case changePasswordButton = "manage.password.changePassword.button" case genericError = "manage.password.generic.error" case genericSuccess = "manage.password.generic.success" enum PasswordRemoved: String, Localizable { case title = "manage.password.passwordRemoved.title" // "Password is removed" case message = "manage.password.passwordRemoved.message" // "App is no longer protected with password." } enum IncorrectPassword: String, Localizable { case title = "manage.password.incorrectPassword.title" // "Password doesn't match" case message = "manage.password.incorrectPassword.message" // "Existing password is entered incorrectly." } enum EmptyPassword: String, Localizable { case title = "manage.password.emptyPassword.title" // "Incorrect password" case message = "manage.password.emptyPassword.message" // "Password should not be empty." } enum PasswordsDontMatch: String, Localizable { case title = "manage.password.passwordsDontMatch.title" // "Passwords doesn't match" case message = "manage.password.passwordsDontMatch.message" // "New passwords do not match." } enum PasswordChanged: String, Localizable { case title = "manage.password.passwordChanged.title" // "Password is changed" case message = "manage.password.passwordChanged.message" // "New password is now used to protect the app data." } enum PasswordSet: String, Localizable { case title = "manage.password.passwordSet.title" // "Password is set" case message = "manage.password.passwordSet.message" // "Password is now used to protect the app data." } enum InconsistencyError: String, Localizable { case title = "manage.password.inconsistencyError.title" // "Password error" case message = "manage.password.inconsistencyError.message" // "Internal inconsistency with passwords. Try closing the app and opening again." } } }
53.961977
154
0.678481
bf9422c22d0258de2a85e97f547e88837544973b
1,413
// // UIDevice+HomeIndicator.swift // TLCommon // // Created by Charles on 2018/9/19. // Copyright © 2018 Charles. All rights reserved. // import UIKit extension UIDevice { public static var haveHomeIndicator : Bool { get { var isHave = false if #available(iOS 11.0, *) { // 11 以下的系统 没有刘海 从 iOS11开始有刘海 print("safeAreaInsets", UIApplication.shared.windows.first?.safeAreaInsets ?? UIEdgeInsets.zero) isHave = UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0 > 0 } return isHave } } /// 状态栏高度 - 顶部安全距离就是状态栏高度 public static var statusBarHeight: CGFloat { if #available(iOS 11.0, *) { return UIApplication.shared.windows.first?.safeAreaInsets.top ?? 20 } return 20 } // public static var isIphoneX : Bool { // return UIScreen.main.bounds.size == CGSize(width: 375, height: 812) // } // // public static var isIphoneXS : Bool { // return UIScreen.main.bounds.size == CGSize(width: 375, height: 812) // } // // public static var isIphoneXR : Bool { // return UIScreen.main.bounds.size == CGSize(width: 414, height: 896) // } // // public static var isIphoneXSMax : Bool { // return UIScreen.main.bounds.size == CGSize(width: 414, height: 896) // } }
27.705882
112
0.583864
62ed39b621f0261cb641ee9d8d289a2fc4598607
36,958
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. import Foundation import SotoCore extension Polly { // MARK: Enums public enum Engine: String, CustomStringConvertible, Codable, _SotoSendable { case neural case standard public var description: String { return self.rawValue } } public enum Gender: String, CustomStringConvertible, Codable, _SotoSendable { case female = "Female" case male = "Male" public var description: String { return self.rawValue } } public enum LanguageCode: String, CustomStringConvertible, Codable, _SotoSendable { case arb case caES = "ca-ES" case cmnCN = "cmn-CN" case cyGB = "cy-GB" case daDK = "da-DK" case deAT = "de-AT" case deDE = "de-DE" case enAU = "en-AU" case enGB = "en-GB" case enGBWLS = "en-GB-WLS" case enIN = "en-IN" case enNZ = "en-NZ" case enUS = "en-US" case enZA = "en-ZA" case esES = "es-ES" case esMX = "es-MX" case esUS = "es-US" case frCA = "fr-CA" case frFR = "fr-FR" case hiIN = "hi-IN" case isIS = "is-IS" case itIT = "it-IT" case jaJP = "ja-JP" case koKR = "ko-KR" case nbNO = "nb-NO" case nlNL = "nl-NL" case plPL = "pl-PL" case ptBR = "pt-BR" case ptPT = "pt-PT" case roRO = "ro-RO" case ruRU = "ru-RU" case svSE = "sv-SE" case trTR = "tr-TR" public var description: String { return self.rawValue } } public enum OutputFormat: String, CustomStringConvertible, Codable, _SotoSendable { case json case mp3 case oggVorbis = "ogg_vorbis" case pcm public var description: String { return self.rawValue } } public enum SpeechMarkType: String, CustomStringConvertible, Codable, _SotoSendable { case sentence case ssml case viseme case word public var description: String { return self.rawValue } } public enum TaskStatus: String, CustomStringConvertible, Codable, _SotoSendable { case completed case failed case inProgress case scheduled public var description: String { return self.rawValue } } public enum TextType: String, CustomStringConvertible, Codable, _SotoSendable { case ssml case text public var description: String { return self.rawValue } } public enum VoiceId: String, CustomStringConvertible, Codable, _SotoSendable { case aditi = "Aditi" case amy = "Amy" case aria = "Aria" case arlet = "Arlet" case astrid = "Astrid" case ayanda = "Ayanda" case bianca = "Bianca" case brian = "Brian" case camila = "Camila" case carla = "Carla" case carmen = "Carmen" case celine = "Celine" case chantal = "Chantal" case conchita = "Conchita" case cristiano = "Cristiano" case dora = "Dora" case emma = "Emma" case enrique = "Enrique" case ewa = "Ewa" case filiz = "Filiz" case gabrielle = "Gabrielle" case geraint = "Geraint" case giorgio = "Giorgio" case gwyneth = "Gwyneth" case hannah = "Hannah" case hans = "Hans" case ines = "Ines" case ivy = "Ivy" case jacek = "Jacek" case jan = "Jan" case joanna = "Joanna" case joey = "Joey" case justin = "Justin" case karl = "Karl" case kendra = "Kendra" case kevin = "Kevin" case kimberly = "Kimberly" case lea = "Lea" case liv = "Liv" case lotte = "Lotte" case lucia = "Lucia" case lupe = "Lupe" case mads = "Mads" case maja = "Maja" case marlene = "Marlene" case mathieu = "Mathieu" case matthew = "Matthew" case maxim = "Maxim" case mia = "Mia" case miguel = "Miguel" case mizuki = "Mizuki" case naja = "Naja" case nicole = "Nicole" case olivia = "Olivia" case penelope = "Penelope" case raveena = "Raveena" case ricardo = "Ricardo" case ruben = "Ruben" case russell = "Russell" case salli = "Salli" case seoyeon = "Seoyeon" case takumi = "Takumi" case tatyana = "Tatyana" case vicki = "Vicki" case vitoria = "Vitoria" case zeina = "Zeina" case zhiyu = "Zhiyu" public var description: String { return self.rawValue } } // MARK: Shapes public struct DeleteLexiconInput: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "name", location: .uri("Name")) ] /// The name of the lexicon to delete. Must be an existing lexicon in the region. public let name: String public init(name: String) { self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9A-Za-z]{1,20}$") } private enum CodingKeys: CodingKey {} } public struct DeleteLexiconOutput: AWSDecodableShape { public init() {} } public struct DescribeVoicesInput: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "engine", location: .querystring("Engine")), AWSMemberEncoding(label: "includeAdditionalLanguageCodes", location: .querystring("IncludeAdditionalLanguageCodes")), AWSMemberEncoding(label: "languageCode", location: .querystring("LanguageCode")), AWSMemberEncoding(label: "nextToken", location: .querystring("NextToken")) ] /// Specifies the engine (standard or neural) used by Amazon Polly when processing input text for speech synthesis. public let engine: Engine? /// Boolean value indicating whether to return any bilingual voices that use the specified language as an additional language. For instance, if you request all languages that use US English (es-US), and there is an Italian voice that speaks both Italian (it-IT) and US English, that voice will be included if you specify yes but not if you specify no. public let includeAdditionalLanguageCodes: Bool? /// The language identification tag (ISO 639 code for the language name-ISO 3166 country code) for filtering the list of voices returned. If you don't specify this optional parameter, all available voices are returned. public let languageCode: LanguageCode? /// An opaque pagination token returned from the previous DescribeVoices operation. If present, this indicates where to continue the listing. public let nextToken: String? public init(engine: Engine? = nil, includeAdditionalLanguageCodes: Bool? = nil, languageCode: LanguageCode? = nil, nextToken: String? = nil) { self.engine = engine self.includeAdditionalLanguageCodes = includeAdditionalLanguageCodes self.languageCode = languageCode self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.nextToken, name: "nextToken", parent: name, max: 4096) } private enum CodingKeys: CodingKey {} } public struct DescribeVoicesOutput: AWSDecodableShape { /// The pagination token to use in the next request to continue the listing of voices. NextToken is returned only if the response is truncated. public let nextToken: String? /// A list of voices with their properties. public let voices: [Voice]? public init(nextToken: String? = nil, voices: [Voice]? = nil) { self.nextToken = nextToken self.voices = voices } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case voices = "Voices" } } public struct GetLexiconInput: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "name", location: .uri("Name")) ] /// Name of the lexicon. public let name: String public init(name: String) { self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9A-Za-z]{1,20}$") } private enum CodingKeys: CodingKey {} } public struct GetLexiconOutput: AWSDecodableShape { /// Lexicon object that provides name and the string content of the lexicon. public let lexicon: Lexicon? /// Metadata of the lexicon, including phonetic alphabetic used, language code, lexicon ARN, number of lexemes defined in the lexicon, and size of lexicon in bytes. public let lexiconAttributes: LexiconAttributes? public init(lexicon: Lexicon? = nil, lexiconAttributes: LexiconAttributes? = nil) { self.lexicon = lexicon self.lexiconAttributes = lexiconAttributes } private enum CodingKeys: String, CodingKey { case lexicon = "Lexicon" case lexiconAttributes = "LexiconAttributes" } } public struct GetSpeechSynthesisTaskInput: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "taskId", location: .uri("TaskId")) ] /// The Amazon Polly generated identifier for a speech synthesis task. public let taskId: String public init(taskId: String) { self.taskId = taskId } public func validate(name: String) throws { try self.validate(self.taskId, name: "taskId", parent: name, pattern: "^[a-zA-Z0-9_-]{1,100}$") } private enum CodingKeys: CodingKey {} } public struct GetSpeechSynthesisTaskOutput: AWSDecodableShape { /// SynthesisTask object that provides information from the requested task, including output format, creation time, task status, and so on. public let synthesisTask: SynthesisTask? public init(synthesisTask: SynthesisTask? = nil) { self.synthesisTask = synthesisTask } private enum CodingKeys: String, CodingKey { case synthesisTask = "SynthesisTask" } } public struct Lexicon: AWSDecodableShape { /// Lexicon content in string format. The content of a lexicon must be in PLS format. public let content: String? /// Name of the lexicon. public let name: String? public init(content: String? = nil, name: String? = nil) { self.content = content self.name = name } private enum CodingKeys: String, CodingKey { case content = "Content" case name = "Name" } } public struct LexiconAttributes: AWSDecodableShape { /// Phonetic alphabet used in the lexicon. Valid values are ipa and x-sampa. public let alphabet: String? /// Language code that the lexicon applies to. A lexicon with a language code such as "en" would be applied to all English languages (en-GB, en-US, en-AUS, en-WLS, and so on. public let languageCode: LanguageCode? /// Date lexicon was last modified (a timestamp value). public let lastModified: Date? /// Number of lexemes in the lexicon. public let lexemesCount: Int? /// Amazon Resource Name (ARN) of the lexicon. public let lexiconArn: String? /// Total size of the lexicon, in characters. public let size: Int? public init(alphabet: String? = nil, languageCode: LanguageCode? = nil, lastModified: Date? = nil, lexemesCount: Int? = nil, lexiconArn: String? = nil, size: Int? = nil) { self.alphabet = alphabet self.languageCode = languageCode self.lastModified = lastModified self.lexemesCount = lexemesCount self.lexiconArn = lexiconArn self.size = size } private enum CodingKeys: String, CodingKey { case alphabet = "Alphabet" case languageCode = "LanguageCode" case lastModified = "LastModified" case lexemesCount = "LexemesCount" case lexiconArn = "LexiconArn" case size = "Size" } } public struct LexiconDescription: AWSDecodableShape { /// Provides lexicon metadata. public let attributes: LexiconAttributes? /// Name of the lexicon. public let name: String? public init(attributes: LexiconAttributes? = nil, name: String? = nil) { self.attributes = attributes self.name = name } private enum CodingKeys: String, CodingKey { case attributes = "Attributes" case name = "Name" } } public struct ListLexiconsInput: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "nextToken", location: .querystring("NextToken")) ] /// An opaque pagination token returned from previous ListLexicons operation. If present, indicates where to continue the list of lexicons. public let nextToken: String? public init(nextToken: String? = nil) { self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.nextToken, name: "nextToken", parent: name, max: 4096) } private enum CodingKeys: CodingKey {} } public struct ListLexiconsOutput: AWSDecodableShape { /// A list of lexicon names and attributes. public let lexicons: [LexiconDescription]? /// The pagination token to use in the next request to continue the listing of lexicons. NextToken is returned only if the response is truncated. public let nextToken: String? public init(lexicons: [LexiconDescription]? = nil, nextToken: String? = nil) { self.lexicons = lexicons self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case lexicons = "Lexicons" case nextToken = "NextToken" } } public struct ListSpeechSynthesisTasksInput: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring("MaxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring("NextToken")), AWSMemberEncoding(label: "status", location: .querystring("Status")) ] /// Maximum number of speech synthesis tasks returned in a List operation. public let maxResults: Int? /// The pagination token to use in the next request to continue the listing of speech synthesis tasks. public let nextToken: String? /// Status of the speech synthesis tasks returned in a List operation public let status: TaskStatus? public init(maxResults: Int? = nil, nextToken: String? = nil, status: TaskStatus? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.status = status } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 4096) } private enum CodingKeys: CodingKey {} } public struct ListSpeechSynthesisTasksOutput: AWSDecodableShape { /// An opaque pagination token returned from the previous List operation in this request. If present, this indicates where to continue the listing. public let nextToken: String? /// List of SynthesisTask objects that provides information from the specified task in the list request, including output format, creation time, task status, and so on. public let synthesisTasks: [SynthesisTask]? public init(nextToken: String? = nil, synthesisTasks: [SynthesisTask]? = nil) { self.nextToken = nextToken self.synthesisTasks = synthesisTasks } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case synthesisTasks = "SynthesisTasks" } } public struct PutLexiconInput: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "name", location: .uri("Name")) ] /// Content of the PLS lexicon as string data. public let content: String /// Name of the lexicon. The name must follow the regular express format [0-9A-Za-z]{1,20}. That is, the name is a case-sensitive alphanumeric string up to 20 characters long. public let name: String public init(content: String, name: String) { self.content = content self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9A-Za-z]{1,20}$") } private enum CodingKeys: String, CodingKey { case content = "Content" } } public struct PutLexiconOutput: AWSDecodableShape { public init() {} } public struct StartSpeechSynthesisTaskInput: AWSEncodableShape { /// Specifies the engine (standard or neural) for Amazon Polly to use when processing input text for speech synthesis. Using a voice that is not supported for the engine selected will result in an error. public let engine: Engine? /// Optional language code for the Speech Synthesis request. This is only necessary if using a bilingual voice, such as Aditi, which can be used for either Indian English (en-IN) or Hindi (hi-IN). If a bilingual voice is used and no language code is specified, Amazon Polly uses the default language of the bilingual voice. The default language for any voice is the one returned by the DescribeVoices operation for the LanguageCode parameter. For example, if no language code is specified, Aditi will use Indian English rather than Hindi. public let languageCode: LanguageCode? /// List of one or more pronunciation lexicon names you want the service to apply during synthesis. Lexicons are applied only if the language of the lexicon is the same as the language of the voice. public let lexiconNames: [String]? /// The format in which the returned output will be encoded. For audio stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will be json. public let outputFormat: OutputFormat /// Amazon S3 bucket name to which the output file will be saved. public let outputS3BucketName: String /// The Amazon S3 key prefix for the output speech file. public let outputS3KeyPrefix: String? /// The audio frequency specified in Hz. The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and "24000". The default value for standard voices is "22050". The default value for neural voices is "24000". Valid values for pcm are "8000" and "16000" The default value is "16000". public let sampleRate: String? /// ARN for the SNS topic optionally used for providing status notification for a speech synthesis task. public let snsTopicArn: String? /// The type of speech marks returned for the input text. public let speechMarkTypes: [SpeechMarkType]? /// The input text to synthesize. If you specify ssml as the TextType, follow the SSML format for the input text. public let text: String /// Specifies whether the input text is plain text or SSML. The default value is plain text. public let textType: TextType? /// Voice ID to use for the synthesis. public let voiceId: VoiceId public init(engine: Engine? = nil, languageCode: LanguageCode? = nil, lexiconNames: [String]? = nil, outputFormat: OutputFormat, outputS3BucketName: String, outputS3KeyPrefix: String? = nil, sampleRate: String? = nil, snsTopicArn: String? = nil, speechMarkTypes: [SpeechMarkType]? = nil, text: String, textType: TextType? = nil, voiceId: VoiceId) { self.engine = engine self.languageCode = languageCode self.lexiconNames = lexiconNames self.outputFormat = outputFormat self.outputS3BucketName = outputS3BucketName self.outputS3KeyPrefix = outputS3KeyPrefix self.sampleRate = sampleRate self.snsTopicArn = snsTopicArn self.speechMarkTypes = speechMarkTypes self.text = text self.textType = textType self.voiceId = voiceId } public func validate(name: String) throws { try self.lexiconNames?.forEach { try validate($0, name: "lexiconNames[]", parent: name, pattern: "^[0-9A-Za-z]{1,20}$") } try self.validate(self.lexiconNames, name: "lexiconNames", parent: name, max: 5) try self.validate(self.outputS3BucketName, name: "outputS3BucketName", parent: name, pattern: "^[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]$") try self.validate(self.outputS3KeyPrefix, name: "outputS3KeyPrefix", parent: name, pattern: "^[0-9a-zA-Z\\/\\!\\-_\\.\\*\\'\\(\\):;\\$@=+\\,\\?&]{0,800}$") try self.validate(self.snsTopicArn, name: "snsTopicArn", parent: name, pattern: "^arn:aws(-(cn|iso(-b)?|us-gov))?:sns:[a-z0-9_-]{1,50}:\\d{12}:[a-zA-Z0-9_-]{1,256}$") try self.validate(self.speechMarkTypes, name: "speechMarkTypes", parent: name, max: 4) } private enum CodingKeys: String, CodingKey { case engine = "Engine" case languageCode = "LanguageCode" case lexiconNames = "LexiconNames" case outputFormat = "OutputFormat" case outputS3BucketName = "OutputS3BucketName" case outputS3KeyPrefix = "OutputS3KeyPrefix" case sampleRate = "SampleRate" case snsTopicArn = "SnsTopicArn" case speechMarkTypes = "SpeechMarkTypes" case text = "Text" case textType = "TextType" case voiceId = "VoiceId" } } public struct StartSpeechSynthesisTaskOutput: AWSDecodableShape { /// SynthesisTask object that provides information and attributes about a newly submitted speech synthesis task. public let synthesisTask: SynthesisTask? public init(synthesisTask: SynthesisTask? = nil) { self.synthesisTask = synthesisTask } private enum CodingKeys: String, CodingKey { case synthesisTask = "SynthesisTask" } } public struct SynthesisTask: AWSDecodableShape { /// Timestamp for the time the synthesis task was started. public let creationTime: Date? /// Specifies the engine (standard or neural) for Amazon Polly to use when processing input text for speech synthesis. Using a voice that is not supported for the engine selected will result in an error. public let engine: Engine? /// Optional language code for a synthesis task. This is only necessary if using a bilingual voice, such as Aditi, which can be used for either Indian English (en-IN) or Hindi (hi-IN). If a bilingual voice is used and no language code is specified, Amazon Polly uses the default language of the bilingual voice. The default language for any voice is the one returned by the DescribeVoices operation for the LanguageCode parameter. For example, if no language code is specified, Aditi will use Indian English rather than Hindi. public let languageCode: LanguageCode? /// List of one or more pronunciation lexicon names you want the service to apply during synthesis. Lexicons are applied only if the language of the lexicon is the same as the language of the voice. public let lexiconNames: [String]? /// The format in which the returned output will be encoded. For audio stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will be json. public let outputFormat: OutputFormat? /// Pathway for the output speech file. public let outputUri: String? /// Number of billable characters synthesized. public let requestCharacters: Int? /// The audio frequency specified in Hz. The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and "24000". The default value for standard voices is "22050". The default value for neural voices is "24000". Valid values for pcm are "8000" and "16000" The default value is "16000". public let sampleRate: String? /// ARN for the SNS topic optionally used for providing status notification for a speech synthesis task. public let snsTopicArn: String? /// The type of speech marks returned for the input text. public let speechMarkTypes: [SpeechMarkType]? /// The Amazon Polly generated identifier for a speech synthesis task. public let taskId: String? /// Current status of the individual speech synthesis task. public let taskStatus: TaskStatus? /// Reason for the current status of a specific speech synthesis task, including errors if the task has failed. public let taskStatusReason: String? /// Specifies whether the input text is plain text or SSML. The default value is plain text. public let textType: TextType? /// Voice ID to use for the synthesis. public let voiceId: VoiceId? public init(creationTime: Date? = nil, engine: Engine? = nil, languageCode: LanguageCode? = nil, lexiconNames: [String]? = nil, outputFormat: OutputFormat? = nil, outputUri: String? = nil, requestCharacters: Int? = nil, sampleRate: String? = nil, snsTopicArn: String? = nil, speechMarkTypes: [SpeechMarkType]? = nil, taskId: String? = nil, taskStatus: TaskStatus? = nil, taskStatusReason: String? = nil, textType: TextType? = nil, voiceId: VoiceId? = nil) { self.creationTime = creationTime self.engine = engine self.languageCode = languageCode self.lexiconNames = lexiconNames self.outputFormat = outputFormat self.outputUri = outputUri self.requestCharacters = requestCharacters self.sampleRate = sampleRate self.snsTopicArn = snsTopicArn self.speechMarkTypes = speechMarkTypes self.taskId = taskId self.taskStatus = taskStatus self.taskStatusReason = taskStatusReason self.textType = textType self.voiceId = voiceId } private enum CodingKeys: String, CodingKey { case creationTime = "CreationTime" case engine = "Engine" case languageCode = "LanguageCode" case lexiconNames = "LexiconNames" case outputFormat = "OutputFormat" case outputUri = "OutputUri" case requestCharacters = "RequestCharacters" case sampleRate = "SampleRate" case snsTopicArn = "SnsTopicArn" case speechMarkTypes = "SpeechMarkTypes" case taskId = "TaskId" case taskStatus = "TaskStatus" case taskStatusReason = "TaskStatusReason" case textType = "TextType" case voiceId = "VoiceId" } } public struct SynthesizeSpeechInput: AWSEncodableShape { /// Specifies the engine (standard or neural) for Amazon Polly to use when processing input text for speech synthesis. For information on Amazon Polly voices and which voices are available in standard-only, NTTS-only, and both standard and NTTS formats, see Available Voices. NTTS-only voices When using NTTS-only voices such as Kevin (en-US), this parameter is required and must be set to neural. If the engine is not specified, or is set to standard, this will result in an error. Type: String Valid Values: standard | neural Required: Yes /// Standard voices For standard voices, this is not required; the engine parameter defaults to standard. If the engine is not specified, or is set to standard and an NTTS-only voice is selected, this will result in an error. public let engine: Engine? /// Optional language code for the Synthesize Speech request. This is only necessary if using a bilingual voice, such as Aditi, which can be used for either Indian English (en-IN) or Hindi (hi-IN). If a bilingual voice is used and no language code is specified, Amazon Polly uses the default language of the bilingual voice. The default language for any voice is the one returned by the DescribeVoices operation for the LanguageCode parameter. For example, if no language code is specified, Aditi will use Indian English rather than Hindi. public let languageCode: LanguageCode? /// List of one or more pronunciation lexicon names you want the service to apply during synthesis. Lexicons are applied only if the language of the lexicon is the same as the language of the voice. For information about storing lexicons, see PutLexicon. public let lexiconNames: [String]? /// The format in which the returned output will be encoded. For audio stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will be json. When pcm is used, the content returned is audio/pcm in a signed 16-bit, 1 channel (mono), little-endian format. public let outputFormat: OutputFormat /// The audio frequency specified in Hz. The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and "24000". The default value for standard voices is "22050". The default value for neural voices is "24000". Valid values for pcm are "8000" and "16000" The default value is "16000". public let sampleRate: String? /// The type of speech marks returned for the input text. public let speechMarkTypes: [SpeechMarkType]? /// Input text to synthesize. If you specify ssml as the TextType, follow the SSML format for the input text. public let text: String /// Specifies whether the input text is plain text or SSML. The default value is plain text. For more information, see Using SSML. public let textType: TextType? /// Voice ID to use for the synthesis. You can get a list of available voice IDs by calling the DescribeVoices operation. public let voiceId: VoiceId public init(engine: Engine? = nil, languageCode: LanguageCode? = nil, lexiconNames: [String]? = nil, outputFormat: OutputFormat, sampleRate: String? = nil, speechMarkTypes: [SpeechMarkType]? = nil, text: String, textType: TextType? = nil, voiceId: VoiceId) { self.engine = engine self.languageCode = languageCode self.lexiconNames = lexiconNames self.outputFormat = outputFormat self.sampleRate = sampleRate self.speechMarkTypes = speechMarkTypes self.text = text self.textType = textType self.voiceId = voiceId } public func validate(name: String) throws { try self.lexiconNames?.forEach { try validate($0, name: "lexiconNames[]", parent: name, pattern: "^[0-9A-Za-z]{1,20}$") } try self.validate(self.lexiconNames, name: "lexiconNames", parent: name, max: 5) try self.validate(self.speechMarkTypes, name: "speechMarkTypes", parent: name, max: 4) } private enum CodingKeys: String, CodingKey { case engine = "Engine" case languageCode = "LanguageCode" case lexiconNames = "LexiconNames" case outputFormat = "OutputFormat" case sampleRate = "SampleRate" case speechMarkTypes = "SpeechMarkTypes" case text = "Text" case textType = "TextType" case voiceId = "VoiceId" } } public struct SynthesizeSpeechOutput: AWSDecodableShape & AWSShapeWithPayload { /// The key for the payload public static let _payloadPath: String = "audioStream" public static let _options: AWSShapeOptions = [.rawPayload, .allowStreaming] public static var _encoding = [ AWSMemberEncoding(label: "audioStream", location: .body("AudioStream")), AWSMemberEncoding(label: "contentType", location: .header("Content-Type")), AWSMemberEncoding(label: "requestCharacters", location: .header("x-amzn-RequestCharacters")) ] /// Stream containing the synthesized speech. public let audioStream: AWSPayload? /// Specifies the type audio stream. This should reflect the OutputFormat parameter in your request. If you request mp3 as the OutputFormat, the ContentType returned is audio/mpeg. If you request ogg_vorbis as the OutputFormat, the ContentType returned is audio/ogg. If you request pcm as the OutputFormat, the ContentType returned is audio/pcm in a signed 16-bit, 1 channel (mono), little-endian format. If you request json as the OutputFormat, the ContentType returned is application/x-json-stream. public let contentType: String? /// Number of characters synthesized. public let requestCharacters: Int? public init(audioStream: AWSPayload? = nil, contentType: String? = nil, requestCharacters: Int? = nil) { self.audioStream = audioStream self.contentType = contentType self.requestCharacters = requestCharacters } private enum CodingKeys: String, CodingKey { case audioStream = "AudioStream" case contentType = "Content-Type" case requestCharacters = "x-amzn-RequestCharacters" } } public struct Voice: AWSDecodableShape { /// Additional codes for languages available for the specified voice in addition to its default language. For example, the default language for Aditi is Indian English (en-IN) because it was first used for that language. Since Aditi is bilingual and fluent in both Indian English and Hindi, this parameter would show the code hi-IN. public let additionalLanguageCodes: [LanguageCode]? /// Gender of the voice. public let gender: Gender? /// Amazon Polly assigned voice ID. This is the ID that you specify when calling the SynthesizeSpeech operation. public let id: VoiceId? /// Language code of the voice. public let languageCode: LanguageCode? /// Human readable name of the language in English. public let languageName: String? /// Name of the voice (for example, Salli, Kendra, etc.). This provides a human readable voice name that you might display in your application. public let name: String? /// Specifies which engines (standard or neural) that are supported by a given voice. public let supportedEngines: [Engine]? public init(additionalLanguageCodes: [LanguageCode]? = nil, gender: Gender? = nil, id: VoiceId? = nil, languageCode: LanguageCode? = nil, languageName: String? = nil, name: String? = nil, supportedEngines: [Engine]? = nil) { self.additionalLanguageCodes = additionalLanguageCodes self.gender = gender self.id = id self.languageCode = languageCode self.languageName = languageName self.name = name self.supportedEngines = supportedEngines } private enum CodingKeys: String, CodingKey { case additionalLanguageCodes = "AdditionalLanguageCodes" case gender = "Gender" case id = "Id" case languageCode = "LanguageCode" case languageName = "LanguageName" case name = "Name" case supportedEngines = "SupportedEngines" } } }
48.437746
553
0.64365
e45f863215574b7cfe2cd59c55a0f521cf37f0e7
2,221
// // AppDelegate.swift // KontaktBeaconSample // // Created by Anthony Arzola on 9/9/17. // Copyright © 2017 Anthony Arzola. All rights reserved. // import UIKit import KontaktSDK @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.270833
285
0.752364
0a339ef88ca70d4d42cff54cddb8089279d99f56
307
// // Cons.swift // CatLive // // Created by qianjn on 2017/6/11. // Copyright © 2017年 SF. All rights reserved. // // 此文件用来定义全局常量-宏 import UIKit let kScreenW = UIScreen.main.bounds.width let kScreenH = UIScreen.main.bounds.height let kNavigationBarH : CGFloat = 44 let kStatusBarH : CGFloat = 20
15.35
46
0.700326
29c7987ffac1867e7465b26238f084dca5915e66
8,535
// // YLPhotoCell.swift // YLPhotoBrowser // // Created by yl on 2017/7/27. // Copyright © 2017年 February12. All rights reserved. // import UIKit import Photos protocol YLPhotoCellDelegate :NSObjectProtocol { func epPhotoPanGestureRecognizerBegin(_ pan: UIPanGestureRecognizer,photo: YLPhoto) func epPhotoPanGestureRecognizerEnd(_ currentImageViewFrame: CGRect,photo: YLPhoto) func epPhotoSingleTap() func epPhotoDoubleTap() } class YLPhotoCell: UICollectionViewCell { var panGestureRecognizer: UIPanGestureRecognizer! var transitionImageViewFrame = CGRect.zero var panBeginScaleX:CGFloat = 0 var panBeginScaleY:CGFloat = 0 weak var delegate: YLPhotoCellDelegate? var photo: YLPhoto! let scrollView: UIScrollView = { let sv = UIScrollView(frame: CGRect.zero) sv.showsHorizontalScrollIndicator = false sv.showsVerticalScrollIndicator = false sv.bounces = false sv.maximumZoomScale = 4.0 sv.minimumZoomScale = 1.0 if #available(iOS 11.0, *) { sv.contentInsetAdjustmentBehavior = .never } return sv }() // 图片容器 let imageView: UIImageView = { let imgView = UIImageView() imgView.backgroundColor = UIColor.clear imgView.tag = ImageViewTag imgView.contentMode = UIViewContentMode.scaleAspectFit return imgView }() deinit { delegate = nil } override init(frame: CGRect) { super.init(frame: frame) layoutUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func layoutUI() { backgroundColor = UIColor.clear panGestureRecognizer = UIPanGestureRecognizer.init(target: self, action: #selector(YLPhotoCell.pan(_:))) panGestureRecognizer.delegate = self scrollView.addGestureRecognizer(panGestureRecognizer) scrollView.delegate = self addSubview(scrollView) // scrollView 约束 scrollView.addConstraints(toItem: self, edgeInsets: .init(top: 0, left: 0, bottom: 0, right: 0)) scrollView.addSubview(imageView) // 手势 let singleTap = UITapGestureRecognizer.init(target: self, action: #selector(YLPhotoCell.singleTap)) self.addGestureRecognizer(singleTap) let doubleTap = UITapGestureRecognizer.init(target: self, action: #selector(YLPhotoCell.doubleTap)) doubleTap.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTap) // 优先识别 双击 singleTap.require(toFail: doubleTap) } /// 单击手势 @objc func singleTap() { delegate?.epPhotoSingleTap() } /// 双击手势 @objc func doubleTap() { delegate?.epPhotoDoubleTap() } // 慢移手势 @objc func pan(_ pan: UIPanGestureRecognizer) { let translation = pan.translation(in: pan.view?.superview) var scale = 1 - translation.y / frame.height scale = scale > 1 ? 1:scale scale = scale < 0 ? 0:scale switch pan.state { case .possible: break case .began: transitionImageViewFrame = imageView.frame panBeginScaleX = pan.location(in: pan.view).x / transitionImageViewFrame.width panBeginScaleY = pan.location(in: imageView).y / imageView.frame.height scrollView.delegate = nil if panBeginScaleX < 0 { panBeginScaleX = 0 }else if panBeginScaleX > 1 { panBeginScaleX = 1 } if panBeginScaleY < 0 { panBeginScaleY = 0 }else if panBeginScaleY > 1 { panBeginScaleY = 1 } delegate?.epPhotoPanGestureRecognizerBegin(pan,photo: self.photo) break case .changed: imageView.frame.size = CGSize.init(width: transitionImageViewFrame.size.width * scale, height: transitionImageViewFrame.size.height * scale) var frame = imageView.frame frame.origin.x = transitionImageViewFrame.origin.x + (transitionImageViewFrame.size.width - imageView.frame.size.width ) * panBeginScaleX + translation.x frame.origin.y = transitionImageViewFrame.origin.y + (transitionImageViewFrame.size.height - imageView.frame.size.height ) * panBeginScaleY + translation.y imageView.frame = frame break case .failed,.cancelled,.ended: if translation.y <= 80 { UIView.animate(withDuration: 0.2, animations: { self.imageView.frame = self.transitionImageViewFrame }) scrollView.delegate = self }else { imageView.isHidden = true } delegate?.epPhotoPanGestureRecognizerEnd(imageView.frame,photo: self.photo) break } } func updatePhoto(_ photo: YLPhoto) { self.photo = photo scrollView.setZoomScale(1, animated: false) scrollView.contentOffset.y = 0 imageView.image = nil if let image = photo.image { imageView.frame = YLPhotoBrowser.getImageViewFrame(image.size) imageView.image = image } if photo.assetModel?.type == .gif { if let asset = photo.assetModel?.asset { let options = PHImageRequestOptions() options.resizeMode = PHImageRequestOptionsResizeMode.fast options.isSynchronous = true PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { [weak self] (data:Data?, dataUTI:String?, _, _) in if let data = data { self?.imageView.image = UIImage.yl_gifWithData(data) } }) } } scrollView.contentSize = imageView.frame.size } } extension YLPhotoCell: UIScrollViewDelegate { // 设置UIScrollView中要缩放的视图 func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } // 让UIImageView在UIScrollView缩放后居中显示 func scrollViewDidZoom(_ scrollView: UIScrollView) { let size = scrollView.bounds.size let offsetX = (size.width > scrollView.contentSize.width) ? (size.width - scrollView.contentSize.width) * 0.5 : 0.0 let offsetY = (size.height > scrollView.contentSize.height) ? (size.height - scrollView.contentSize.height) * 0.5 : 0.0 imageView.center = CGPoint.init(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY) } } // MARK: - UIGestureRecognizerDelegate extension YLPhotoCell: UIGestureRecognizerDelegate { func isScrollViewOnTopOrBottom(_ pan:UIPanGestureRecognizer) -> Bool { let translation = pan.translation(in: pan.view?.superview) if translation.y > 0 && scrollView.contentOffset.y <= 0 { return true } return false } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer is UIPanGestureRecognizer && gestureRecognizer.state == UIGestureRecognizerState.possible { if isScrollViewOnTopOrBottom(gestureRecognizer as! UIPanGestureRecognizer) { return true } } return false } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer.view == scrollView { return true } return false } }
31.036364
157
0.581371
3a85d3d7c8235fb1940a7a12594410f860d9c836
2,412
// // AppDelegate.swift // ZXLockView // // Created by admin on 28/02/2017. // Copyright © 2017 admin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "vc") window?.backgroundColor = UIColor.white window?.rootViewController = viewController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.509434
285
0.746683
0ab72ccf328ea2b5e64816ed975a1eda9f50f124
17,172
import XCTest @testable import SendKeysLib final class CommandIteratorTests: XCTestCase { func testParsesCharacters() throws { let commands = getCommands(CommandsIterator("abc")) XCTAssertEqual( commands, [ DefaultCommand(key: "a"), DefaultCommand(key: "b"), DefaultCommand(key: "c"), ]) } func testParsesKeyPress() throws { let commands = getCommands(CommandsIterator("<c:a>")) XCTAssertEqual( commands, [ KeyPressCommand(key: "a", modifiers: []) ]) } func testParsesKeyPressDelete() throws { let commands = getCommands(CommandsIterator("<c:delete>")) XCTAssertEqual( commands, [ KeyPressCommand(key: "delete", modifiers: []) ]) } func testParsesKeyPressesWithModifierKey() throws { let commands = getCommands(CommandsIterator("<c:a:command>")) XCTAssertEqual( commands, [ KeyPressCommand(key: "a", modifiers: ["command"]) ]) } func testParsesKeyPressesWithModifierKeys() throws { let commands = getCommands(CommandsIterator("<c:a:command,shift>")) XCTAssertEqual( commands, [ KeyPressCommand(key: "a", modifiers: ["command", "shift"]) ]) } func testParsesKeyPressAlias() throws { let commands = getCommands(CommandsIterator("<k:a>")) XCTAssertEqual( commands, [ KeyPressCommand(key: "a", modifiers: []) ]) } func testParsesKeyDown() throws { let commands = getCommands(CommandsIterator("<kd:a>")) XCTAssertEqual( commands, [ KeyDownCommand(key: "a", modifiers: []) ]) } func testParsesKeyDownWithModifierKey() throws { let commands = getCommands(CommandsIterator("<kd:a:shift>")) XCTAssertEqual( commands, [ KeyDownCommand(key: "a", modifiers: ["shift"]) ]) } func testParsesKeyDownAsModifierKey() throws { let commands = getCommands(CommandsIterator("<kd:shift>")) XCTAssertEqual( commands, [ KeyDownCommand(key: "shift", modifiers: []) ]) } func testParsesKeyUp() throws { let commands = getCommands(CommandsIterator("<ku:a>")) XCTAssertEqual( commands, [ KeyUpCommand(key: "a", modifiers: []) ]) } func testParsesKeyUpWithModifierKey() throws { let commands = getCommands(CommandsIterator("<ku:a:shift>")) XCTAssertEqual( commands, [ KeyUpCommand(key: "a", modifiers: ["shift"]) ]) } func testParsesKeyUpAsModifierKey() throws { let commands = getCommands(CommandsIterator("<ku:shift>")) XCTAssertEqual( commands, [ KeyUpCommand(key: "shift", modifiers: []) ]) } func testParsesNewLines() throws { let commands = getCommands(CommandsIterator("\n\n\n")) XCTAssertEqual( commands, [ NewlineCommand(), NewlineCommand(), NewlineCommand(), ]) } func testParsesNewLinesWithCarriageReturns() throws { let commands = getCommands(CommandsIterator("\r\n\r\n\n")) XCTAssertEqual( commands, [ NewlineCommand(), NewlineCommand(), NewlineCommand(), ]) } func testParsesMultipleKeyPresses() throws { let commands = getCommands(CommandsIterator("<c:a:command><c:c:command>")) XCTAssertEqual( commands, [ KeyPressCommand(key: "a", modifiers: ["command"]), KeyPressCommand(key: "c", modifiers: ["command"]), ]) } func testParsesContinuation() throws { let commands = getCommands(CommandsIterator("<\\>")) XCTAssertEqual( commands, [ ContinuationCommand() ]) } func testParsesPause() throws { let commands = getCommands(CommandsIterator("<p:0.2>")) XCTAssertEqual( commands, [ PauseCommand(duration: 0.2) ]) } func testParsesStickyPause() throws { let commands = getCommands(CommandsIterator("<P:0.2>")) XCTAssertEqual( commands, [ StickyPauseCommand(duration: 0.2) ]) } func testParsesMouseMove() throws { let commands = getCommands(CommandsIterator("<m:1.5,2.5,3.5,4.5>")) XCTAssertEqual( commands, [ MouseMoveCommand(x1: 1.5, y1: 2.5, x2: 3.5, y2: 4.5, duration: 0, modifiers: []) ]) } func testParsesMouseMoveWithModifier() throws { let commands = getCommands(CommandsIterator("<m:1,2,3,4:command>")) XCTAssertEqual( commands, [ MouseMoveCommand(x1: 1, y1: 2, x2: 3, y2: 4, duration: 0, modifiers: ["command"]) ]) } func testParsesMouseMoveWithDuration() throws { let commands = getCommands(CommandsIterator("<m:1,2,3,4:0.1>")) XCTAssertEqual( commands, [ MouseMoveCommand(x1: 1, y1: 2, x2: 3, y2: 4, duration: 0.1, modifiers: []) ]) } func testParsesMouseMoveWithNegativeCoordinates() throws { let commands = getCommands(CommandsIterator("<m:-1,-2,-3,-4:0.1>")) XCTAssertEqual( commands, [ MouseMoveCommand(x1: -1, y1: -2, x2: -3, y2: -4, duration: 0.1, modifiers: []) ]) } func testParsesMouseMoveWithDurationAndModifiers() throws { let commands = getCommands(CommandsIterator("<m:1,2,3,4:0.1:shift,command>")) XCTAssertEqual( commands, [ MouseMoveCommand(x1: 1, y1: 2, x2: 3, y2: 4, duration: 0.1, modifiers: ["shift", "command"]) ]) } func testParsesPartialMouseMove() throws { let commands = getCommands(CommandsIterator("<m:3,4>")) XCTAssertEqual( commands, [ MouseMoveCommand(x1: nil, y1: nil, x2: 3, y2: 4, duration: 0, modifiers: []) ]) } func testParsesPartialMouseMoveWithDuration() throws { let commands = getCommands(CommandsIterator("<m:3,4:2>")) XCTAssertEqual( commands, [ MouseMoveCommand(x1: nil, y1: nil, x2: 3, y2: 4, duration: 2, modifiers: []) ]) } func testParsesMouseClick() throws { let commands = getCommands(CommandsIterator("<m:left>")) XCTAssertEqual( commands, [ MouseClickCommand(button: "left", modifiers: [], clicks: 1) ]) } func testParsesMouseClickWithModifiers() throws { let commands = getCommands(CommandsIterator("<m:left:shift,command>")) XCTAssertEqual( commands, [ MouseClickCommand(button: "left", modifiers: ["shift", "command"], clicks: 1) ]) } func testParsesMouseClickWithClickCount() throws { let commands = getCommands(CommandsIterator("<m:right:2>")) XCTAssertEqual( commands, [ MouseClickCommand(button: "right", modifiers: [], clicks: 2) ]) } func testParsesMouseClickWithModifiersAndClickCount() throws { let commands = getCommands(CommandsIterator("<m:right:command:2>")) XCTAssertEqual( commands, [ MouseClickCommand(button: "right", modifiers: ["command"], clicks: 2) ]) } func testParsesMousePath() throws { let commands = getCommands(CommandsIterator("<mpath:L 200 400:2>")) XCTAssertEqual( commands, [ MousePathCommand( path: "L 200 400", offsetX: 0, offsetY: 0, scaleX: 1, scaleY: 1, duration: 2, modifiers: []) ]) } func testParsesMousePathWithOffset() throws { let commands = getCommands(CommandsIterator("<mpath:L 200 400:100,200:2>")) XCTAssertEqual( commands, [ MousePathCommand( path: "L 200 400", offsetX: 100, offsetY: 200, scaleX: 1, scaleY: 1, duration: 2, modifiers: []) ]) } func testParsesMousePathWithOffsetAndScale() throws { let commands = getCommands(CommandsIterator("<mpath:L 200 400:100,200,0.5,2.5:2>")) XCTAssertEqual( commands, [ MousePathCommand( path: "L 200 400", offsetX: 100, offsetY: 200, scaleX: 0.5, scaleY: 2.5, duration: 2, modifiers: []) ]) } func testParsesMousePathWithOffsetAndPartialScale() throws { let commands = getCommands(CommandsIterator("<mpath:L 200 400:100,200,0.4:2>")) XCTAssertEqual( commands, [ MousePathCommand( path: "L 200 400", offsetX: 100, offsetY: 200, scaleX: 0.4, scaleY: 0.4, duration: 2, modifiers: []) ]) } func testParsesMouseDrag() throws { let commands = getCommands(CommandsIterator("<d:1.5,2.5,3.5,4.5>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: 1.5, y1: 2.5, x2: 3.5, y2: 4.5, duration: 0, button: "left", modifiers: []) ]) } func testParsesMouseDragWithButton() throws { let commands = getCommands(CommandsIterator("<d:1,2,3,4:right>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: 1, y1: 2, x2: 3, y2: 4, duration: 0, button: "right", modifiers: []) ]) } func testParsesMouseDragWithButtonAndModifiers() throws { let commands = getCommands(CommandsIterator("<d:1,2,3,4:right:command,shift>")) XCTAssertEqual( commands, [ MouseDragCommand( x1: 1, y1: 2, x2: 3, y2: 4, duration: 0, button: "right", modifiers: ["command", "shift"]) ]) } func testParsesMouseDragWithDuration() throws { let commands = getCommands(CommandsIterator("<d:1,2,3,4:0.1>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: 1, y1: 2, x2: 3, y2: 4, duration: 0.1, button: "left", modifiers: []) ]) } func testParsesMouseDragWithDurationWithNegativeCoordinates() throws { let commands = getCommands(CommandsIterator("<d:-1.5,-2,-3,-4:0.1>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: -1.5, y1: -2, x2: -3, y2: -4, duration: 0.1, button: "left", modifiers: []) ]) } func testParsesMouseDragWithDurationAndButton() throws { let commands = getCommands(CommandsIterator("<d:1,2,3,4:0.1:right>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: 1, y1: 2, x2: 3, y2: 4, duration: 0.1, button: "right", modifiers: []) ]) } func testParsesMouseDragWithDurationAndButtonAndModifier() throws { let commands = getCommands(CommandsIterator("<d:1,2,3,4:0.1:right:command>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: 1, y1: 2, x2: 3, y2: 4, duration: 0.1, button: "right", modifiers: ["command"]) ]) } func testParsesPartialMouseDrag() throws { let commands = getCommands(CommandsIterator("<d:3,4>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: nil, y1: nil, x2: 3, y2: 4, duration: 0, button: "left", modifiers: []) ]) } func testParsesPartialMouseDragWithDuration() throws { let commands = getCommands(CommandsIterator("<d:3,4:2>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: nil, y1: nil, x2: 3, y2: 4, duration: 2, button: "left", modifiers: []) ]) } func testParsesPartialMouseDragWithDurationAndButton() throws { let commands = getCommands(CommandsIterator("<d:3,4:2:center>")) XCTAssertEqual( commands, [ MouseDragCommand(x1: nil, y1: nil, x2: 3, y2: 4, duration: 2, button: "center", modifiers: []) ]) } func testParsesMouseScroll() throws { let commands = getCommands(CommandsIterator("<s:0,10.5>")) XCTAssertEqual( commands, [ MouseScrollCommand(x: 0, y: 10.5, duration: 0, modifiers: []) ]) } func testParsesMouseScrollWithNegativeAmount() throws { let commands = getCommands(CommandsIterator("<s:-100,10>")) XCTAssertEqual( commands, [ MouseScrollCommand(x: -100, y: 10, duration: 0, modifiers: []) ]) } func testParsesMouseScrollWithDuration() throws { let commands = getCommands(CommandsIterator("<s:0,10:0.5>")) XCTAssertEqual( commands, [ MouseScrollCommand(x: 0, y: 10, duration: 0.5, modifiers: []) ]) } func testParsesMouseScrollWithDurationAndModifiers() throws { let commands = getCommands(CommandsIterator("<s:0,10:0.5:shift>")) XCTAssertEqual( commands, [ MouseScrollCommand(x: 0, y: 10, duration: 0.5, modifiers: ["shift"]) ]) } func testParsesMouseScrollWithNegativeAmountAndDuration() throws { let commands = getCommands(CommandsIterator("<s:0,-10:0.5>")) XCTAssertEqual( commands, [ MouseScrollCommand(x: 0, y: -10, duration: 0.5, modifiers: []) ]) } func testParsesMouseDown() throws { let commands = getCommands(CommandsIterator("<md:right>")) XCTAssertEqual( commands, [ MouseDownCommand(button: "right", modifiers: []) ]) } func testParsesMouseDownWithModifiers() throws { let commands = getCommands(CommandsIterator("<md:left:shift,command>")) XCTAssertEqual( commands, [ MouseDownCommand(button: "left", modifiers: ["shift", "command"]) ]) } func testParsesMouseUp() throws { let commands = getCommands(CommandsIterator("<mu:center>")) XCTAssertEqual( commands, [ MouseUpCommand(button: "center", modifiers: []) ]) } func testParsesMouseUpWithModifiers() throws { let commands = getCommands(CommandsIterator("<mu:right:option,command>")) XCTAssertEqual( commands, [ MouseUpCommand(button: "right", modifiers: ["option", "command"]) ]) } func testParsesMouseFocus() throws { let commands = getCommands(CommandsIterator("<mf:0.5,0.5:100.5,50.5:0.5,360.5:1>")) XCTAssertEqual( commands, [ MouseFocusCommand(x: 0.5, y: 0.5, rx: 100.5, ry: 50.5, angleFrom: 0.5, angleTo: 360.5, duration: 1) ]) } func testParsesMouseFocusWithSingleRadius() throws { let commands = getCommands(CommandsIterator("<mf:0,0:100:0,360:0.1>")) XCTAssertEqual( commands, [ MouseFocusCommand(x: 0, y: 0, rx: 100, ry: 100, angleFrom: 0, angleTo: 360, duration: 0.1) ]) } func testParsesMouseFocusWithNegativeCoordinates() throws { let commands = getCommands(CommandsIterator("<mf:-10,-20:100,50:0,360:1.5>")) XCTAssertEqual( commands, [ MouseFocusCommand(x: -10, y: -20, rx: 100, ry: 50, angleFrom: 0, angleTo: 360, duration: 1.5) ]) } func testParsesMouseFocusWithNegativeAngles() throws { let commands = getCommands(CommandsIterator("<mf:-10,-20:100,50:100,-360:1.5>")) XCTAssertEqual( commands, [ MouseFocusCommand(x: -10, y: -20, rx: 100, ry: 50, angleFrom: 100, angleTo: -360, duration: 1.5) ]) } private func getCommands(_ iterator: CommandsIterator) -> [Command] { var commands: [Command] = [] while true { let command = iterator.next() if command == nil { break } commands.append(command!) } return commands } }
31.918216
120
0.533194
e2f63ee36502af9a5d7aaca534df6c09751794ab
1,227
// // GameViewController.swift // G-Waz // // Created by Bertrand Pouteau on 05/10/2019. // Copyright © 2019 Behr. All rights reserved. // import UIKit import SpriteKit import GameplayKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let view = self.view as! SKView? { // Load the SKScene from 'GameScene.sks' if let scene = SKScene(fileNamed: "GameScene") { // Set the scale mode to scale to fit the window scene.scaleMode = .resizeFill // Present the scene view.presentScene(scene) } view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override var prefersStatusBarHidden: Bool { return true } }
24.058824
77
0.568052
33e0a5edef6a589dfbd694d7dd6e013bc73757ef
1,217
// // pager.swift // DemoApp // // Created by WVMAC3 on 09/01/18. // Copyright © 2018 WVMAC3. All rights reserved. // import UIKit public class pager: UICollectionViewCell { var arrImage = UIImageView() var lblTitle = UILabel() override init(frame: CGRect) { super.init(frame: frame) let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)) headerView.backgroundColor = #colorLiteral(red: 0.9486700892, green: 0.9493889213, blue: 0.9487814307, alpha: 1) arrImage.frame = CGRect.init(x: 0, y: 0, width: headerView.frame.size.width, height: headerView.frame.size.height-60) headerView.addSubview(arrImage) lblTitle.frame = CGRect.init(x: 5, y:headerView.frame.size.height-50, width: headerView.frame.size.width-10, height: 45) lblTitle.numberOfLines = 0 lblTitle.font = UIFont.systemFont(ofSize: 14) lblTitle.textColor = .red headerView.addSubview(lblTitle) self.addSubview(headerView) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
29.682927
130
0.642564
381198dd18e50271c18d28c413b02ba10adbe83e
129
//___FILEHEADER___ import RxSwift import RxCocoa class ___VARIABLE_moduleName___ViewModel { init() { } }
10.75
42
0.658915
dd2e5436de3c3df9b349b671d235d922700e1627
9,662
// 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. // // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment // swiftlint:disable type_body_length function_body_length generic_type_name cyclomatic_complexity // -- Generated Code; do not edit -- // // StepFunctionsModelErrors.swift // StepFunctionsModel // import Foundation import Logging public typealias StepFunctionsErrorResult<SuccessPayload> = Result<SuccessPayload, StepFunctionsError> public extension Swift.Error { func asUnrecognizedStepFunctionsError() -> StepFunctionsError { let errorType = String(describing: type(of: self)) let errorDescription = String(describing: self) return .unrecognizedError(errorType, errorDescription) } } private let activityDoesNotExistIdentity = "ActivityDoesNotExist" private let activityLimitExceededIdentity = "ActivityLimitExceeded" private let activityWorkerLimitExceededIdentity = "ActivityWorkerLimitExceeded" private let executionAlreadyExistsIdentity = "ExecutionAlreadyExists" private let executionDoesNotExistIdentity = "ExecutionDoesNotExist" private let executionLimitExceededIdentity = "ExecutionLimitExceeded" private let invalidArnIdentity = "InvalidArn" private let invalidDefinitionIdentity = "InvalidDefinition" private let invalidExecutionInputIdentity = "InvalidExecutionInput" private let invalidLoggingConfigurationIdentity = "InvalidLoggingConfiguration" private let invalidNameIdentity = "InvalidName" private let invalidOutputIdentity = "InvalidOutput" private let invalidTokenIdentity = "InvalidToken" private let invalidTracingConfigurationIdentity = "InvalidTracingConfiguration" private let missingRequiredParameterIdentity = "MissingRequiredParameter" private let resourceNotFoundIdentity = "ResourceNotFound" private let stateMachineAlreadyExistsIdentity = "StateMachineAlreadyExists" private let stateMachineDeletingIdentity = "StateMachineDeleting" private let stateMachineDoesNotExistIdentity = "StateMachineDoesNotExist" private let stateMachineLimitExceededIdentity = "StateMachineLimitExceeded" private let stateMachineTypeNotSupportedIdentity = "StateMachineTypeNotSupported" private let taskDoesNotExistIdentity = "TaskDoesNotExist" private let taskTimedOutIdentity = "TaskTimedOut" private let tooManyTagsIdentity = "TooManyTags" private let __accessDeniedIdentity = "AccessDenied" public enum StepFunctionsError: Swift.Error, Decodable { case activityDoesNotExist(ActivityDoesNotExist) case activityLimitExceeded(ActivityLimitExceeded) case activityWorkerLimitExceeded(ActivityWorkerLimitExceeded) case executionAlreadyExists(ExecutionAlreadyExists) case executionDoesNotExist(ExecutionDoesNotExist) case executionLimitExceeded(ExecutionLimitExceeded) case invalidArn(InvalidArn) case invalidDefinition(InvalidDefinition) case invalidExecutionInput(InvalidExecutionInput) case invalidLoggingConfiguration(InvalidLoggingConfiguration) case invalidName(InvalidName) case invalidOutput(InvalidOutput) case invalidToken(InvalidToken) case invalidTracingConfiguration(InvalidTracingConfiguration) case missingRequiredParameter(MissingRequiredParameter) case resourceNotFound(ResourceNotFound) case stateMachineAlreadyExists(StateMachineAlreadyExists) case stateMachineDeleting(StateMachineDeleting) case stateMachineDoesNotExist(StateMachineDoesNotExist) case stateMachineLimitExceeded(StateMachineLimitExceeded) case stateMachineTypeNotSupported(StateMachineTypeNotSupported) case taskDoesNotExist(TaskDoesNotExist) case taskTimedOut(TaskTimedOut) case tooManyTags(TooManyTags) case accessDenied(message: String?) case validationError(reason: String) case unrecognizedError(String, String?) enum CodingKeys: String, CodingKey { case type = "__type" case message = "message" } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) var errorReason = try values.decode(String.self, forKey: .type) let errorMessage = try values.decodeIfPresent(String.self, forKey: .message) if let index = errorReason.firstIndex(of: "#") { errorReason = String(errorReason[errorReason.index(index, offsetBy: 1)...]) } switch errorReason { case activityDoesNotExistIdentity: let errorPayload = try ActivityDoesNotExist(from: decoder) self = StepFunctionsError.activityDoesNotExist(errorPayload) case activityLimitExceededIdentity: let errorPayload = try ActivityLimitExceeded(from: decoder) self = StepFunctionsError.activityLimitExceeded(errorPayload) case activityWorkerLimitExceededIdentity: let errorPayload = try ActivityWorkerLimitExceeded(from: decoder) self = StepFunctionsError.activityWorkerLimitExceeded(errorPayload) case executionAlreadyExistsIdentity: let errorPayload = try ExecutionAlreadyExists(from: decoder) self = StepFunctionsError.executionAlreadyExists(errorPayload) case executionDoesNotExistIdentity: let errorPayload = try ExecutionDoesNotExist(from: decoder) self = StepFunctionsError.executionDoesNotExist(errorPayload) case executionLimitExceededIdentity: let errorPayload = try ExecutionLimitExceeded(from: decoder) self = StepFunctionsError.executionLimitExceeded(errorPayload) case invalidArnIdentity: let errorPayload = try InvalidArn(from: decoder) self = StepFunctionsError.invalidArn(errorPayload) case invalidDefinitionIdentity: let errorPayload = try InvalidDefinition(from: decoder) self = StepFunctionsError.invalidDefinition(errorPayload) case invalidExecutionInputIdentity: let errorPayload = try InvalidExecutionInput(from: decoder) self = StepFunctionsError.invalidExecutionInput(errorPayload) case invalidLoggingConfigurationIdentity: let errorPayload = try InvalidLoggingConfiguration(from: decoder) self = StepFunctionsError.invalidLoggingConfiguration(errorPayload) case invalidNameIdentity: let errorPayload = try InvalidName(from: decoder) self = StepFunctionsError.invalidName(errorPayload) case invalidOutputIdentity: let errorPayload = try InvalidOutput(from: decoder) self = StepFunctionsError.invalidOutput(errorPayload) case invalidTokenIdentity: let errorPayload = try InvalidToken(from: decoder) self = StepFunctionsError.invalidToken(errorPayload) case invalidTracingConfigurationIdentity: let errorPayload = try InvalidTracingConfiguration(from: decoder) self = StepFunctionsError.invalidTracingConfiguration(errorPayload) case missingRequiredParameterIdentity: let errorPayload = try MissingRequiredParameter(from: decoder) self = StepFunctionsError.missingRequiredParameter(errorPayload) case resourceNotFoundIdentity: let errorPayload = try ResourceNotFound(from: decoder) self = StepFunctionsError.resourceNotFound(errorPayload) case stateMachineAlreadyExistsIdentity: let errorPayload = try StateMachineAlreadyExists(from: decoder) self = StepFunctionsError.stateMachineAlreadyExists(errorPayload) case stateMachineDeletingIdentity: let errorPayload = try StateMachineDeleting(from: decoder) self = StepFunctionsError.stateMachineDeleting(errorPayload) case stateMachineDoesNotExistIdentity: let errorPayload = try StateMachineDoesNotExist(from: decoder) self = StepFunctionsError.stateMachineDoesNotExist(errorPayload) case stateMachineLimitExceededIdentity: let errorPayload = try StateMachineLimitExceeded(from: decoder) self = StepFunctionsError.stateMachineLimitExceeded(errorPayload) case stateMachineTypeNotSupportedIdentity: let errorPayload = try StateMachineTypeNotSupported(from: decoder) self = StepFunctionsError.stateMachineTypeNotSupported(errorPayload) case taskDoesNotExistIdentity: let errorPayload = try TaskDoesNotExist(from: decoder) self = StepFunctionsError.taskDoesNotExist(errorPayload) case taskTimedOutIdentity: let errorPayload = try TaskTimedOut(from: decoder) self = StepFunctionsError.taskTimedOut(errorPayload) case tooManyTagsIdentity: let errorPayload = try TooManyTags(from: decoder) self = StepFunctionsError.tooManyTags(errorPayload) case __accessDeniedIdentity: self = .accessDenied(message: errorMessage) default: self = StepFunctionsError.unrecognizedError(errorReason, errorMessage) } } }
51.668449
102
0.762058
d7380d925f8d693e3ab7c7f28a41a31ab9195418
1,717
// // UIHelper.swift // VS // // Created by Vladyslav Semenchenko on 12/14/17. // Copyright © 2017 Vladyslav Semenchenko. All rights reserved. // import UIKit public class UIHelper { public class func isiPhone5() -> Bool { let screenRect = UIScreen.main.bounds if screenRect.size.height == 568 || screenRect.size.width == 568 { return true } else { return false } } public class func addMediumParallax(to: UIView) { UIHelper.addParallax(to: to, min: -20, max: 20) } public class func addSmallParallax(to: UIView) { UIHelper.addParallax(to: to, min: -10, max: 10) } public class func removeParallax(to: UIView) { for effect in to.motionEffects { to.removeMotionEffect(effect) } } public class func setStatusBarStyleTo(_ style: UIStatusBarStyle) { UIApplication.shared.statusBarStyle = style } // MARK: - Private private class func addParallax(to: UIView, min: Int, max: Int) { let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) verticalMotionEffect.minimumRelativeValue = min verticalMotionEffect.maximumRelativeValue = max let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) horizontalMotionEffect.minimumRelativeValue = min horizontalMotionEffect.maximumRelativeValue = max let group = UIMotionEffectGroup() group.motionEffects = [horizontalMotionEffect, verticalMotionEffect] to.addMotionEffect(group) } }
30.122807
117
0.649971
9bfbf1283701c094990097678c41f5088fec1f25
164
import UIKit extension ViewTextBar { struct Constants { static let buttonFontSize:CGFloat = 14 static let buttonWidth:CGFloat = 70 } }
14.909091
46
0.652439
502ddc6d12379a98c704e4fd70917bcc5795def9
2,873
// // HzyTransitioningDelegate.swift // library // // Created by Ranger on 2018/5/18. // Copyright © 2018年 hzy. All rights reserved. // import UIKit protocol HzyTransitioningDelegateable { var portrait: CGRect? {get set} var landScape: CGRect? {get set} var maskColor: UIColor? {get set} } protocol HzyTransitioningAnimatorable: UIViewControllerAnimatedTransitioning { var isPresent: Bool{get set} } class HzyTransitioningDelegate: NSObject { enum PresentTransionStyle: String { case circle = "circle" case backScale = "backScale" case rightToLeft = "rightToLeft" case leftToRight = "leftToRight" case bottomToTop = "bottomToTop" case show = "show" } fileprivate var presentTransionStyle: PresentTransionStyle fileprivate var animator: HzyTransitioningAnimatorable var portrait: CGRect? var landScape: CGRect? var maskColor: UIColor? init(presentTransionStyle: PresentTransionStyle) { self.presentTransionStyle = presentTransionStyle switch presentTransionStyle { case .bottomToTop: self.animator = HzyPresentSimpleAnimation(.bottomToTop) case .leftToRight: self.animator = HzyPresentSimpleAnimation(.leftToRight) case .rightToLeft: self.animator = HzyPresentSimpleAnimation(.rightToLeft) case .show: self.animator = HzyPresentSimpleAnimation(.show) default: self.animator = HzyPresentBackScaleAnimation() } } } // MARK:- 自定义转场代理的方法 extension HzyTransitioningDelegate : UIViewControllerTransitioningDelegate { // 目的:改变弹出View的尺寸 func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { let presentation = HzyPresentationController(presentedViewController: presented, presenting: presenting) if presentTransionStyle != .circle { presentation.presentedPortraitFrame = portrait presentation.presentedLandscapeFrame = landScape presentation.maskBackgroundColor = maskColor } return presentation } // 目的:自定义弹出的动画 func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.isPresent = true return animator } // 目的:自定义消失的动画 func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.isPresent = false return animator } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return nil } }
31.571429
170
0.704838
76fc415229f63d419b724c3627220b1ef43f2b4d
2,358
// // SceneDelegate.swift // DataCollection_Swift // // Created by geowin on 2020/7/22. // Copyright © 2020 geowin. 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. } }
42.872727
147
0.71162
71b17ad8130a445591e35dbfc37853265e7e580a
1,667
// // ProfileActionButtonView.swift // Twitter // // Created by user204085 on 11/21/21. // import SwiftUI struct ProfileActionButtonView: View { @ObservedObject var viewModel: ProfileViewModel @Binding var editProfilePresented: Bool var body: some View { if viewModel.user.isCurrentUser { Button(action: { editProfilePresented.toggle() }, label: { Text("View Profile") .frame(width: 360, height: 40) .background(Color.blue) .foregroundColor(.white) }) .fullScreenCover(isPresented: $editProfilePresented) { EditProfileView(isShowing: $editProfilePresented, user: viewModel.user) } .cornerRadius(20) } else { HStack { Button(action: { viewModel.user.isFollowed ? viewModel.unfollow() : viewModel.follow() }, label: { Text(viewModel.user.isFollowed ? "Following" : "Follow") .frame(width: 180, height: 40) .background(Color.blue) .foregroundColor(.white) }) .cornerRadius(20) NavigationLink(destination: ChatView(user: viewModel.user), label: { Text("Message") .frame(width: 180, height: 40) .background(Color.purple) .foregroundColor(.white) }) .cornerRadius(20) } } } }
32.686275
89
0.483503
9c57e8b649887922fdd50ee0b501e81432e961dd
2,390
// Copyright (c) 2016 NoodleNation <[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. public protocol Separable : Hashable { func separatedComponents() -> [Self] } extension String : Separable {} extension String { public func separatedComponents() -> [String] { return components(separatedBy: .whitespaces) } } /// public protocol SeparableOptionSetType : OptionSet { /// associatedtype Key: Separable /// static var values: [Key : Element] { get } /// init(rawValue: RawValue) /// init(_ rawValue: RawValue) /// init(key: Key?) /// init(_ key: Key?) /// init(keys: [Key]?) /// init(_ keys: [Key]?) } extension SeparableOptionSetType { public init(_ rawValue: RawValue) { self.init(rawValue: rawValue) } public init(key: Key?) { self.init(keys: key?.separatedComponents()) } public init(_ key: Key?) { self.init(key: key) } public init(keys: [Key]?) { self.init() guard let keys = keys else { return } for key in keys { guard let element = Self.values[key] else { continue } insert(element) } } public init(_ keys: [Key]?) { self.init(keys: keys) } }
27.471264
80
0.645607
481668ef3f8c9e469fd679711280c8612a0b22cc
11,152
import AVFoundation import CoreFoundation import VideoToolbox protocol VideoEncoderDelegate: class { func didSetFormatDescription(video formatDescription: CMFormatDescription?) func sampleOutput(video sampleBuffer: CMSampleBuffer) } // MARK: - final class H264Encoder: NSObject { static let supportedSettingsKeys: [String] = [ "muted", "width", "height", "bitrate", "profileLevel", "dataRateLimits", "enabledHardwareEncoder", // macOS only "maxKeyFrameIntervalDuration", "scalingMode" ] static let defaultWidth: Int32 = 480 static let defaultHeight: Int32 = 272 static let defaultBitrate: UInt32 = 160 * 1024 static let defaultScalingMode: String = "Trim" #if os(iOS) static let defaultAttributes: [NSString: AnyObject] = [ kCVPixelBufferIOSurfacePropertiesKey: [:] as AnyObject, kCVPixelBufferOpenGLESCompatibilityKey: kCFBooleanTrue ] #else static let defaultAttributes: [NSString: AnyObject] = [ kCVPixelBufferIOSurfacePropertiesKey: [:] as AnyObject, kCVPixelBufferOpenGLCompatibilityKey: kCFBooleanTrue ] #endif static let defaultDataRateLimits: [Int] = [0, 0] @objc var muted: Bool = false @objc var scalingMode: String = H264Encoder.defaultScalingMode { didSet { guard scalingMode != oldValue else { return } invalidateSession = true } } @objc var width: Int32 = H264Encoder.defaultWidth { didSet { guard width != oldValue else { return } invalidateSession = true } } @objc var height: Int32 = H264Encoder.defaultHeight { didSet { guard height != oldValue else { return } invalidateSession = true } } @objc var enabledHardwareEncoder: Bool = true { didSet { guard enabledHardwareEncoder != oldValue else { return } invalidateSession = true } } @objc var bitrate: UInt32 = H264Encoder.defaultBitrate { didSet { guard bitrate != oldValue else { return } setProperty(kVTCompressionPropertyKey_AverageBitRate, Int(bitrate) as CFTypeRef) } } @objc var dataRateLimits: [Int] = H264Encoder.defaultDataRateLimits { didSet { guard dataRateLimits != oldValue else { return } if dataRateLimits == H264Encoder.defaultDataRateLimits { invalidateSession = true return } setProperty(kVTCompressionPropertyKey_DataRateLimits, dataRateLimits as CFTypeRef) } } @objc var profileLevel: String = kVTProfileLevel_H264_Baseline_3_1 as String { didSet { guard profileLevel != oldValue else { return } invalidateSession = true } } @objc var maxKeyFrameIntervalDuration: Double = 2.0 { didSet { guard maxKeyFrameIntervalDuration != oldValue else { return } invalidateSession = true } } var locked: UInt32 = 0 var lockQueue = DispatchQueue(label: "com.haishinkit.HaishinKit.H264Encoder.lock") var expectedFPS: Float64 = AVMixer.defaultFPS { didSet { guard expectedFPS != oldValue else { return } setProperty(kVTCompressionPropertyKey_ExpectedFrameRate, NSNumber(value: expectedFPS)) } } var formatDescription: CMFormatDescription? { didSet { guard !CMFormatDescriptionEqual(formatDescription, otherFormatDescription: oldValue) else { return } delegate?.didSetFormatDescription(video: formatDescription) } } weak var delegate: VideoEncoderDelegate? private(set) var isRunning: Atomic<Bool> = .init(false) private(set) var status: OSStatus = noErr private var attributes: [NSString: AnyObject] { var attributes: [NSString: AnyObject] = H264Encoder.defaultAttributes attributes[kCVPixelBufferWidthKey] = NSNumber(value: width) attributes[kCVPixelBufferHeightKey] = NSNumber(value: height) return attributes } private var invalidateSession: Bool = true private var lastImageBuffer: CVImageBuffer? // @see: https://developer.apple.com/library/mac/releasenotes/General/APIDiffsMacOSX10_8/VideoToolbox.html private var properties: [NSString: NSObject] { let isBaseline: Bool = profileLevel.contains("Baseline") var properties: [NSString: NSObject] = [ kVTCompressionPropertyKey_RealTime: kCFBooleanTrue, kVTCompressionPropertyKey_ProfileLevel: profileLevel as NSObject, kVTCompressionPropertyKey_AverageBitRate: Int(bitrate) as NSObject, kVTCompressionPropertyKey_ExpectedFrameRate: NSNumber(value: expectedFPS), kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration: NSNumber(value: maxKeyFrameIntervalDuration), kVTCompressionPropertyKey_AllowFrameReordering: !isBaseline as NSObject, kVTCompressionPropertyKey_PixelTransferProperties: [ "ScalingMode": scalingMode ] as NSObject ] #if os(OSX) if enabledHardwareEncoder { properties[kVTVideoEncoderSpecification_EncoderID] = "com.apple.videotoolbox.videoencoder.h264.gva" as NSObject properties["EnableHardwareAcceleratedVideoEncoder"] = kCFBooleanTrue properties["RequireHardwareAcceleratedVideoEncoder"] = kCFBooleanTrue } #endif if dataRateLimits != H264Encoder.defaultDataRateLimits { properties[kVTCompressionPropertyKey_DataRateLimits] = dataRateLimits as NSObject } if !isBaseline { properties[kVTCompressionPropertyKey_H264EntropyMode] = kVTH264EntropyMode_CABAC } return properties } private var callback: VTCompressionOutputCallback = {( outputCallbackRefCon: UnsafeMutableRawPointer?, sourceFrameRefCon: UnsafeMutableRawPointer?, status: OSStatus, infoFlags: VTEncodeInfoFlags, sampleBuffer: CMSampleBuffer?) in guard let refcon: UnsafeMutableRawPointer = outputCallbackRefCon, let sampleBuffer: CMSampleBuffer = sampleBuffer, status == noErr else { return } let encoder: H264Encoder = Unmanaged<H264Encoder>.fromOpaque(refcon).takeUnretainedValue() encoder.formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer) encoder.delegate?.sampleOutput(video: sampleBuffer) } private var _session: VTCompressionSession? private var session: VTCompressionSession? { get { if _session == nil { guard VTCompressionSessionCreate( allocator: kCFAllocatorDefault, width: width, height: height, codecType: kCMVideoCodecType_H264, encoderSpecification: nil, imageBufferAttributes: attributes as CFDictionary?, compressedDataAllocator: nil, outputCallback: callback, refcon: Unmanaged.passUnretained(self).toOpaque(), compressionSessionOut: &_session ) == noErr else { logger.warn("create a VTCompressionSessionCreate") return nil } invalidateSession = false status = VTSessionSetProperties(_session!, propertyDictionary: properties as CFDictionary) status = VTCompressionSessionPrepareToEncodeFrames(_session!) } return _session } set { if let session: VTCompressionSession = _session { VTCompressionSessionInvalidate(session) } _session = newValue } } func encodeImageBuffer(_ imageBuffer: CVImageBuffer, presentationTimeStamp: CMTime, duration: CMTime) { guard isRunning.value && locked == 0 else { return } if invalidateSession { session = nil } guard let session: VTCompressionSession = session else { return } var flags: VTEncodeInfoFlags = [] VTCompressionSessionEncodeFrame( session, imageBuffer: muted ? lastImageBuffer ?? imageBuffer : imageBuffer, presentationTimeStamp: presentationTimeStamp, duration: duration, frameProperties: nil, sourceFrameRefcon: nil, infoFlagsOut: &flags ) if !muted { lastImageBuffer = imageBuffer } } private func setProperty(_ key: CFString, _ value: CFTypeRef?) { lockQueue.async { guard let session: VTCompressionSession = self._session else { return } self.status = VTSessionSetProperty( session, key: key, value: value ) } } #if os(iOS) @objc private func applicationWillEnterForeground(_ notification: Notification) { invalidateSession = true } @objc private func didAudioSessionInterruption(_ notification: Notification) { guard let userInfo: [AnyHashable: Any] = notification.userInfo, let value: NSNumber = userInfo[AVAudioSessionInterruptionTypeKey] as? NSNumber, let type: AVAudioSession.InterruptionType = AVAudioSession.InterruptionType(rawValue: value.uintValue) else { return } switch type { case .ended: invalidateSession = true default: break } } #endif } extension H264Encoder: Running { // MARK: Running func startRunning() { lockQueue.async { self.isRunning.mutate { $0 = true } #if os(iOS) NotificationCenter.default.addObserver( self, selector: #selector(self.didAudioSessionInterruption), name: AVAudioSession.interruptionNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(self.applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil ) #endif } } func stopRunning() { lockQueue.async { self.session = nil self.lastImageBuffer = nil self.formatDescription = nil #if os(iOS) NotificationCenter.default.removeObserver(self) #endif OSAtomicAnd32Barrier(0, &self.locked) self.isRunning.mutate { $0 = false } } } }
34.526316
123
0.609846
46cc3d2ccc21d80811e4e037e141e93cf4174708
5,935
// // BmoDoubleLabel.swift // Pods // // Created by LEE ZHE YU on 2017/4/3. // // import UIKit class BmoDoubleLabel: UILabel { let foreLabel = UILabel() var foreColor = UIColor.black { didSet { foreLabel.textColor = foreColor self.setNeedsDisplay() } } let foreMaskLayer = CAShapeLayer() let rearLabel = UILabel() let rearMaskLayer = CAShapeLayer() var rearView = UIView() var foreView = UIView() var orientation: UIPageViewControllerNavigationOrientation = .horizontal var maskProgress: CGFloat = 0.0 { didSet { self.setNeedsDisplay() } } override var text: String? { didSet { if text != nil { foreLabel.text = text rearLabel.text = text self.text = nil } } } override var font: UIFont! { didSet { foreLabel.font = font rearLabel.font = font } } override var textColor: UIColor! { didSet { rearLabel.textColor = textColor } } override var textAlignment: NSTextAlignment { didSet { foreLabel.textAlignment = textAlignment rearLabel.textAlignment = textAlignment } } var rearAttributedText: NSAttributedString? { didSet { rearLabel.attributedText = rearAttributedText } } var foreAttributedText: NSAttributedString? { didSet { foreLabel.attributedText = foreAttributedText } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { self.addSubview(rearView) rearView.backgroundColor = UIColor.clear rearView.layer.mask = rearMaskLayer rearView.bmoVP.autoFit(self) rearView.addSubview(rearLabel) rearLabel.backgroundColor = UIColor.clear rearLabel.bmoVP.autoFit(rearView) self.addSubview(foreView) foreView.backgroundColor = UIColor.clear foreView.layer.mask = foreMaskLayer foreView.bmoVP.autoFit(self) foreView.addSubview(foreLabel) foreLabel.backgroundColor = UIColor.clear foreLabel.bmoVP.autoFit(foreView) } func setRearBackgroundView(_ view: UIView) { rearView.subviews.forEach { (view) in if view is UILabel == false { view.removeFromSuperview() } } rearView.insertSubview(view, at: 0) view.bmoVP.autoFit(rearView) } func setForeBackgroundView(_ view: UIView) { foreView.subviews.forEach { (view) in if view is UILabel == false { view.removeFromSuperview() } } foreView.insertSubview(view, at: 0) view.bmoVP.autoFit(foreView) } override func draw(_ rect: CGRect) { super.draw(rect) if maskProgress == 1.0 { foreMaskLayer.path = CGPath(rect: rect, transform: nil) rearMaskLayer.path = CGPath(rect: CGRect.zero, transform: nil) } else if maskProgress > 0 { if orientation == .horizontal { foreMaskLayer.path = CGPath(rect: .init(origin: .zero, size: .init(width: rect.width * maskProgress, height: rect.height)), transform: nil) rearMaskLayer.path = CGPath(rect: .init(origin: .init(x: rect.width * abs(maskProgress), y: 0), size: .init(width: rect.width * 1 - abs(maskProgress), height: rect.height)), transform: nil) } else { foreMaskLayer.path = CGPath(rect: .init(origin: .zero, size: .init(width: rect.width, height: rect.height * maskProgress)), transform: nil) rearMaskLayer.path = CGPath(rect: .init(origin: .init(x: 0, y: rect.height * abs(maskProgress)), size: .init(width: rect.width, height: rect.height * 1 - abs(maskProgress))), transform: nil) } } else if maskProgress < 0 { if orientation == .horizontal { foreMaskLayer.path = CGPath(rect: .init(origin: .init(x: rect.width * abs(maskProgress), y: 0), size: .init(width: rect.width * 1 - abs(maskProgress), height: rect.height)), transform: nil) rearMaskLayer.path = CGPath(rect: .init(origin: .zero, size: .init(width: rect.width * abs(maskProgress), height: rect.height)), transform: nil) } else { foreMaskLayer.path = CGPath(rect: .init(origin: .init(x: 0, y: rect.height * abs(maskProgress)), size: .init(width: rect.width, height: rect.height * 1 - abs(maskProgress))), transform: nil) rearMaskLayer.path = CGPath(rect: .init(origin: .zero, size: .init(width: rect.width, height: rect.height * abs(maskProgress))), transform: nil) } } else { foreMaskLayer.path = CGPath(rect: CGRect.zero, transform: nil) rearMaskLayer.path = CGPath(rect: rect, transform: nil) } } }
38.290323
133
0.512216
908ad01ecdebddc7f2b05d4f584fb9a32e368233
5,463
// // RawColors.swift // iOSStoryBookDemo // // Created by junnikrishn on 10/2/20. // Copyright © 2020 Jayakrishnan u. All rights reserved. // import UIKit /** RawColors generated from design data. */ public struct RawColors { public static let black = UIColor(hexString: readPlist(file: "RawColors", key: "c-black")) public static let blueTint = UIColor(hexString: readPlist(file: "RawColors", key: "c-blue-tint")) public static let white = UIColor(hexString: readPlist(file: "RawColors", key: "c-white")) public static let orange4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-orange")) public static let green2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-green")) public static let blue1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-blue")) public static let purple3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-purple")) public static let pink2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-pink")) public static let purple1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-purple")) public static let pink1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-pink")) public static let green1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-green")) public static let blue4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-blue")) public static let gray3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-gray")) public static let gray7 = UIColor(hexString: readPlist(file: "RawColors", key: "c-07-gray")) public static let red2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-red")) public static let orange3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-orange")) public static let purple5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-purple")) public static let red3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-red")) public static let gray2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-gray")) public static let gray6 = UIColor(hexString: readPlist(file: "RawColors", key: "c-06-gray")) public static let gray8 = UIColor(hexString: readPlist(file: "RawColors", key: "c-08-gray")) public static let gray4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-gray")) public static let blue5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-blue")) public static let purple2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-purple")) public static let green4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-green")) public static let green3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-green")) public static let blue2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-blue")) public static let teal1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-teal")) public static let teal5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-teal")) public static let red1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-red")) public static let pink4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-pink")) public static let purple4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-purple")) public static let teal3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-teal")) public static let pink3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-pink")) public static let yellow5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-yellow")) public static let orange1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-orange")) public static let orange2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-orange")) public static let pink5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-pink")) public static let red4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-red")) public static let green5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-green")) public static let red5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-red")) public static let yellow1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-yellow")) public static let yellow2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-yellow")) public static let gray1 = UIColor(hexString: readPlist(file: "RawColors", key: "c-01-gray")) public static let teal4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-teal")) public static let yellow3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-yellow")) public static let yellow4 = UIColor(hexString: readPlist(file: "RawColors", key: "c-04-yellow")) public static let blue3 = UIColor(hexString: readPlist(file: "RawColors", key: "c-03-blue")) public static let orange5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-orange")) public static let teal2 = UIColor(hexString: readPlist(file: "RawColors", key: "c-02-teal")) public static let gray5 = UIColor(hexString: readPlist(file: "RawColors", key: "c-05-gray")) // Turbo colors public static let teal6 = UIColor(hexString: readPlist(file: "RawColors", key: "c-06-teal")) public static let red6 = UIColor(hexString: readPlist(file: "RawColors", key: "c-06-red")) }
76.943662
101
0.70291
dd0a98a273669241587bd73097051dc80f3324a7
4,010
// // Ref.swift // AntsColony // // Created by rhishikesh on 05/04/20. // Copyright © 2020 Helpshift. All rights reserved. // import Foundation class BadRef<A: Equatable> { private var val: A? private let lock: UnsafeMutablePointer<pthread_mutex_t> public init() { val = .none lock = UnsafeMutablePointer.allocate(capacity: MemoryLayout<pthread_mutex_t>.size) pthread_mutex_init(lock, nil) } /// Creates a new `Ref` containing the supplied value. public convenience init(initial: A) { self.init() put(initial) } private func put(_ x: A) { val = x } public func deref() -> A { let value = val! return value } public func alter(_ f: (A) throws -> A) { let a = val! do { let a1 = try f(a) // has a write happened ? if a1 != a { // Transaction pthread_mutex_lock(lock) // check if the value is still what we expect if val! == a { // yes, put the value, we won ! val = a1 pthread_mutex_unlock(lock) } else { // no, try again pthread_mutex_unlock(lock) alter(f) } } } catch _ { put(a) } } } func assoc(_ map: [String: Int], key: String, value: Int) -> [String: Int] { var new = map new[key] = value return new } func multiThreadAccess(_ count: Int) { let initialValue: [String: Int] = [:] let place = BadRef(initial: initialValue) // this emulates multi thread access with contention. for i in 1 ... count { DispatchQueue.global(qos: .userInteractive).async { place.alter { (old: [String: Int]) -> [String: Int] in assoc(old, key: "key:\(i)", value: i) } } } let t0 = Date().timeIntervalSince1970 // This is just to ensure that work is done while place.deref().keys.count < count { sleep(1) } let t1 = Date().timeIntervalSince1970 print("Time taken : \(t1 - t0)") print("Number of keys : \(place.deref().keys.count)") } func singleThreadAccess(_ count: Int) { let initialValue: [String: Int] = [:] let place = BadRef(initial: initialValue) // this is single thread access, no contention or retries. DispatchQueue.global(qos: .userInteractive).async { for i in 1 ... count { place.alter { (old: [String: Int]) -> [String: Int] in assoc(old, key: "key:\(i)", value: i) } } } let t0 = Date().timeIntervalSince1970 // This is just to ensure that work is done while place.deref().keys.count < count { sleep(1) } let t1 = Date().timeIntervalSince1970 print("Time taken : \(t1 - t0)") print("Number of keys : \(place.deref().keys.count)") } func simpleAccess(_ count: Int) { let initialValue: [String: Int] = [:] // this is best case, no contention, no function calls. DispatchQueue.global(qos: .userInteractive).async { let t0 = Date().timeIntervalSince1970 var old = initialValue for i in 1 ... count { var new = old new["key\(i)"] = i old = new } let t1 = Date().timeIntervalSince1970 print("Time taken : \(t1 - t0)") print("Number of keys : \(old.keys.count)") } } func simpleFunctionAccess(_ count: Int) { let initialValue: [String: Int] = [:] // this is best case with function call overheads. DispatchQueue.global(qos: .userInteractive).async { let t0 = Date().timeIntervalSince1970 var old = initialValue for i in 1 ... count { old = assoc(old, key: "key:\(i)", value: i) } let t1 = Date().timeIntervalSince1970 print("Time taken : \(t1 - t0)") } }
27.655172
90
0.539651
294d33d8c0940f750a94b3c072cdaa5436d41853
117
import SwiftUI public protocol KComponentProtocol: Codable { func render(withChildrens: [AnyView]) -> AnyView }
19.5
52
0.760684
e9aab3563264efcb8ec82a7caaad00dbbb8ef3b0
1,331
import Cocoa class NotConnectedTextField: NSTextField { var hover: Bool = false var trackingArea: NSTrackingArea? var onClick: (() -> Void)? func setup() { trackingArea = NSTrackingArea(rect: visibleRect, options: [.mouseEnteredAndExited, .activeAlways], owner: self, userInfo: nil) addTrackingArea(trackingArea!) } override init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) } override func mouseEntered(with _: NSEvent) { if isHidden { return } hover = true layer?.add(fadeTransition(duration: 0.2), forKey: "transition") stringValue = "Click to remove" textColor = NSColor.labelColor } override func mouseExited(with _: NSEvent) { if isHidden { return } hover = false layer?.add(fadeTransition(duration: 0.3), forKey: "transition") stringValue = "Not connected" textColor = NSColor.secondaryLabelColor } override func mouseDown(with _: NSEvent) { if isHidden { return } onClick?() } }
23.350877
134
0.589782
feb6f5292f02f163cfc95e4e388028b25c674e3e
5,670
// Validators.swift // // Copyright (c) 2016 Auth0 (http://auth0.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 protocol InputValidator { func validate(_ value: String?) -> Error? } public class PhoneValidator: InputValidator { let predicate: NSPredicate public init() { let regex = "^[0-9]{8,15}$" self.predicate = NSPredicate(format: "SELF MATCHES %@", regex) } func validate(_ value: String?) -> Error? { guard let email = value?.trimmed, !email.isEmpty else { return InputValidationError.mustNotBeEmpty } guard self.predicate.evaluate(with: email) else { return InputValidationError.notAPhoneNumber } return nil } } public class OneTimePasswordValidator: InputValidator { func validate(_ value: String?) -> Error? { guard let value = value?.trimmed, !value.isEmpty else { return InputValidationError.mustNotBeEmpty } #if swift(>=3.2) guard value.count > 3, value.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else { return InputValidationError.notAOneTimePassword } #else guard value.characters.count > 3, value.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else { return InputValidationError.notAOneTimePassword } #endif return nil } } public class NonEmptyValidator: InputValidator { func validate(_ value: String?) -> Error? { guard let value = value?.trimmed, !value.isEmpty else { return InputValidationError.mustNotBeEmpty } return nil } } public class UsernameValidator: InputValidator { let invalidSet: CharacterSet? let range: CountableClosedRange<Int> let emailValidator = EmailValidator() var min: Int { return self.range.lowerBound } var max: Int { return self.range.upperBound } public init() { self.range = 1...Int.max self.invalidSet = nil } public init(withLength range: CountableClosedRange<Int>, characterSet: CharacterSet) { self.invalidSet = characterSet self.range = range } func validate(_ value: String?) -> Error? { guard let username = value?.trimmed, !username.isEmpty else { return InputValidationError.mustNotBeEmpty } #if swift(>=3.2) guard self.range ~= username.count else { return self.invalidSet == nil ? InputValidationError.mustNotBeEmpty : InputValidationError.notAUsername } #else guard self.range ~= username.characters.count else { return self.invalidSet == nil ? InputValidationError.mustNotBeEmpty : InputValidationError.notAUsername } #endif guard let characterSet = self.invalidSet else { return nil } guard username.rangeOfCharacter(from: characterSet) == nil else { return InputValidationError.notAUsername } guard self.emailValidator.validate(username) != nil else { return InputValidationError.notAUsername } return nil } public static var auth0: CharacterSet { let set = NSMutableCharacterSet() set.formUnion(with: CharacterSet.alphanumerics) set.addCharacters(in: "_.-!#$'^`~@+") return set.inverted } } public class EmailValidator: InputValidator { let predicate: NSPredicate public init() { let regex = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?" self.predicate = NSPredicate(format: "SELF MATCHES %@", regex) } func validate(_ value: String?) -> Error? { guard let email = value?.trimmed, !email.isEmpty else { return InputValidationError.mustNotBeEmpty } guard self.predicate.evaluate(with: email) else { return InputValidationError.notAnEmailAddress } return nil } } protocol PasswordPolicyValidatorDelegate: class { func update(withRules rules: [RuleResult]) } public class PasswordPolicyValidator: InputValidator { let policy: PasswordPolicy weak var delegate: PasswordPolicyValidatorDelegate? public init(policy: PasswordPolicy) { self.policy = policy } func validate(_ value: String?) -> Error? { let result = self.policy.on(value) self.delegate?.update(withRules: result) let valid = result.allSatisfy { $0.valid } guard !valid else { return nil } return InputValidationError.passwordPolicyViolation(result: result.filter { !$0.valid }) } } private extension String { var trimmed: String { return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } }
39.375
181
0.6903
3ad447d061378e9226d77c0b13a9da1442c8c1f3
5,614
// // MultiLingualString.swift // PretixScan // // Created by Daniel Jilg on 15.03.19. // Copyright © 2019 rami.io. All rights reserved. // import Foundation /// A key for `MultiLingualString` public enum LanguageCode: String { case english = "en" case german = "de" case germanInformal = "de-informal" case spanish = "es" case french = "fr" case dutch = "nl" case dutchInformal = "nl-informal" case turkish = "tr" } /// A String equal that contains various translations. /// /// This entry is the type alias. See `MultiLingualString` for full documentation and methods. /// /// @see `MultiLingualString`, `MultiLingualStringLanguage` public typealias MultiLingualString = [String: String] // MARK: - Creation extension MultiLingualString { /// Create a new `MultiLingualString` with the given value as english representation public static func english(_ newStringValue: String) -> MultiLingualString { var newMultiLingualString = MultiLingualString() newMultiLingualString[LanguageCode.english.rawValue] = newStringValue return newMultiLingualString } /// Create a new `MultiLingualString` with the given value as german representation public static func german(_ newStringValue: String) -> MultiLingualString { var newMultiLingualString = MultiLingualString() newMultiLingualString[LanguageCode.german.rawValue] = newStringValue return newMultiLingualString } } // MARK: - Custom Getters and Setters extension MultiLingualString { public var english: String? { get { return self[LanguageCode.english.rawValue] } set { self[LanguageCode.english.rawValue] = newValue } } public var german: String? { get { return self[LanguageCode.german.rawValue] } set { self[LanguageCode.german.rawValue] = newValue } } public var germanInformal: String? { get { return self[LanguageCode.germanInformal.rawValue] } set { self[LanguageCode.germanInformal.rawValue] = newValue } } public var dutch: String? { get { return self[LanguageCode.dutch.rawValue] } set { self[LanguageCode.dutch.rawValue] = newValue } } public var dutchInformal: String? { get { return self[LanguageCode.dutchInformal.rawValue] } set { self[LanguageCode.dutchInformal.rawValue] = newValue } } public var spanish: String? { get { return self[LanguageCode.spanish.rawValue] } set { self[LanguageCode.spanish.rawValue] = newValue } } public var french: String? { get { return self[LanguageCode.french.rawValue] } set { self[LanguageCode.french.rawValue] = newValue } } public var turkish: String? { get { return self[LanguageCode.turkish.rawValue] } set { self[LanguageCode.turkish.rawValue] = newValue } } } // MARK: - Getting a String Representation /// A String equal that contains various translations. /// /// Use the `representation(in:)` methods to retrieve a specific representation or use `anyRepresentation()` to /// get a representation that will prioritize english, then german, then other languages. extension MultiLingualString { /// Return a representation of the string with the given locale public func representation(in locale: Locale?) -> String? { guard let languageCode = locale?.languageCode else { return anyRepresentation() } return representation(in: languageCode) } /// Return a representation of the string with the region code as `MultiLingualStringLanguage`. public func representation(in languageCode: LanguageCode) -> String? { return representation(in: languageCode.rawValue) } /// Return a representation of the string with the given ISO639-2 code public func representation(in languageCode: String) -> String? { if let representation = self[languageCode], representation.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).count > 0 { return representation } if let representation = self["\(languageCode)-informal"], representation.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).count > 0 { return representation } return anyRepresentation() } /// Return a string representation of the MultiLingual String, if any such exists at all /// /// Will try known languages first, then pick any other languages. Will only return `nil` /// if not a single language is saved inside the MultiLingualString. public func anyRepresentation() -> String? { let languageCodes: [LanguageCode] = [.english, .german, .germanInformal, .spanish, .french, .dutch, .dutchInformal, .turkish] for languageCode in languageCodes { if let representation = self[languageCode.rawValue], representation.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).count > 0 { return representation } } return self.first?.value } } // MARK: - Storing as JSON public extension MultiLingualString { /// Returns the MultiLingualString's representation as a String containing JSON. /// /// You should use `JSONDecoder.iso8601withFractionsDecoder` to decode the string again. func toJSONString() -> String? { if let data = try? JSONEncoder.iso8601withFractionsEncoder.encode(self) { return String(data: data, encoding: .utf8) } return nil } }
36.69281
111
0.678839
0aa30b95d9f3096ac286e39b03de6eb8ea53f98a
1,080
// // CarInputTableViewCell.swift // CarsApp // // Created by Joachim Kret on 31/07/2017. // Copyright © 2017 Joachim Kret. All rights reserved. // import Foundation import UIKit import Reusable final class CarInputTableViewCell: UITableViewCell, NibReusable, UITextFieldDelegate { @IBOutlet weak var textFieldInput: UITextField? private var viewModel: CarInputViewModelType? override func awakeFromNib() { super.awakeFromNib() configureTextField() } private func configureTextField() { let sel = #selector(CarInputTableViewCell.textDidChange) textFieldInput?.addTarget(self, action: sel, for: .editingChanged) textFieldInput?.delegate = self } func configure(with viewModel: CarInputViewModelType) { self.viewModel = viewModel textFieldInput?.placeholder = viewModel.outputs.currentPlaceholder textFieldInput?.text = viewModel.outputs.currentText } func textDidChange() { let text = textFieldInput?.text viewModel?.inputs.change(input: text) } }
25.714286
86
0.70463
cc906d51796b37698ad2ef6623294a9e6e46613a
769
// // Array+IndexPath.swift // TableViewLiaison // // Created by Dylan Shine on 4/6/18. // import Foundation extension Array where Element == IndexPath { func sortBySection() -> [Int: [IndexPath]] { var indexPathsBySection = [Int: [IndexPath]]() forEach { indexPath in if var indexPaths = indexPathsBySection[indexPath.section] { indexPaths.append(indexPath) indexPathsBySection[indexPath.section] = indexPaths.sorted(by: { (current, next) -> Bool in current.item > next.item }) } else { indexPathsBySection[indexPath.section] = [indexPath] } } return indexPathsBySection } }
25.633333
107
0.557867
acf77f5f17a51e79c6d14d7b9e0176b7a0def935
1,021
// // MKNetworkKitTests.swift // MKNetworkKitTests // // Created by Mugunth Kumar on 6/10/15. // Copyright © 2015 Steinlogic Consulting and Training Pte Ltd. All rights reserved. // import XCTest @testable import MKNetworkKit class MKNetworkKitTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.594595
111
0.646425
28fcf979428bb6b6fa74e73f534814846f7c0573
729
// // AppDelegate.swift // // Created by Fabrizio Duroni on 06/08/2018. // 2018 Fabrizio Duroni. // import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UNUserNotificationCenter .current() .requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in print("Did allow notification \(didAllow)") }) return true } }
27
114
0.615912
8a1aff2c6f291cbb62c28949703a8850d4adee60
3,511
import XCTest @testable import Swift_Base //MARK: - extension XCTestCase { func testActions(forControl control: UIControl, getActionsForTarget target:(object: AnyObject, event: UIControlEvents), mustBeNumberOfActions: Int, mustBeSelectors: Set<Selector>) { let actions = control.actions(forTarget: target.object, forControlEvent: target.event) XCTAssertNotNil(actions, "\(control) not have targets") XCTAssertEqual(actions!.count, mustBeNumberOfActions, "Action of \(control) not equal \(mustBeNumberOfActions)") for currentAction in actions! { let currentSelector = Selector(currentAction) XCTAssertTrue(mustBeSelectors.contains(currentSelector)) } } func testSendAction(selector: Selector, to: Any? = nil, from: Any? = nil) { UIApplication.shared.sendAction(selector, to: to, from: from, for: nil) } } //MARK: - extension UIViewController { func canPerformSegue(_ id: String) -> Bool { let segues = self.value(forKey: "storyboardSegueTemplates") as? [NSObject] guard let filtered = segues?.filter({ $0.value(forKey: "identifier") as? String == id }) else { return false } return filtered.count > 0 } // Just so you dont have to check all the time func performSegue(_ id: String, sender: AnyObject?) -> Bool { if self.canPerformSegue(id) { self.performSegue(withIdentifier: id, sender: sender) return true } return false } } //MARK: - extension UITableView { func touchRandomVisibleCell(_ inSection: Int, animated: Bool = false, scrollPosition: UITableViewScrollPosition = .none) -> Bool { guard var indexPathsForVisibleRows = self.indexPathsForVisibleRows , indexPathsForVisibleRows.count > 0 else { return false } indexPathsForVisibleRows = indexPathsForVisibleRows.filter { (indexPath) -> Bool in return (indexPath as NSIndexPath).section == inSection } guard indexPathsForVisibleRows.count > 0 else { return false } let index = Int(arc4random_uniform(UInt32(indexPathsForVisibleRows.count))) let indexPath = indexPathsForVisibleRows[index] self.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition) self.delegate?.tableView?(self, didSelectRowAt: indexPath) return true } } extension UICollectionView { func touchRandomVisibleCell(_ inSection: Int, animated: Bool = false, scrollPosition: UICollectionViewScrollPosition = UICollectionViewScrollPosition()) -> Bool { var indexPathsForVisibleItems = self.indexPathsForVisibleItems guard indexPathsForVisibleItems.count > 0 else { return false } indexPathsForVisibleItems = indexPathsForVisibleItems.filter { (indexPath) -> Bool in return (indexPath as NSIndexPath).section == inSection } guard indexPathsForVisibleItems.count > 0 else { return false } let index = Int(arc4random_uniform(UInt32(indexPathsForVisibleItems.count))) let indexPath = indexPathsForVisibleItems[index] self.selectItem(at: indexPath, animated: animated, scrollPosition: scrollPosition) self.delegate?.collectionView?(self, didSelectItemAt: indexPath) return true } } //MARK: - extension UIAlertAction { typealias HandlerAction = ((UIAlertAction) -> Void) var handler: HandlerAction? { return self.value(forKey: "simpleHandler") as? HandlerAction } }
41.305882
185
0.698661
21f94b573d7ee2ef1895ae9f7d05d95c735618e3
3,292
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import UIKit // MARK: - XCCollectionViewTileLayoutCustomizable public protocol XCCollectionViewTileLayoutCustomizable { func sectionConfiguration(in layout: XCCollectionViewTileLayout, for section: Int) -> XCCollectionViewTileLayout.SectionConfiguration } open class XCCollectionViewTileLayoutAdapter: XCComposedCollectionViewLayoutAdapter, XCCollectionViewDelegateTileLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: XCCollectionViewTileLayout, heightForItemAt indexPath: IndexPath, width: CGFloat) -> CGFloat? { let attributes = composedDataSource.collectionView(collectionView, itemAttributesAt: indexPath) return attributes?.height } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: XCCollectionViewTileLayout, headerAttributesInSection section: Int, width: CGFloat) -> (Bool, CGFloat?) { let attributes = composedDataSource.collectionView(collectionView, headerAttributesForSectionAt: section) return (attributes.enabled, attributes.size?.height) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: XCCollectionViewTileLayout, footerAttributesInSection section: Int, width: CGFloat) -> (Bool, CGFloat?) { let attributes = composedDataSource.collectionView(collectionView, footerAttributesForSectionAt: section) return (attributes.enabled, attributes.size?.height) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: XCCollectionViewTileLayout, estimatedHeightForItemAt indexPath: IndexPath, width: CGFloat) -> CGFloat { XCDataSourceSizeCalculator.estimatedItemSize(in: composedDataSource, at: indexPath, availableWidth: width).height } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: XCCollectionViewTileLayout, estimatedHeaderHeightInSection section: Int, width: CGFloat) -> CGFloat { XCDataSourceSizeCalculator.estimatedHeaderSize(in: composedDataSource, for: section, availableWidth: width).height } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: XCCollectionViewTileLayout, estimatedFooterHeightInSection section: Int, width: CGFloat) -> CGFloat { XCDataSourceSizeCalculator.estimatedFooterSize(in: composedDataSource, for: section, availableWidth: width).height } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: XCCollectionViewTileLayout, sectionConfigurationAt section: Int) -> XCCollectionViewTileLayout.SectionConfiguration? { let source = composedDataSource.index(for: section) guard let custom = source.dataSource as? XCCollectionViewTileLayoutCustomizable else { return nil } return custom.sectionConfiguration(in: collectionViewLayout, for: source.localSection) } } extension XCCollectionViewTileLayout: XCComposedCollectionViewLayoutCompatible { public static var defaultAdapterType: XCComposedCollectionViewLayoutAdapter.Type { XCCollectionViewTileLayoutAdapter.self } }
57.754386
214
0.79921
264694cf81e3a63fee9c329e8ab16cfe38d83629
4,674
// // AppDelegate.swift // ProyectoFinalEquipo2 // // Created by Universidad Politecnica de Gómez Palacio on 19-03-26. // Copyright © 2019 Universidad Politecnica de Gómez Palacio. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "ProyectoFinalEquipo2") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
49.723404
285
0.691057
64e5f4ea876c6dc67dc20080275a58110e3c114c
613
// // TransactionBurnNode.swift // WavesWallet-iOS // // Created by Prokofev Ruslan on 07/08/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation extension Node.DTO { struct BurnTransaction: Decodable { let type: Int let id: String let sender: String let senderPublicKey: String let fee: Int64 let timestamp: Date let version: Int let height: Int64? let signature: String? let proofs: [String]? let chainId: Int? let assetId: String let amount: Int64 } }
21.137931
57
0.597064
563bc934a0aa33e2d004f601fcd84195df7593fb
2,582
// // // Workspace: ImagePlayer // MacOS Version: 11.4 // // File Name: FileManager+Ext+ImagePlayer.swift // Creation: 5/31/21 8:18 PM // // Author: Dragos-Costin Mandu // // import Foundation import UniformTypeIdentifiers import os public extension FileManager { // MARK: - Constants & Variables /// The prefix to be used in the file creation/search methods. static var s_FileNamePrefix: String = Bundle.main.bundleIdentifier! + "-" static var s_LoggerCategory: String = "FileManager" static let s_Logger: Logger = .init(subsystem: loggerSubsystem, category: FileManager.s_LoggerCategory) } public extension FileManager { // MARK: - Methods /// Creates a file with given file name, in directory. If the file name isn't provided, it will create a file name. /// - Parameters: /// - fileName: The name of the file to be created. /// - contentType: The content type of the file. /// - data: The data that the file may contain when it's created. /// - directory: The directory in which the file is located. /// - domainMask: Domain constants specifying base locations to use when you search for significant directories. /// - attributes: A dictionary containing the attributes to associate with the new file. You can use these attributes to set the owner and group numbers, file permissions, and modification date. For a list of keys, see FileAttributeKey. If you specify nil for attributes, the file is created with a set of default attributes. /// - Returns: An URL that points to the newly created file. static func createFile(fileName: String? = nil, contentType: UTType? = nil, data: Data? = nil, directory: FileManager.SearchPathDirectory = .cachesDirectory, domainMask: FileManager.SearchPathDomainMask = .userDomainMask, attributes: [FileAttributeKey : Any]? = nil) -> URL? { if let fileUrl = createFileUrl(fileName: fileName, contentType: contentType, directory: directory, domainMask: domainMask) { if !FileManager.default.fileExists(atPath: fileUrl.path) { if FileManager.default.createFile(atPath: fileUrl.path, contents: data, attributes: attributes) { return fileUrl } s_Logger.error("Failed to create file with \(data ?? Data()).") } else { s_Logger.debug("File with name '\(fileName ?? "")' already exists.") } } return nil } }
40.34375
331
0.652595
f5085d6b7dc56a59f1a81bec9495c7d4984f633d
2,865
// // ViewController.swift // tipCalc // // Created by Chris Martinez on 8/30/18. // Copyright © 2018 Chris Martinez. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! 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. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let defaults = UserDefaults.standard tipControl.selectedSegmentIndex = defaults.integer(forKey: "tipIndex") calcUpdatedTip() } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } func calcUpdatedTip(){ //load defaults, grab bill from textfield let defaults = UserDefaults.standard let bill = Double(billField.text!) ?? 0 let tipPercentage = [0.18, 0.20, 0.25] //set the control from settings //if no previous settings has been set, set to first one: // if(defaults.integer(forKey: "tipIndex") == nil){ // tipControl.selectedSegmentIndex = 0 // } // else{ // tipControl.selectedSegmentIndex = defaults.integer(forKey: "tipIndex") // } let tipValue = tipPercentage[tipControl.selectedSegmentIndex] let tip = bill * tipValue let total = bill + tip tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } @IBAction func calculateTip(_ sender: Any) { //load defaults, grab bill from textfield let defaults = UserDefaults.standard let bill = Double(billField.text!) ?? 0 let tipPercentage = [0.18, 0.20, 0.25] //set the control from settings //if no previous settings has been set, set to first one: // if(defaults.integer(forKey: "tipIndex") == nil){ // tipControl.selectedSegmentIndex = 0 // } // else{ // tipControl.selectedSegmentIndex = defaults.integer(forKey: "tipIndex") // } let tipValue = tipPercentage[tipControl.selectedSegmentIndex] let tip = bill * tipValue let total = bill + tip tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } }
29.536082
92
0.582897
ed7062ae3a270236b0e1ef34a1b48d78b7ac5f2a
22,357
// // MessagesManager.swift // ConversationsApp // // Copyright © Twilio, Inc. All rights reserved. // import Foundation import TwilioConversationsClient protocol MessageManagerDelegate: AnyObject { func onMessageManagerError(_ error: Error) } class MessagesManager: MessagesManagerProtocol { private(set) var conversationsProvider: ConversationsProvider private(set) var conversationsRepository: ConversationsRepositoryProtocol private(set) var imageCache: ImageCache internal weak var delegate: MessageManagerDelegate? private let messageManagerDispatch = DispatchQueue(label: "com.twilio.conversationsdemo.MessagesManager", qos: .userInitiated) var conversationSid: String! // MARK: Intialization init(conversationsProvider: ConversationsProvider = ConversationsClientWrapper.wrapper, conversationsRepository: ConversationsRepositoryProtocol = ConversationsRepository.shared, imageCache: ImageCache = DefaultImageCache.shared) { self.conversationsProvider = conversationsProvider self.conversationsRepository = conversationsRepository self.imageCache = imageCache } func sendTextMessage(to conversationSid: String, with body: String, completion: @escaping (Error?) -> Void) { guard let identity: String = conversationsProvider.conversationsClient?.user?.identity else { return } guard body.trimmingCharacters(in: .whitespacesAndNewlines).count > 0 else { return } // Inserting message into cache even before it's sent to other participants. let uuid = UUID().uuidString let outgoingMessage: MessageDataItem = MessageDataItem(uuid: uuid, direction: MessageDirection.outgoing, author: identity, body: body, dateCreated: Date().timeIntervalSince1970, sendStatus: MessageSendStatus.sending, conversationSid: conversationSid, type: TCHMessageType.text) conversationsRepository.insertMessages([outgoingMessage], for: conversationSid) sendMessage(outgoingMessage, completion: completion) } func retrySendMessageWithUuid(_ uuid: String, _ completion: ((Error?) -> Void)? = nil) { let localMessageData = self.conversationsRepository.getMessageWithUuid(uuid).data guard let localMessage = localMessageData.value?.first?.getMessageDataItem() else { completion?(ActionError.notAbleToRetrieveCachedMessage) return } if (localMessage.sendStatus != .error) { return } localMessage.sendStatus = .sending conversationsRepository.updateMessages([localMessage]) sendMessage(localMessage) } // MARK: Helpers func notifyTypingOnConversation(_ conversationSid: String) { guard let client = conversationsProvider.conversationsClient else { self.delegate?.onMessageManagerError(DataFetchError.conversationsClientIsNotAvailable) return } client.conversation(withSidOrUniqueName: conversationSid) { result, conversation in conversation?.typing() } } private func sendMessage(_ outgoingMessage: MessageDataItem, completion: ((Error?) -> Void)? = nil) { guard let conversationSid = outgoingMessage.conversationSid, let messageOptions = TCHMessageOptions() .withBody(outgoingMessage.body!) .withAttributes(TCHJsonAttributes.init(dictionary: outgoingMessage.attributesDictionary), error: nil) else { completion?(ActionError.notAbleToBuildMessage) return } guard let client = conversationsProvider.conversationsClient else { self.delegate?.onMessageManagerError(DataFetchError.conversationsClientIsNotAvailable) return } client.conversation(withSidOrUniqueName: conversationSid) { result, conversation in guard result.isSuccessful, let conversation = conversation else { completion?(DataFetchError.requiredDataCallsFailed) return } conversation.sendMessage(with: messageOptions) { (result, sentMessage) in if let error = result.error { print("Error encountered while sending message: \(error)") outgoingMessage.sendStatus = MessageSendStatus.error } else { outgoingMessage.dateCreated = Date().timeIntervalSince1970 outgoingMessage.sid = sentMessage!.sid! outgoingMessage.sendStatus = .sent outgoingMessage.index = sentMessage!.index!.uintValue } self.conversationsRepository.updateMessages([outgoingMessage]) completion?(result.error) } } } func reactToMessage(withSid messageSid: String, withReaction reaction: ReactionType) { guard let messageToSend = conversationsRepository.getMessageWithSid(messageSid), let userIdentity = conversationsProvider.conversationsClient?.user?.identity else { delegate?.onMessageManagerError(ActionError.messagesNotAvailable) return } guard let client = conversationsProvider.conversationsClient else { self.delegate?.onMessageManagerError(DataFetchError.conversationsClientIsNotAvailable) return } client.conversation(withSidOrUniqueName: messageToSend.conversationSid!) { result, conversation in guard let conversation = conversation else { return } conversation.message(withIndex: NSNumber(value: messageToSend.index)) { [weak self] result, message in messageToSend.reactions.tooggleReaction(reaction, forParticipant: userIdentity) message?.setAttributes(TCHJsonAttributes(dictionary: messageToSend.attributesDictionary)) { updateResult in if (!updateResult.isSuccessful) { guard let error = updateResult.error else { self?.delegate?.onMessageManagerError(ActionError.unknown) return } self?.delegate?.onMessageManagerError(error) } } } } } func sendMediaMessage(toConversationWithSid sid: String, inputStream: InputStream, mimeType: String, inputSize: Int) { guard let identity: String = conversationsProvider.conversationsClient?.user?.identity else { return } guard let client = conversationsProvider.conversationsClient else { self.delegate?.onMessageManagerError(DataFetchError.conversationsClientIsNotAvailable) return } client.conversation(withSidOrUniqueName: sid) { result, conversation in guard let conversation = conversation else { return } self.sendMediaMessage(onConversation: conversation, author: identity, inputStream: inputStream, mimeType: mimeType, inputSize: inputSize) } } private func sendMediaMessage(onConversation conversation: TCHConversation, author: String, inputStream: InputStream, mimeType: String, inputSize: Int) { let result = imageCache.copyToAppCache(inputStream: inputStream) switch result { case .success(let url): print("[MediaMessage] Image copied to cache uploading to twilio") let uuid = UUID().uuidString let outgoingMessage = MessageDataItem( uuid: uuid, direction: MessageDirection.outgoing, author: author, body: nil, dateCreated: Date().timeIntervalSince1970, sendStatus: MessageSendStatus.sending, conversationSid: conversationSid, type: TCHMessageType.media ) guard let mediaData = try? Data(contentsOf: url), let messageOptions = TCHMessageOptions() .withAttributes(TCHJsonAttributes(dictionary: outgoingMessage.attributesDictionary), error: nil) else { self.delegate?.onMessageManagerError(ActionError.notAbleToBuildMessage) return } outgoingMessage.mediaProperties = MediaMessageProperties(mediaURL: url, messageSize: inputSize, uploadedSize: 0) outgoingMessage.mediaStatus = .uploading outgoingMessage.conversationSid = conversationSid self.conversationsRepository.updateMessages([outgoingMessage]) messageOptions.withMediaStream( InputStream(data: mediaData), contentType: mimeType, defaultFilename: nil, onStarted: { // Called when upload of media begins. print("[MediaMessage] Media upload started") }, onProgress: { (bytes) in let updatedProperties = MediaMessageProperties(mediaURL: nil, messageSize: inputSize, uploadedSize: Int(bytes)) outgoingMessage.mediaProperties = updatedProperties outgoingMessage.mediaStatus = .uploading self.conversationsRepository.updateMessages([outgoingMessage]) }, onCompleted: { (mediaSid) in print("[MediaMessage] Upload completed for sid \(mediaSid)") outgoingMessage.mediaSid = mediaSid outgoingMessage.mediaStatus = .uploaded let updatedProperties = MediaMessageProperties(mediaURL: url, messageSize: inputSize, uploadedSize: inputSize) outgoingMessage.mediaProperties = updatedProperties }) conversation.sendMessage(with: messageOptions) { (result, message) in if !result.isSuccessful { print("[MediaMessage] Media message has failed to send") outgoingMessage.sendStatus = .error self.conversationsRepository.updateMessages([outgoingMessage]) } else { print("[MediaMessage] Media message has been sent succesfully") outgoingMessage.sendStatus = .sent outgoingMessage.mediaSid = message?.mediaSid self.conversationsRepository.updateMessages([outgoingMessage]) } } outgoingMessage.sendStatus = .error self.conversationsRepository.updateMessages([outgoingMessage]) case .failure (let error): self.delegate?.onMessageManagerError(ActionError.writeToCacheError) print("[MediaMessage] Unable to copy to app cache \(error)") } } func retrySendMediaMessageWithUuid(_ messageUuid: String) { messageManagerDispatch.async { [weak self] in guard let self = self else { return } guard let client = self.conversationsProvider.conversationsClient else { self.delegate?.onMessageManagerError(DataFetchError.conversationsClientIsNotAvailable) return } client.conversation(withSidOrUniqueName: self.conversationSid) { result, conversation in let localMessageData = self.conversationsRepository.getMessageWithUuid(messageUuid).data guard let conversation = conversation, let localMessage = localMessageData.value?.first?.getMessageDataItem(), let localMediaUrl = localMessage.mediaProperties?.mediaURL, let messageSize = localMessage.mediaProperties?.messageSize, let messageOptions = TCHMessageOptions() .withAttributes(TCHJsonAttributes(dictionary: localMessage.attributesDictionary), error: nil), let data = try? Data(contentsOf: localMediaUrl) else { self.delegate?.onMessageManagerError(ActionError.notAbleToRetrieveCachedMessage) return } localMessage.sendStatus = .sending // Reset the uploaded size to zero in case the first upload try was interrupted localMessage.mediaProperties = MediaMessageProperties.init(mediaURL: localMediaUrl, messageSize: messageSize, uploadedSize: 0) self.conversationsRepository.updateMessages([localMessage]) messageOptions.withMediaStream( InputStream(data: data), contentType: "image/jpeg", defaultFilename: nil, onStarted: { // Called when upload of media begins. print("[MediaMessage] Media upload started") }, onProgress: { (bytes) in let updatedProperties = MediaMessageProperties(mediaURL: nil, messageSize: messageSize, uploadedSize: Int(bytes)) localMessage.mediaProperties = updatedProperties self.conversationsRepository.updateMessages([localMessage]) }, onCompleted: { (mediaSid) in print("Media message upload completed") let updatedProperties = MediaMessageProperties(mediaURL: nil, messageSize: messageSize, uploadedSize: messageSize) localMessage.mediaProperties = updatedProperties localMessage.mediaStatus = .uploaded self.conversationsRepository.updateMessages([localMessage]) }) conversation.sendMessage(with: messageOptions) { result, message in if result.isSuccessful { print("Media message Sent succesfully") localMessage.sendStatus = .sent localMessage.mediaSid = message?.mediaSid } else { print("Media message failed to be sent") localMessage.sendStatus = .error } self.conversationsRepository.updateMessages([localMessage]) } } } } func startMediaMessageDownloadForIndex(_ messageIndex: UInt) { messageManagerDispatch.async { [weak self] in guard let self = self else { NSLog("[MediaMessage] Download won't be happening as the identity or self can not be retreived") return } guard let client = self.conversationsProvider.conversationsClient else { self.delegate?.onMessageManagerError(DataFetchError.conversationsClientIsNotAvailable) return } client.conversation(withSidOrUniqueName: self.conversationSid) { result, conversation in guard let conversation = conversation else { return } conversation.message(withIndex: NSNumber(value: messageIndex)) { (result, tchMessage) in NSLog("[MediaMessage] startMediaMessageDownloadForIndex\(messageIndex) -> Get message result \(result) -> \(tchMessage.debugDescription) ") guard let message = tchMessage, let messageSid = message.sid, let messageDataItem = self.conversationsRepository.getMessageWithSid(messageSid) else { return } if (!self.isMessageNeedingDownload(mediaMessage: messageDataItem)) { NSLog("[MediaMessage] No need to download the message with index \(messageIndex) ") return } NSLog("[MediaMessage] We got what we need") messageDataItem.conversationSid = self.conversationSid messageDataItem.mediaStatus = .downloading self.conversationsRepository.updateMessages([messageDataItem]) message.getMediaContentTemporaryUrl { [weak self] _, urlString in guard let url = URL(string: urlString ?? "invalid url" ) else { NSLog("[MediaMessage] We got a wrong url from getMediaContentTemporaryUrl message with Index \(messageIndex)") messageDataItem.mediaStatus = .error self?.conversationsRepository.updateMessages([messageDataItem]) return } self?.imageCache.copyToAppCache(locatedAt: url) { cachedResult in switch cachedResult { case .success(let image): self?.messageManagerDispatch.async { messageDataItem.mediaProperties = MediaMessageProperties(mediaURL: image.url, messageSize: Int(message.mediaSize), uploadedSize: Int(message.mediaSize)) messageDataItem.mediaStatus = .downloaded self?.conversationsRepository.updateMessages([messageDataItem]) NSLog("[MediaMessage][cache] Download succes for message with Index: \(messageIndex)") } case .failure(_): messageDataItem.mediaStatus = .error self?.conversationsRepository.updateMessages([messageDataItem]) NSLog("[MediaMessage][cache] Download error for message with Index: \(messageIndex)") } } } } } } } func isMessageNeedingDownload(mediaMessage: MessageDataItem) -> Bool { guard let mediaStatus = mediaMessage.mediaStatus else { return true } switch mediaStatus { case .downloading: return false case .downloaded, .uploaded: return !imageCache.hasDataForURL(url: mediaMessage.mediaProperties?.mediaURL) case .error: return true case .uploading: return false } } func removeMessage(withIndex messageIndex: UInt, messageSid: String) { messageManagerDispatch.async { [weak self] in guard let self = self, let conversationSid = self.conversationSid else { return } guard let client = self.conversationsProvider.conversationsClient else { self.delegate?.onMessageManagerError(DataFetchError.conversationsClientIsNotAvailable) return } client.conversation(withSidOrUniqueName: self.conversationSid) { result, conversation in guard let conversation = conversation else { self.delegate?.onMessageManagerError(DataFetchError.requiredDataCallsFailed) return } conversation.message(withIndex: NSNumber(value: messageIndex)) { (result, message) in guard result.isSuccessful, let message = message else { self.delegate?.onMessageManagerError(DataFetchError.requiredDataCallsFailed) return } if message.sid != messageSid { self.delegate?.onMessageManagerError(DataFetchError.dataIsInconsistent) return } self.removeMessage(tchMessage: message, onConversationWithSid: conversationSid) } } } } private func removeMessage(tchMessage message: TCHMessage, onConversationWithSid conversationSid: String) { guard let client = conversationsProvider.conversationsClient else { self.delegate?.onMessageManagerError(DataFetchError.conversationsClientIsNotAvailable) return } client.conversation(withSidOrUniqueName: conversationSid) { result, conversation in guard let messageSid = message.sid, let conversation = conversation else { return } conversation.remove(message) { tchResult in if let error = tchResult.error { self.delegate?.onMessageManagerError(error) return } self.conversationsRepository.deleteMessagesWithSids([messageSid]) } } } func isCurrentUserAuthorOf(messageWithSid sid: String) -> Bool { guard let message = self.conversationsRepository.getMessageWithSid(sid), let identity: String = conversationsProvider.conversationsClient?.user?.identity else { return false } return message.author == identity } }
47.366525
159
0.578029
22cdf7b9d684c03f4e268e45cfc93d8e47162287
7,048
// // SearchResultView.swift // BetterReads // // Created by Jorge Alvarez on 4/20/20. // Copyright © 2020 Labs23. All rights reserved. // import UIKit class SearchResultView: UIView { // MARK: - Properties /// Displays book cover image var imageView: UIImageView! /// Displays title of book var titleLabel: UILabel! /// Displays author of book var authorLabel: UILabel! /// Not sure if this is even used anymore, too scared to remove right now var ratingView: UILabel! /// View that holds 5 star UIImageViews made below var starsView: UIView! /// Array that holds star UIImageViews to loop through all later var starsArray: [UIImageView] = [] /// Used for padding var standardMargin: CGFloat = CGFloat(16.0) /// Spacing between each star in the starsView var starSpacing: Int = 4 private let titleFont = UIFont(name: "FrankRuhlLibre-Regular", size: 20) private let authorFont = UIFont(name: "SourceSansPro-Light", size: 16) private let authorTextColor = UIColor.tundra /// Stores last image the cell had *(might have to delete this if you choose to implement image caches) private var lastThumbnailImage: String? /// Book passed in from SearchTableViewController var book: Book? { didSet { updateViews() } } // MARK: - View Life Cycle override init(frame: CGRect) { super.init(frame: frame) setUpSubviews() } required init?(coder: NSCoder) { super.init(coder: coder) setUpSubviews() } private func updateViews() { guard let book = book else { return } titleLabel.text = book.title authorLabel.text = book.authors?.first updateStarRating(value: book.averageRating ?? 0.0) guard let thumbnail = book.thumbnail else { imageView.image = UIImage().chooseDefaultBookImage() return } // there used to be a bug where images would flash, and this "fixed" it // use cache to improve this later (this might not be needed anymore) if lastThumbnailImage != thumbnail { SearchController.fetchImage(with: thumbnail) { (image) in DispatchQueue.main.async { self.imageView.image = image self.lastThumbnailImage = thumbnail } } } } /// Takes in double and fills up the stars in rating view private func updateStarRating(value: Double) { var chunk = value for star in starsArray { if chunk >= 0.66 && chunk <= 5.0 { star.image = UIImage(named: "Stars_Chunky-DoveGray") } else if chunk >= 0.33 && chunk < 0.66 { star.image = UIImage(named: "Stars_Chunky-AltoGray-LeftHalf") } else { star.image = UIImage(named: "Stars_Chunky-AltoGray") } chunk = value - Double(star.tag) } } // This can be split up into smaller functions called in order private func setUpSubviews() { // Image View let imageView = UIImageView() addSubview(imageView) self.imageView = imageView imageView.translatesAutoresizingMaskIntoConstraints = false imageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: standardMargin).isActive = true imageView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.20).isActive = true imageView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.75).isActive = true //imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: 3 / 4).isActive = true // mult for height used to be 1.5 of imageView.widthAnchor // widthAnchor used to be 0.25 imageView.contentMode = .scaleToFill // used to be .scaleAspectFit imageView.clipsToBounds = true imageView.layer.cornerRadius = 5 imageView.tintColor = .trinidadOrange // Title Label let label = UILabel() addSubview(label) self.titleLabel = label titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.topAnchor.constraint(equalTo: imageView.topAnchor).isActive = true titleLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: standardMargin).isActive = true titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -standardMargin).isActive = true titleLabel.font = titleFont titleLabel.textColor = .tundra titleLabel.numberOfLines = 2 // Author Label let author = UILabel() addSubview(author) self.authorLabel = author authorLabel.translatesAutoresizingMaskIntoConstraints = false authorLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: standardMargin * 0).isActive = true authorLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: standardMargin).isActive = true authorLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -standardMargin).isActive = true authorLabel.numberOfLines = 2 authorLabel.textColor = .tundra authorLabel.font = authorFont // Stars View (5 image view inside) let view = UIView() addSubview(view) self.starsView = view starsView.translatesAutoresizingMaskIntoConstraints = false starsView.topAnchor.constraint(equalTo: authorLabel.bottomAnchor, constant: standardMargin * 0.15).isActive = true // pushed to left by 1 so star point lines up with author name (and so I don't wake up screaming at night) starsView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: standardMargin - 1.0).isActive = true starsView.heightAnchor.constraint(equalTo: titleLabel.heightAnchor).isActive = true starsView.widthAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true // Stars Array (goes inside starsView) let starSize = Int(self.frame.size.height * CGFloat(0.10)) for integer in 1...5 { let star = UIImageView() starsView.addSubview(star) starsArray.append(star) star.tag = integer star.frame = CGRect(x: ((starSize + starSpacing) * (integer - 1)), y: 0, width: starSize, height: starSize) star.image = UIImage(named: "Stars_Chunky-AltoGray") } } }
39.374302
114
0.616771
1464f1ad741a04c8abfca752314d1169a260609a
1,338
import XCTest import CZUtils import CZTestUtils @testable import CZNetworking /** Verify StubSupport. */ final class StubSupportTests: XCTestCase { private enum MockData { static let dictionary: [String: AnyHashable] = [ "a": "sdlfjas", "c": "sdlksdf", "b": "239823sd", "d": 189298723, ] static let array: [AnyHashable] = [ "sdlfjas", "sdlksdf", "239823sd", 189298723, ] } func testStubData() { let (waitForExpectatation, expectation) = CZTestUtils.waitWithInterval(3, testCase: self) // Create mockDataMap. let url = URL(string: "https://www.apple.com/newsroom/rss-feed.rss")! let mockData = CZHTTPJsonSerializer.jsonData(with: MockData.dictionary)! let mockDataMap = [url: mockData] // Fetch with stub URLSession. let session = CZHTTPStub.stubURLSession(mockDataMap: mockDataMap) session.dataTask(with: url) { (data, response, error) in guard let data = data.assertIfNil else { return } let res: [String: AnyHashable]? = CZHTTPJsonSerializer.deserializedObject(with: data) XCTAssert(res == MockData.dictionary, "Actual result = \(res), Expected result = \(MockData.dictionary)") expectation.fulfill() }.resume() // Wait for expectation. waitForExpectatation() } }
27.875
111
0.653214
9b47c59ed737250cc8bd95464d664fc9ea21bfe4
576
// // Matcher.swift // // Created by zhangshumeng on 2018/8/25. // Copyright © 2018年 ZSM. All rights reserved. // import UIKit public enum Matcher: String { case phone = "^1[0-9]{10}$" case email = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$" case password = "^(?=.*[a-zA-Z])(?=.*[0-9]).{8,}$" case number = "^[0-9]+$" case url = "[a-zA-z]+://[^\\s]*" public func evaluate(_ input: String) -> Bool { let predicate = NSPredicate(format: "SELF MATCHES %@", rawValue) return predicate.evaluate(with: input) } }
25.043478
72
0.539931
db96081e5745cb2c732d5f5af22fb6a77642ff69
1,697
// // PatternImage.swift // LightShow // // Created by Guido Westenberg on 11/28/20. // import SwiftUI struct PatternImage: View { var pattern: LightShow.Pattern var body: some View { let width = getSize() let height = (pattern.nframes > 1 ? pattern.nframes : 3)! let rowheight = pattern.nframes > 1 ? 1 : 3 let size = NSSize(width: Int(width), height: height) let renderer = compile2(pattern.id.CString(), pattern.pattern.CString()) let image = NSImage(size: size, flipped: true, drawingHandler: { rect in for row in 0 ..< pattern.nframes { let timestamp = row * (1000 / pattern.framerate) render(renderer, timestamp) for p in 0 ..< width { let rgba = getPixel(p) let r = CGFloat(rgba >> 24 & 0x0ff) / 255.0 let g = CGFloat(rgba >> 16 & 0x0ff) / 255.0 let b = CGFloat(rgba >> 8 & 0x0ff) / 255.0 let a = CGFloat(rgba & 0x0ff) / 255.0 let color = NSColor(red: r, green: g, blue: b, alpha: a) let pixel = NSRect(origin: NSPoint(x: Int(p), y: row), size: NSSize(width: 1, height: rowheight)) color.setFill() pixel.fill() } } return true }) return Image(nsImage: image) } } struct PatternImage_Previews: PreviewProvider { static var previews: some View { let appDelegate = NSApplication.shared.delegate as! AppDelegate let pattern = appDelegate.patterns[0] return PatternImage(pattern: pattern) } }
35.354167
117
0.539187
034d1a12b8cd5b6c984d0634fad367de782bb051
2,579
//===----------------------------------------------------------------------===// // // 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 the list of Swift project authors // //===----------------------------------------------------------------------===// import Lifecycle import LifecycleNIOCompat import Logging import Metrics import NIO import StatsdClient @main enum PackageRegistry { static func main() { let configuration = Configuration() LoggingSystem.bootstrap { label in var logger = StreamLogHandler.standardOutput(label: label) logger.logLevel = configuration.app.logLevel return logger } let logger = Logger(label: "\(PackageRegistry.self)") logger.info("\(configuration)") let lifecycle = ServiceLifecycle() let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) lifecycle.registerShutdown(label: "eventLoopGroup", .sync(eventLoopGroup.syncShutdownGracefully)) let dataAccess = PostgresDataAccess(eventLoopGroup: eventLoopGroup, configuration: configuration.postgres) lifecycle.register(label: "dataAccess", start: .async(dataAccess.migrate), shutdown: .sync(dataAccess.shutdown)) let api = API(configuration: configuration, dataAccess: dataAccess) lifecycle.register(label: "api", start: .sync(api.start), shutdown: .sync(api.shutdown), shutdownIfNotStarted: true) if let metricsPort = configuration.app.metricsPort { logger.info("Bootstrapping statsd client on port \(metricsPort)") if let statsdClient = try? StatsdClient(eventLoopGroupProvider: .shared(eventLoopGroup), host: "localhost", port: metricsPort) { MetricsSystem.bootstrap(statsdClient) lifecycle.registerShutdown(label: "statsd-client", .async(statsdClient.shutdown)) } } lifecycle.start { error in if let error = error { logger.error("Failed starting \(self) ☠️: \(error)") } else { logger.info("\(self) started successfully 🚀") } } lifecycle.wait() } }
39.075758
140
0.597131
082c18c004022b9a0d363cd412d8a5f74c05d007
1,556
import Foundation import XCTest import TestHelper @testable import UhSpotCoreNavigation final class UnimplementedLoggingTests: TestCase { class UnimplementedClass: UnimplementedLogging { func func1() { logUnimplemented(protocolType: self, level: .default) } func func2() { logUnimplemented(protocolType: self, level: .default) } func func3() { logUnimplemented(protocolType: self, level: .default) } } func testUnimplementedLoggingMultithreaded() { let iterations = 100 let iterationsFinished = expectation(description: "Iterations finished") iterationsFinished.expectedFulfillmentCount = iterations let unimplementedClass = UnimplementedClass() DispatchQueue.concurrentPerform(iterations: iterations) { iterationIdx in unimplementedClass.func1() unimplementedClass.func2() unimplementedClass.func3() iterationsFinished.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(_unimplementedLoggingState.countWarned(forTypeDescription: "UnimplementedClass"), 3) } func testUnimplementedLoggingPerformance() { measure { let iterations = 50 for _ in 0..<iterations { let unimplementedClass = UnimplementedClass() unimplementedClass.func1() unimplementedClass.func2() unimplementedClass.func3() } } } }
33.826087
107
0.643959
03b4f4e88730e33ed85436438b1129d9e5b4fb56
1,649
// // NavigationController.swift // CARTE // // Created by tomoki.koga on 2019/06/03. // Copyright © 2019 PLAID, inc. All rights reserved. // import UIKit func navi(_ viewControllers: UIViewController...) -> NavigationController { let navigationController: NavigationController if viewControllers.count == 1 { navigationController = NavigationController(rootViewController: viewControllers[0]) } else { navigationController = NavigationController() navigationController.viewControllers = viewControllers } return navigationController } class NavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() delegate = self if let viewController = viewControllers.last { clearBackBarButtonItemText(viewController) } } } extension NavigationController { private func clearBackBarButtonItemText(_ viewController: UIViewController) { let backBarButtonItem = UIBarButtonItem() backBarButtonItem.title = "" viewController.navigationItem.backBarButtonItem = backBarButtonItem viewController.navigationItem.backBarButtonItem?.isEnabled = true } } extension NavigationController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { clearBackBarButtonItemText(viewController) } func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { } }
30.537037
138
0.733778
f9ea19b884fb3b0eb2b7933762947447c6f4ac0d
4,186
// // Validations.swift // ConstantFramework // // Created by Apple on 28/11/17. // import Foundation import UIKit public class Validations : NSObject{ public static let instance = Validations() public func isRestrictNumberCharacters(string:String)->Bool{ let invalidCharacters = NSCharacterSet(charactersIn: "0123456789").inverted return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil } public func isRestrictAlphaCharacters(string: String) -> Bool { let invalidCharacters = NSCharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").inverted return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil } public func isRestrictEmailWithAtTheRateCharacters(string: String) -> Bool { let invalidCharacters = NSCharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_-.@").inverted return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil } public func isRestrictEmailWithoutAtTheRateCharacters(string: String) -> Bool { let invalidCharacters = NSCharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_-.").inverted return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil } public func isRestrictAlphaNumericCharacters(string: String) -> Bool { let invalidCharacters = NSCharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,#. ").inverted return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil } public func isRestrictCityCharacters(string: String) -> Bool { let invalidCharacters = NSCharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 ").inverted return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil } public func isRestrictAddressCharacters(string: String) -> Bool { let invalidCharacters = NSCharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_-. /\\|,:'").inverted return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil } public func onlyNumeric(persistanceTextString:String,maximumTextLength:Int) -> Bool { var returnValue = false if (persistanceTextString.characters.count>maximumTextLength) { return false } if (persistanceTextString.characters.count==1 && persistanceTextString == "0") { return false } else { let alphaNum = "[0-9]+" let regexTest = NSPredicate(format: "SELF MATCHES %@", alphaNum) if (regexTest.evaluate(with: persistanceTextString)==false) { if (persistanceTextString.characters.count==0) { return true } returnValue = false } else { returnValue = true } } return returnValue } public func onlyAlphabets(persistanceTextString:String,maximumTextLength:Int) -> Bool { var returnValue = false if (persistanceTextString.characters.count>maximumTextLength) { return false } let alphaNum = "[a-zA-Z]+" let regexTest = NSPredicate(format: "SELF MATCHES %@", alphaNum) if (regexTest.evaluate(with: persistanceTextString)==false) { if (persistanceTextString.characters.count==0) { return true } returnValue = false } else { returnValue = true } return returnValue } }
39.866667
146
0.661252
fcdf4d7f86a21bd74c48fac956efb6fcf86d70e1
1,666
// TorThread.swift // // Copyright (c) 2013 Claudiu-Vlad Ursache. // See LICENCE for licensing information // import Foundation class TorThread: Thread { var configuration: TorConfiguration let kTorArgsValueIsolateDestPort = "IsolateDestPort" let kTorArgsValueIsolateDestAddr = "IsolateDestAddr" let kTorArgsKeyARG0 = "tor" let kTorArgsKeyDataDirectory = "DataDirectory" let kTorArgsKeyControlPort = "ControlPort" let kTorArgsKeyKeySOCKSPort = "SocksPort" let kTorArgsKeyGeoIPFile = "GeoIPFile" let kTorArgsKeyTorrcFile = "-f" let kTorArgsKeyLog = "Log" #if DEBUG let kTorArgsValueLogLevel = "warn stderr" #else let kTorArgsValueLogLevel = "notice stderr" #endif init(configuration: TorConfiguration) { self.configuration = configuration super.init() } override func main() { var socksPort = "localhost:\(configuration.socksPort)" if configuration.isolateDestinationAddress { socksPort += " " + kTorArgsValueIsolateDestAddr } if configuration.isolateDestinationPort { socksPort += " " + kTorArgsValueIsolateDestPort } let params = [kTorArgsKeyARG0, kTorArgsKeyDataDirectory, configuration.torDataDirectoryPath, kTorArgsKeyControlPort, "\(configuration.controlPort)", kTorArgsKeyKeySOCKSPort, socksPort, kTorArgsKeyGeoIPFile, configuration.geoipPath, kTorArgsKeyTorrcFile, configuration.torrcPath, kTorArgsKeyLog, kTorArgsValueLogLevel] TorMain(params as [Any]) } }
32.666667
83
0.666867
dddb1b3e19d8ba274179058e6da20e2651f36825
1,746
// // Copyright © 2021 Jesús Alfredo Hernández Alarcón. All rights reserved. // import Foundation final class URLProtocolStub: URLProtocol { private struct Stub { let data: Data? let response: URLResponse? let error: Error? let requestObserver: ((URLRequest) -> Void)? } private static var _stub: Stub? private static var stub: Stub? { get { queue.sync { _stub } } set { queue.sync { _stub = newValue } } } private static let queue = DispatchQueue(label: "URLProtocolStub.queue") static func stub(data: Data?, response: URLResponse?, error: Error?) { stub = Stub(data: data, response: response, error: error, requestObserver: nil) } static func observeRequests(observer: @escaping (URLRequest) -> Void) { stub = Stub(data: nil, response: nil, error: nil, requestObserver: observer) } static func removeStub() { stub = nil } override class func canInit(with _: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { guard let stub = URLProtocolStub.stub else { return } if let data = stub.data { client?.urlProtocol(self, didLoad: data) } if let response = stub.response { client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } if let error = stub.error { client?.urlProtocol(self, didFailWithError: error) } else { client?.urlProtocolDidFinishLoading(self) } stub.requestObserver?(request) } override func stopLoading() {} }
26.861538
92
0.617984
767aa8a89047459b377eb32ed7a1e2fb339642dc
3,775
// // ListagemViewController.swift // LinkHub // // Created by Student on 12/15/15. // Copyright © 2015 Student. All rights reserved. // import UIKit import CoreData class ListagemViewController: UIViewController, UITableViewDataSource , NSFetchedResultsControllerDelegate { @IBOutlet weak var mLabel: UINavigationItem! @IBOutlet weak var listaLinks: UITableView! var pasta: Pasta? = nil @IBOutlet weak var nomePasta: UILabel! let contexto = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController() override func viewDidLoad() { super.viewDidLoad() self.listaLinks.dataSource = self fetchedResultController = getFetchedResultController() fetchedResultController.delegate = self do{ try fetchedResultController.performFetch() } catch let error as NSError{ print("Erro ao buscar tarefas: \(error), \(error.userInfo)") } self.mLabel.title = pasta?.nome } func getFetchedResultController() -> NSFetchedResultsController { fetchedResultController = NSFetchedResultsController(fetchRequest: linkFetchRequest(), managedObjectContext: contexto, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultController } func linkFetchRequest() -> NSFetchRequest { let fetchRequest = NSFetchRequest(entityName: "Link") let sortDescription = NSSortDescriptor(key: "url", ascending: true) let filter = pasta let predicate = NSPredicate(format: "pasta = %@", filter!) fetchRequest.predicate = predicate fetchRequest.sortDescriptors = [sortDescription] return fetchRequest } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { let numberOfSections = fetchedResultController.sections?.count return numberOfSections! } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects return numberOfRowsInSection! } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellLink") as! TableViewCell let link = fetchedResultController.objectAtIndexPath(indexPath) as! Link cell.linkLabel?.text = link.url return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { let manageObject:NSManagedObject = fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject contexto.deleteObject(manageObject) do { try contexto.save() } catch _ { print("Erro ao deletar link") } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "mostrarTelaLink" { let listagemController: LinkDetailViewController = segue.destinationViewController as! LinkDetailViewController listagemController.pasta = pasta } } func controllerDidChangeContent(controller: NSFetchedResultsController) { listaLinks.reloadData() } }
37.376238
167
0.701192
7aaae62619a301675afdeb2bcc82a29c4ecdb5b1
10,240
// // YPImagePickerConfiguration.swift // YPImagePicker // // Created by Sacha DSO on 18/10/2017. // Copyright © 2016 Yummypets. All rights reserved. // import Foundation import AVFoundation import UIKit import Photos /// Typealias for code prettiness internal var YPConfig: YPImagePickerConfiguration { return YPImagePickerConfiguration.shared } public struct YPImagePickerConfiguration { public static var shared: YPImagePickerConfiguration = YPImagePickerConfiguration() public init() {} /// Edit photo or video as full page , defaults to true public var fullEditingMode = false /// Scroll to change modes, defaults to true public var isScrollToChangeModesEnabled = true // Library configuration public var library = YPConfigLibrary() // Video configuration public var video = YPConfigVideo() // Gallery configuration public var gallery = YPConfigSelectionsGallery() /// Use this property to modify the default wordings provided. public var wordings = YPWordings() /// Use this property to modify the default icons provided. public var icons = YPIcons() /// Use this property to modify the default colors provided. public var colors = YPColors() /// Set this to true if you want to force the camera output to be a squared image. Defaults to true public var onlySquareImagesFromCamera = true /// Enables selecting the front camera by default, useful for avatars. Defaults to false public var usesFrontCamera = false /// Adds a Filter step in the photo taking process. Defaults to true public var showsPhotoFilters = true /// Adds a Video Trimmer step in the video taking process. Defaults to true public var showsVideoTrimmer = true /// Enables you to opt out from saving new (or old but filtered) images to the /// user's photo library. Defaults to true. public var shouldSaveNewPicturesToAlbum = true /// Defines the name of the album when saving pictures in the user's photo library. /// In general that would be your App name. Defaults to "DefaultYPImagePickerAlbumName" public var albumName = "DefaultYPImagePickerAlbumName" /// Defines which screen is shown at launch. Video mode will only work if `showsVideo = true`. /// Default value is `.photo` public var startOnScreen: YPPickerScreen = .photo /// Defines which screens are shown at launch, and their order. /// Default value is `[.library, .photo]` public var screens: [YPPickerScreen] = [.library, .photo] /// Adds a Crop step in the photo taking process, after filters. Defaults to .none public var showsCrop: YPCropType = .none /// Ex: cappedTo:1024 will make sure images from the library or the camera will be /// resized to fit in a 1024x1024 box. Defaults to original image size. public var targetImageSize = YPImageSize.original /// Adds a Overlay View to the camera public var overlayView: UIView? /// Defines if the status bar should be hidden when showing the picker. Default is true public var hidesStatusBar = true /// Defines if the bottom bar should be hidden when showing the picker. Default is false. public var hidesBottomBar = false /// Defines if the navigation bar should be hidden when showing the picker. Default is false. public var hidesNavigationBar = false /// Defines the preferredStatusBarAppearance public var preferredStatusBarStyle = UIStatusBarStyle.default /// Defines the text colour to be shown when a bottom option is selected public var bottomMenuItemSelectedTextColour: UIColor = .ypLabel /// Defines the text colour to be shown when a bottom option is unselected public var bottomMenuItemUnSelectedTextColour: UIColor = .ypSecondaryLabel /// Defines the max camera zoom factor for camera. Disable camera zoom with 1. Default is 1. public var maxCameraZoomFactor: CGFloat = 1.0 /// List of default filters which will be added on the filter screen public var filters: [YPFilter] = [ YPFilter(name: "Normal", applier: nil), YPFilter(name: "Nashville", applier: YPFilter.nashvilleFilter), YPFilter(name: "Toaster", applier: YPFilter.toasterFilter), YPFilter(name: "1977", applier: YPFilter.apply1977Filter), YPFilter(name: "Clarendon", applier: YPFilter.clarendonFilter), YPFilter(name: "HazeRemoval", applier: YPFilter.hazeRemovalFilter), YPFilter(name: "Chrome", coreImageFilterName: "CIPhotoEffectChrome"), YPFilter(name: "Fade", coreImageFilterName: "CIPhotoEffectFade"), YPFilter(name: "Instant", coreImageFilterName: "CIPhotoEffectInstant"), YPFilter(name: "Mono", coreImageFilterName: "CIPhotoEffectMono"), YPFilter(name: "Noir", coreImageFilterName: "CIPhotoEffectNoir"), YPFilter(name: "Process", coreImageFilterName: "CIPhotoEffectProcess"), YPFilter(name: "Tonal", coreImageFilterName: "CIPhotoEffectTonal"), YPFilter(name: "Transfer", coreImageFilterName: "CIPhotoEffectTransfer"), YPFilter(name: "Tone", coreImageFilterName: "CILinearToSRGBToneCurve"), YPFilter(name: "Linear", coreImageFilterName: "CISRGBToneCurveToLinear"), YPFilter(name: "Sepia", coreImageFilterName: "CISepiaTone"), ] /// Migration @available(iOS, obsoleted: 3.0.0, renamed: "video.compression") public var videoCompression: String = AVAssetExportPresetHighestQuality @available(iOS, obsoleted: 3.0.0, renamed: "video.fileType") public var videoExtension: AVFileType = .mov @available(iOS, obsoleted: 3.0.0, renamed: "video.recordingTimeLimit") public var videoRecordingTimeLimit: TimeInterval = 60.0 @available(iOS, obsoleted: 3.0.0, renamed: "video.libraryTimeLimit") public var videoFromLibraryTimeLimit: TimeInterval = 60.0 @available(iOS, obsoleted: 3.0.0, renamed: "video.minimumTimeLimit") public var videoMinimumTimeLimit: TimeInterval = 3.0 @available(iOS, obsoleted: 3.0.0, renamed: "video.trimmerMaxDuration") public var trimmerMaxDuration: Double = 60.0 @available(iOS, obsoleted: 3.0.0, renamed: "video.trimmerMinDuration") public var trimmerMinDuration: Double = 3.0 @available(iOS, obsoleted: 3.0.0, renamed: "library.onlySquare") public var onlySquareImagesFromLibrary = false @available(iOS, obsoleted: 3.0.0, renamed: "library.onlySquare") public var onlySquareFromLibrary = false @available(iOS, obsoleted: 3.0.0, renamed: "targetImageSize") public var libraryTargetImageSize = YPImageSize.original @available(iOS, obsoleted: 3.0.0, renamed: "library.mediaType") public var showsVideoInLibrary = false @available(iOS, obsoleted: 3.0.0, renamed: "library.mediaType") public var libraryMediaType = YPlibraryMediaType.photo @available(iOS, obsoleted: 3.0.0, renamed: "library.maxNumberOfItems") public var maxNumberOfItems = 1 } /// Encapsulates library specific settings. public struct YPConfigLibrary { public var options: PHFetchOptions? = nil /// Set this to true if you want to force the library output to be a squared image. Defaults to false. public var onlySquare = false /// Sets the cropping style to square or not. Ignored if `onlySquare` is true. Defaults to true. public var isSquareByDefault = true /// Minimum width, to prevent selectiong too high images. Have sense if onlySquare is true and the image is portrait. public var minWidthForItem: CGFloat? /// Choose what media types are available in the library. Defaults to `.photo` public var mediaType = YPlibraryMediaType.photo /// Initial state of multiple selection button. public var defaultMultipleSelection = false /// Anything superior than 1 will enable the multiple selection feature. public var maxNumberOfItems = 1 /// Anything greater than 1 will desactivate live photo and video modes (library only) and // force users to select at least the number of items defined. public var minNumberOfItems = 1 /// Set the number of items per row in collection view. Defaults to 4. public var numberOfItemsInRow: Int = 4 /// Set the spacing between items in collection view. Defaults to 1.0. public var spacingBetweenItems: CGFloat = 1.0 /// Allow to skip the selections gallery when selecting the multiple media items. Defaults to false. public var skipSelectionsGallery = false /// Allow to preselected media items public var preselectedItems: [YPMediaItem]? } /// Encapsulates video specific settings. public struct YPConfigVideo { /// Choose the videoCompression. Defaults to AVAssetExportPresetHighestQuality public var compression: String = AVAssetExportPresetHighestQuality /// Choose the result video extension if you trim or compress a video. Defaults to mov. public var fileType: AVFileType = .mov /// Defines the time limit for recording videos. /// Default is 60 seconds. public var recordingTimeLimit: TimeInterval = 60.0 /// Defines the time limit for videos from the library. /// Defaults to 60 seconds. public var libraryTimeLimit: TimeInterval = 60.0 /// Defines the minimum time for the video /// Defaults to 3 seconds. public var minimumTimeLimit: TimeInterval = 3.0 /// The maximum duration allowed for the trimming. Change it before setting the asset, as the asset preview public var trimmerMaxDuration: Double = 60.0 /// The minimum duration allowed for the trimming. /// The handles won't pan further if the minimum duration is attained. public var trimmerMinDuration: Double = 3.0 } /// Encapsulates gallery specific settings. public struct YPConfigSelectionsGallery { /// Defines if the remove button should be hidden when showing the gallery. Default is true. public var hidesRemoveButton = true } public enum YPlibraryMediaType { case photo case video case photoAndVideo }
41.124498
121
0.71123
910610080690dcdbeea409cb651d618b50ad7e85
161
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(FakeSwiftUITests.allTests), ] } #endif
16.1
45
0.677019
ebc43580f15be61cd9618787a6acaadabda7d228
275
import XCTest @testable import YandexCheckoutShowcaseApi import YandexMoneyTestInstrumentsApi final class EmailControlMappingTests: MappingApiMethods { func testMapping() { checkApiMethodsParameters(EmailControl.self, fileName: "EmailControl", index: 0) } }
25
88
0.796364
fb34c89fa38769e0873784ce2c5345c8db78b073
3,039
import Perception /// The classic **SET** game play. 81 cards, 12 cards on the board. public class TraditionalGame: Game, Codable { public enum Error: Swift.Error { case gameOver case deal(cardsRequested: Int, cardsAvailable: Int) case cardNotPlayable(Card) } static let cardsRequiredToStart: Int = 12 static let cardsDealtEachRound: Int = 3 public internal(set) var deck: [Card] = Card.makeDeck() public internal(set) var board: [Card] = [] public internal(set) var discard: [Card] = [] public internal(set) var selected: [Card] = [] public init() { } public func shuffle() { deck = Card.makeDeck().shuffled() board = [] discard = [] selected = [] } public func deal() throws { guard !gameOver else { throw Error.gameOver } let triads = availablePlays let hasPlays = !triads.isEmpty let hasEnoughCards = board.count >= Self.cardsRequiredToStart if hasPlays && hasEnoughCards { return } let cardsToDeal = max(Self.cardsRequiredToStart - board.count, Self.cardsDealtEachRound) guard deck.count >= cardsToDeal else { // Endgame conditions guard hasPlays else { // Not sure this is even possible, but it protects against the handling below. throw Error.deal(cardsRequested: cardsToDeal, cardsAvailable: deck.count) } return } let draw = Array(deck.prefix(cardsToDeal)) board.append(contentsOf: draw) deck.removeFirst(cardsToDeal) // Recursively called to handle the special condition where a standard draw // does not provide the game with any additional sets/triads. try deal() } public func play(_ card: Card) throws { guard board.contains(card) else { throw Error.cardNotPlayable(card) } // If previously selected, deselect. if let idx = selected.firstIndex(of: card) { selected.remove(at: idx) return } selected.append(card) guard selected.count == Triad.cardsRequired else { return } do { try Triad.validate(cards: selected) } catch { selected.removeAll() throw error } discard.append(contentsOf: selected) board.removeAll(where: { selected.contains($0) }) selected.removeAll() } /// Returns the discarded cards to the deck (infinite play) public func reshuffleDiscard() { deck.append(contentsOf: discard) discard.removeAll() deck.shuffle() } } public extension TraditionalGame { var availablePlays: [Triad] { Triad.triads(in: board) } var gameOver: Bool { deck.isEmpty && availablePlays.isEmpty } }
29.221154
96
0.572886
71a60eacba7216e261b2b8335135cde1a22497d3
2,383
// // ImagePickerController.swift // RxExample // // Created by Segii Shulga on 1/5/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class ImagePickerController: ViewController { @IBOutlet var imageView: UIImageView! @IBOutlet var cameraButton: UIButton! @IBOutlet var galleryButton: UIButton! @IBOutlet var cropButton: UIButton! override func viewDidLoad() { super.viewDidLoad() cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) cameraButton.rx.tap .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(self) { picker in picker.sourceType = .camera picker.allowsEditing = false } .flatMap { $0.rx.didFinishPickingMediaWithInfo } .take(1) } .map { info in return info[UIImagePickerControllerOriginalImage] as? UIImage } .bindTo(imageView.rx.image) .disposed(by: disposeBag) galleryButton.rx.tap .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(self) { picker in picker.sourceType = .photoLibrary picker.allowsEditing = false } .flatMap { $0.rx.didFinishPickingMediaWithInfo } .take(1) } .map { info in return info[UIImagePickerControllerOriginalImage] as? UIImage } .bindTo(imageView.rx.image) .disposed(by: disposeBag) cropButton.rx.tap .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(self) { picker in picker.sourceType = .photoLibrary picker.allowsEditing = true } .flatMap { $0.rx.didFinishPickingMediaWithInfo } .take(1) } .map { info in return info[UIImagePickerControllerEditedImage] as? UIImage } .bindTo(imageView.rx.image) .disposed(by: disposeBag) } }
30.948052
87
0.55812
e607b8d2ff2f9a73367c5fb9a7daa540e6bed215
1,614
// // CacheManager.swift // BlockEQ // // Created by Nick DiZazzo on 2019-01-15. // Copyright © 2019 BlockEQ. All rights reserved. // import Cache import Imaginary import StellarHub final class CacheManager { static let shared = CacheManager() let images = Configuration.imageStorage var qrCodes: Storage<Image> = { let diskConfig = DiskConfig(name: "QRCodes") let memoryConfig = MemoryConfig(expiry: .never) do { return try Storage<Image>(diskConfig: diskConfig, memoryConfig: memoryConfig, transformer: TransformerFactory.forImage()) } catch { fatalError(error.localizedDescription) } }() private init() { } static func prefetchAssetImages() { let queue = OperationQueue() queue.qualityOfService = .userInitiated let codes = AssetMetadata.staticAssetCodes + AssetMetadata.commonAssetCodes let fetchOperation = FetchAssetIconsOperation(assetCodes: codes) queue.addOperation(fetchOperation) } static func cacheAccountQRCode(_ account: StellarAccount) { let queue = OperationQueue() queue.qualityOfService = .userInitiated let qrCodeOperation = CacheAccountQROperation(accountId: account.accountId) queue.addOperation(qrCodeOperation) } func clearAll() { clearShared() clearAccountCache() } func clearShared() { try? images.removeAll() } func clearAccountCache() { try? qrCodes.removeAll() } }
25.619048
83
0.63197
5b716fc730256c4e12f749632a12b0e2ac5d9af7
127
import XCTest import BinaryTargetTests var tests = [XCTestCaseEntry]() tests += PackageTargetTests.allTests() XCTMain(tests)
15.875
38
0.795276
1a485e7be42e535172495e0f35150af244a7fa02
12,080
// swiftlint:disable all // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen #if os(macOS) import AppKit #elseif os(iOS) import UIKit #elseif os(tvOS) || os(watchOS) import UIKit #endif // Deprecated typealiases @available(*, deprecated, renamed: "ImageAsset.Image", message: "This typealias will be removed in SwiftGen 7.0") internal typealias AssetImageTypeAlias = ImageAsset.Image // swiftlint:disable superfluous_disable_command file_length implicit_return // MARK: - Asset Catalogs // swiftlint:disable identifier_name line_length nesting type_body_length type_name internal enum Asset { internal enum Images { internal static let socialLoginButtonApple = ImageAsset(name: "social_login_button_apple") internal static let socialLoginButtonFacebook = ImageAsset(name: "social_login_button_facebook") internal static let socialLoginButtonGithub = ImageAsset(name: "social_login_button_github") internal static let socialLoginButtonGitlab = ImageAsset(name: "social_login_button_gitlab") internal static let socialLoginButtonGoogle = ImageAsset(name: "social_login_button_google") internal static let socialLoginButtonTwitter = ImageAsset(name: "social_login_button_twitter") internal static let callAudioMuteOffIcon = ImageAsset(name: "call_audio_mute_off_icon") internal static let callAudioMuteOnIcon = ImageAsset(name: "call_audio_mute_on_icon") internal static let callChatIcon = ImageAsset(name: "call_chat_icon") internal static let callHangupLarge = ImageAsset(name: "call_hangup_large") internal static let callSpeakerOffIcon = ImageAsset(name: "call_speaker_off_icon") internal static let callSpeakerOnIcon = ImageAsset(name: "call_speaker_on_icon") internal static let callVideoMuteOffIcon = ImageAsset(name: "call_video_mute_off_icon") internal static let callVideoMuteOnIcon = ImageAsset(name: "call_video_mute_on_icon") internal static let callkitIcon = ImageAsset(name: "callkit_icon") internal static let cameraSwitch = ImageAsset(name: "camera_switch") internal static let appSymbol = ImageAsset(name: "app_symbol") internal static let backIcon = ImageAsset(name: "back_icon") internal static let camera = ImageAsset(name: "camera") internal static let checkmark = ImageAsset(name: "checkmark") internal static let chevron = ImageAsset(name: "chevron") internal static let closeButton = ImageAsset(name: "close_button") internal static let disclosureIcon = ImageAsset(name: "disclosure_icon") internal static let faceidIcon = ImageAsset(name: "faceid_icon") internal static let group = ImageAsset(name: "group") internal static let monitor = ImageAsset(name: "monitor") internal static let placeholder = ImageAsset(name: "placeholder") internal static let plusIcon = ImageAsset(name: "plus_icon") internal static let removeIcon = ImageAsset(name: "remove_icon") internal static let revealPasswordButton = ImageAsset(name: "reveal_password_button") internal static let selectionTick = ImageAsset(name: "selection_tick") internal static let selectionUntick = ImageAsset(name: "selection_untick") internal static let shareActionButton = ImageAsset(name: "share_action_button") internal static let shrinkIcon = ImageAsset(name: "shrink_icon") internal static let smartphone = ImageAsset(name: "smartphone") internal static let startChat = ImageAsset(name: "start_chat") internal static let touchidIcon = ImageAsset(name: "touchid_icon") internal static let addGroupParticipant = ImageAsset(name: "add_group_participant") internal static let removeIconBlue = ImageAsset(name: "remove_icon_blue") internal static let captureAvatar = ImageAsset(name: "capture_avatar") internal static let e2eBlocked = ImageAsset(name: "e2e_blocked") internal static let e2eUnencrypted = ImageAsset(name: "e2e_unencrypted") internal static let e2eWarning = ImageAsset(name: "e2e_warning") internal static let encryptionNormal = ImageAsset(name: "encryption_normal") internal static let encryptionTrusted = ImageAsset(name: "encryption_trusted") internal static let encryptionWarning = ImageAsset(name: "encryption_warning") internal static let favouritesEmptyScreenArtwork = ImageAsset(name: "favourites_empty_screen_artwork") internal static let favouritesEmptyScreenArtworkDark = ImageAsset(name: "favourites_empty_screen_artwork_dark") internal static let roomActionDirectChat = ImageAsset(name: "room_action_direct_chat") internal static let roomActionFavourite = ImageAsset(name: "room_action_favourite") internal static let roomActionLeave = ImageAsset(name: "room_action_leave") internal static let roomActionNotification = ImageAsset(name: "room_action_notification") internal static let roomActionPriorityHigh = ImageAsset(name: "room_action_priority_high") internal static let roomActionPriorityLow = ImageAsset(name: "room_action_priority_low") internal static let homeEmptyScreenArtwork = ImageAsset(name: "home_empty_screen_artwork") internal static let homeEmptyScreenArtworkDark = ImageAsset(name: "home_empty_screen_artwork_dark") internal static let plusFloatingAction = ImageAsset(name: "plus_floating_action") internal static let closeBanner = ImageAsset(name: "close_banner") internal static let importFilesButton = ImageAsset(name: "import_files_button") internal static let keyBackupLogo = ImageAsset(name: "key_backup_logo") internal static let keyVerificationSuccessShield = ImageAsset(name: "key_verification_success_shield") internal static let oldLogo = ImageAsset(name: "old_logo") internal static let cameraCapture = ImageAsset(name: "camera_capture") internal static let cameraPlay = ImageAsset(name: "camera_play") internal static let cameraStop = ImageAsset(name: "camera_stop") internal static let cameraVideoCapture = ImageAsset(name: "camera_video_capture") internal static let videoIcon = ImageAsset(name: "video_icon") internal static let peopleEmptyScreenArtwork = ImageAsset(name: "people_empty_screen_artwork") internal static let peopleEmptyScreenArtworkDark = ImageAsset(name: "people_empty_screen_artwork_dark") internal static let peopleFloatingAction = ImageAsset(name: "people_floating_action") internal static let error = ImageAsset(name: "error") internal static let scrolldown = ImageAsset(name: "scrolldown") internal static let typing = ImageAsset(name: "typing") internal static let roomContextMenuCopy = ImageAsset(name: "room_context_menu_copy") internal static let roomContextMenuEdit = ImageAsset(name: "room_context_menu_edit") internal static let roomContextMenuMore = ImageAsset(name: "room_context_menu_more") internal static let roomContextMenuReply = ImageAsset(name: "room_context_menu_reply") internal static let uploadIcon = ImageAsset(name: "upload_icon") internal static let voiceCallHangonIcon = ImageAsset(name: "voice_call_hangon_icon") internal static let voiceCallHangupIcon = ImageAsset(name: "voice_call_hangup_icon") internal static let addMemberFloatingAction = ImageAsset(name: "add_member_floating_action") internal static let addParticipant = ImageAsset(name: "add_participant") internal static let detailsIcon = ImageAsset(name: "details_icon") internal static let editIcon = ImageAsset(name: "edit_icon") internal static let integrationsIcon = ImageAsset(name: "integrations_icon") internal static let mainAliasIcon = ImageAsset(name: "main_alias_icon") internal static let membersListIcon = ImageAsset(name: "members_list_icon") internal static let modIcon = ImageAsset(name: "mod_icon") internal static let moreReactions = ImageAsset(name: "more_reactions") internal static let scrollup = ImageAsset(name: "scrollup") internal static let roomsEmptyScreenArtwork = ImageAsset(name: "rooms_empty_screen_artwork") internal static let roomsEmptyScreenArtworkDark = ImageAsset(name: "rooms_empty_screen_artwork_dark") internal static let roomsFloatingAction = ImageAsset(name: "rooms_floating_action") internal static let userIcon = ImageAsset(name: "user_icon") internal static let fileDocIcon = ImageAsset(name: "file_doc_icon") internal static let fileMusicIcon = ImageAsset(name: "file_music_icon") internal static let filePhotoIcon = ImageAsset(name: "file_photo_icon") internal static let fileVideoIcon = ImageAsset(name: "file_video_icon") internal static let searchBg = ImageAsset(name: "search_bg") internal static let searchIcon = ImageAsset(name: "search_icon") internal static let secretsRecoveryKey = ImageAsset(name: "secrets_recovery_key") internal static let secretsRecoveryPassphrase = ImageAsset(name: "secrets_recovery_passphrase") internal static let secretsSetupKey = ImageAsset(name: "secrets_setup_key") internal static let secretsSetupPassphrase = ImageAsset(name: "secrets_setup_passphrase") internal static let secretsResetWarning = ImageAsset(name: "secrets_reset_warning") internal static let removeIconPink = ImageAsset(name: "remove_icon_pink") internal static let settingsIcon = ImageAsset(name: "settings_icon") internal static let splashBackground = ImageAsset(name: "Splash-Background") internal static let tabFavourites = ImageAsset(name: "tab_favourites") internal static let tabGroups = ImageAsset(name: "tab_groups") internal static let tabHome = ImageAsset(name: "tab_home") internal static let tabPeople = ImageAsset(name: "tab_people") internal static let tabRooms = ImageAsset(name: "tab_rooms") internal static let exit = ImageAsset(name: "exit") internal static let menu = ImageAsset(name: "menu") internal static let roleOutline = ImageAsset(name: "role_outline") internal static let work = ImageAsset(name: "work") internal static let launchScreenLogo = ImageAsset(name: "launch_screen_logo") internal static let lingoLogoDark = ImageAsset(name: "lingo_logo_dark") internal static let logoTransparent = ImageAsset(name: "logo_transparent") internal static let riotSplash0Blue = ImageAsset(name: "riot_splash_0_blue") } internal enum SharedImages { internal static let cancel = ImageAsset(name: "cancel") internal static let e2eVerified = ImageAsset(name: "e2e_verified") internal static let horizontalLogo = ImageAsset(name: "horizontal_logo") } } // swiftlint:enable identifier_name line_length nesting type_body_length type_name // MARK: - Implementation Details internal struct ImageAsset { internal fileprivate(set) var name: String #if os(macOS) internal typealias Image = NSImage #elseif os(iOS) || os(tvOS) || os(watchOS) internal typealias Image = UIImage #endif internal var image: Image { let bundle = BundleToken.bundle #if os(iOS) || os(tvOS) let image = Image(named: name, in: bundle, compatibleWith: nil) #elseif os(macOS) let name = NSImage.Name(self.name) let image = (bundle == .main) ? NSImage(named: name) : bundle.image(forResource: name) #elseif os(watchOS) let image = Image(named: name) #endif guard let result = image else { fatalError("Unable to load image named \(name).") } return result } } internal extension ImageAsset.Image { @available(macOS, deprecated, message: "This initializer is unsafe on macOS, please use the ImageAsset.image property") convenience init!(asset: ImageAsset) { #if os(iOS) || os(tvOS) let bundle = BundleToken.bundle self.init(named: asset.name, in: bundle, compatibleWith: nil) #elseif os(macOS) self.init(named: NSImage.Name(asset.name)) #elseif os(watchOS) self.init(named: asset.name) #endif } } // swiftlint:disable convenience_type private final class BundleToken { static let bundle: Bundle = { #if SWIFT_PACKAGE return Bundle.module #else return Bundle(for: BundleToken.self) #endif }() } // swiftlint:enable convenience_type
58.357488
115
0.771606
fe768308a4b61b7e0ab0b02cca11cca45fd5c000
244
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing private let b { protocol b { func g<Int>: b } protocol b { typealias b : b
22.181818
87
0.737705
72c2c747de3a272e811cf8319cdd16ed812ddfbf
4,580
// // BooksViewController.swift // Open Book // // Created by martin chibwe on 7/21/16. // Copyright © 2016 martin chibwe. All rights reserved. // import UIKit import CoreData class BooksViewController: UIViewController { var managedObjectContext: NSManagedObjectContext! lazy var booksController: NSFetchedResultsController = { let request = NSFetchRequest(entityName: Book.entityName) let titleDescriptor = NSSortDescriptor(key: "title", ascending: true) request.sortDescriptors = [titleDescriptor] let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) try! controller.performFetch() controller.delegate = self return controller }() @IBOutlet weak var collectionView: UICollectionView! @IBAction func removeAllBooks() { guard let books = booksController.sections?[0].objects as? [Book] where books.count > 0 else { return } for book in books { managedObjectContext.deleteObject(book) } try! managedObjectContext.save() } typealias EmptyBlock = () -> () private var updates = [EmptyBlock]() } extension BooksViewController: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return booksController.sections?[section].numberOfObjects ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! BookCell guard let book = booksController.sections?[indexPath.section].objects?[indexPath.row] as? Book else { fatalError("Cannot get book") } cell.titleView.text = book.title if let imageData = book.cover { cell.coverView.image = UIImage(data: imageData) } if case let .InProgress(_, totalBytes, bytesRead) = book.state { let progress: Float = { if totalBytes > 0 { return Float(bytesRead) / Float(totalBytes) } else { return 0 } }() cell.progressView.progress = progress cell.progressView.hidden = false } else { cell.progressView.hidden = true } return cell } } extension BooksViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { updates.removeAll() } func controllerDidChangeContent(controller: NSFetchedResultsController) { let updatesBlock = { for update in self.updates { update() } } collectionView.performBatchUpdates(updatesBlock, completion: nil) updates.removeAll() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { let collectionView = self.collectionView updates.append({ switch type { case .Insert: return { collectionView.insertItemsAtIndexPaths([newIndexPath!]) } case .Update: return { collectionView.reloadItemsAtIndexPaths([indexPath!]) } case .Delete: return { collectionView.deleteItemsAtIndexPaths([indexPath!]) } case .Move: return { collectionView.deleteItemsAtIndexPaths([indexPath!]) collectionView.insertItemsAtIndexPaths([newIndexPath!]) } } }()) } } class BookCell: UICollectionViewCell { @IBOutlet weak var coverView: UIImageView! @IBOutlet weak var titleView: UILabel! @IBOutlet weak var progressView: UIProgressView! override func awakeFromNib() { super.awakeFromNib() coverView.layer.borderColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.5).CGColor coverView.layer.borderWidth = 1.0 } }
33.188406
211
0.616157
f7b3bcfa13f0247bf180e96527f8343fa4521315
1,665
extension File { convenience public init<T>(name: T, at path: Path) throws where T: StringProtocol { try self.init(name: .init(name), at: path) } convenience public init<T, U>(name: T, at path: U) throws where T: StringProtocol, U: StringProtocol { try self.init(name: .init(name), at: .init(path)) } convenience public init(at path: Path) throws { var path = path guard let name = path.deleteLastComponent() else { throw Error.invalidPath } try self.init(name: .init(name), at: path) } convenience public init<T: StringProtocol>(at path: T) throws { try self.init(at: .init(path)) } } // MARK: API extension File { public func rename<T: StringProtocol>(to name: T) throws { try rename(to: .init(name)) } } // MARK: Static API extension File { public static func isExists<T, U>(name: T, at path: U) throws -> Bool where T: StringProtocol, U: StringProtocol { try File.isExists(name: .init(name), at: .init(path)) } public static func isExists<T: StringProtocol>(at path: T) throws -> Bool { try File.isExists(at: .init(path)) } public static func remove<T: StringProtocol>(at path: T) throws { try File.remove(at: .init(path)) } public static func rename<OldName, NewName, Path>( _ old: OldName, to new: NewName, at path: Path) throws where OldName: StringProtocol, NewName: StringProtocol, Path: StringProtocol { try File.rename(.init(old), to: .init(new), at: .init(path)) } }
25.227273
79
0.592793
18449dfad0411ab9d826ccc218c7d18cb20cbd24
239
// // DexcomG6SensorDataTxMessageTests.swift // xDripTests // // Created by Artem Kalmykov on 04.04.2020. // Copyright © 2020 Faifly. All rights reserved. // import XCTest final class DexcomG6SensorDataTxMessageTests: XCTestCase { }
18.384615
58
0.748954
333717067a0113a89f29ed70c6c9e320eefab819
2,202
/// Copyright (c) 2021 Razeware LLC /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// 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 SwiftUI struct ContentView: View { var body: some View { GeometryReader { proxy in Image("Catground") .resizable() .scaledToFit() .overlay( Image("Badge") .resizable() .scaledToFit() .frame(width: proxy.size.width / 3) .padding(-proxy.size.width / 30), alignment: .bottomTrailing ) } .frame(width: 300) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
41.54717
83
0.709355
6458bac1cab1f5c72f25ef98384574f6a5623d36
1,955
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. /* MIT License Copyright (c) 2017-2020 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import PackageDescription let package = Package( name: "MessageKit", platforms: [.iOS(.v12)], products: [ .library(name: "MessageKit", targets: ["MessageKit"]), ], dependencies: [ .package(url: "https://github.com/nathantannar4/InputBarAccessoryView", .upToNextMajor(from: "5.3.1")) ], targets: [ .target( name: "MessageKit", dependencies: ["InputBarAccessoryView"], path: "Sources", exclude: ["Supporting/Info.plist", "Supporting/MessageKit.h"], swiftSettings: [SwiftSetting.define("IS_SPM")] ), .testTarget(name: "MessageKitTests", dependencies: ["MessageKit"]) ], swiftLanguageVersions: [.v5] )
39.897959
110
0.714066
c1e2ee6647f4e8abebc160e6eb8afca733f380f7
1,035
// // EmoteTableViewCell.swift // GnomeGG // // Created by Kirill Voloshin on 6/3/19. // Copyright © 2019 Kirill Voloshin. All rights reserved. // import UIKit class EmoteTableViewCell: UITableViewCell { @IBOutlet weak var prefixLabel: UILabel! @IBOutlet weak var emoteLabel: UILabel! @IBOutlet weak var sourceLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func renderEmote(emote: Emote) { prefixLabel.text = emote.prefix sourceLabel.text = emote.bbdgg ? "BBDestinyGG" : "DestinyGG" let emoteAttachement = NSTextAttachment() emoteAttachement.image = emote.image emoteAttachement.bounds = CGRect(x: 0, y: -5, width: emote.width, height: emote.height) let emoteString = NSMutableAttributedString(attachment: emoteAttachement) emoteLabel.attributedText = emoteString } }
27.972973
95
0.681159
ded852fcc20705374e5e675c8f23c1dad0ee99dc
4,294
// // FingeringScrollingView.swift // NOTEbook // // Created by Matt Free on 11/21/20. // Copyright © 2020 Matt Free. All rights reserved. // import UIKit class FingeringScrollingView: UIView { var fingerings = [Fingering]() { didSet { for fingeringScrollView in fingeringScrollViews { fingeringScrollView.removeFromSuperview() } fingeringScrollViews.removeAll() for fingering in fingerings { let fingeringScrollView = FingeringScrollView(fingering: fingering) fingeringScrollViews.append(fingeringScrollView) } width = ChartsController.shared.currentChart.instrument.fingeringWidth scrollView.contentSize = CGSize(width: CGFloat(width * fingeringScrollViews.count), height: LetterArrowViewController.fingeringHeight) addFingeringScrollViews() pageControl.numberOfPages = fingeringScrollViews.count pageControlValueChanged(to: 0, animated: false) } } private lazy var pageControl: NotebookPageControl = { let control = NotebookPageControl(pages: 0) control.addTarget(self, action: #selector(pageControlChanged), for: .valueChanged) return control }() private lazy var scrollView: NotebookScrollView = { let sv = NotebookScrollView() sv.delegate = self return sv }() private var width = 0 { didSet { scrollViewWidthAnchor.constant = CGFloat(width) } } private var scrollViewWidthAnchor: NSLayoutConstraint! private var fingeringScrollViews = [FingeringScrollView]() override init(frame: CGRect) { super.init(frame: frame) addSubview(scrollView) addSubview(pageControl) NSLayoutConstraint.activate([ scrollView.centerXAnchor.constraint(equalTo: centerXAnchor), scrollView.bottomAnchor.constraint(equalTo: bottomAnchor), scrollView.heightAnchor.constraint(equalToConstant: LetterArrowViewController.fingeringHeight), pageControl.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 10), pageControl.centerXAnchor.constraint(equalTo: centerXAnchor) ]) scrollViewWidthAnchor = scrollView.widthAnchor.constraint(equalToConstant: 0) scrollViewWidthAnchor.isActive = true width = ChartsController.shared.currentChart.instrument.fingeringWidth } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addFingeringScrollViews() { for (index, fingeringScrollView) in fingeringScrollViews.enumerated() { fingeringScrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(fingeringScrollView) NSLayoutConstraint.activate([ fingeringScrollView.heightAnchor.constraint(equalToConstant: LetterArrowViewController.fingeringHeight), fingeringScrollView.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor), fingeringScrollView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: CGFloat(ChartsController.shared.currentChart.instrument.fingeringWidth * index)), fingeringScrollView.widthAnchor.constraint(equalToConstant: CGFloat(ChartsController.shared.currentChart.instrument.fingeringWidth)) ]) } } @objc private func pageControlChanged(sender: UIPageControl) { pageControlValueChanged(to: sender.currentPage) } private func pageControlValueChanged(to value: Int, animated: Bool = true) { pageControl.currentPage = value scrollView.setContentOffset(CGPoint(x: CGFloat(width * value), y: 0), animated: animated) } } extension FingeringScrollingView: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageIndex = round(scrollView.contentOffset.x / frame.size.width) pageControl.currentPage = Int(pageIndex) } }
38.684685
152
0.662785
8957af213d946135cdc5b90e00a0fb68e697baa1
1,286
// // SicknessCertificatePersonalDataCoordinator.swift // CoronaContact // import UIKit final class SicknessCertificatePersonalDataCoordinator: Coordinator, ErrorPresentableCoordinator { lazy var rootViewController: SicknessCertificatePersonalDataViewController = { SicknessCertificatePersonalDataViewController.instantiate() }() var navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController } override func start() { rootViewController.viewModel = SicknessCertificatePersonalDataViewModel(with: self) navigationController.pushViewController(rootViewController, animated: true) } override func finish(animated: Bool = false) { // if the viewController is still here this call came from the parent and we need to remove it if rootViewController.parent == navigationController { navigationController.popViewController(animated: false) } parentCoordinator?.didFinish(self) } func tanConfirmation() { let child = SicknessCertificateTanConfirmationCoordinator(navigationController: navigationController) addChildCoordinator(child) child.start() } }
33.842105
109
0.748834
0edcac89b1568a52e9c3ccbf6f8052cf2b2ef870
266
// // TimelineTableViewCell+HasDisposeBag.swift // TravelersOnFlight // // Created by ruin09 on 23/04/2020. // Copyright © 2020 ruin09. All rights reserved. // import TimelineTableViewCell import NSObject_Rx extension TimelineTableViewCell : HasDisposeBag { }
20.461538
51
0.766917
feeaedb5672aabcec65c07c160a07c8471ea3126
381
// // ConfigurationResults.swift // Moviefy // // Created by Macbook Pro 15 on 4/30/20. // Copyright © 2020 Adriana González Martínez. All rights reserved. // import Foundation struct ConfigurationResults<T: ModelProtocol>: ModelProtocol { let changeKeys: [String] let images: T } extension ConfigurationResults { static var decoder: JSONDecoder { T.decoder } }
20.052632
68
0.721785
c1d156346081444532ce5bc64f9731519dd92aaf
2,436
// Copyright © 2021 Stormbird PTE. LTD. import Foundation import BigInt //Shape of this originally created to match OpenSea's API output protocol NonFungibleFromJson: Codable { var tokenId: String { get } var tokenType: NonFungibleFromJsonTokenType { get } var value: BigInt { get set } var contractName: String { get } var decimals: Int { get } var symbol: String { get } var name: String { get } var description: String { get } var thumbnailUrl: String { get } var imageUrl: String { get } var contractImageUrl: String { get } var externalLink: String { get } var backgroundColor: String? { get } var traits: [OpenSeaNonFungibleTrait] { get } var generationTrait: OpenSeaNonFungibleTrait? { get } var collectionCreatedDate: Date? { get } var collectionDescription: String? { get } var meltStringValue: String? { get } var meltFeeRatio: Int? { get } var meltFeeMaxRatio: Int? { get } var totalSupplyStringValue: String? { get } var circulatingSupplyStringValue: String? { get } var reserveStringValue: String? { get } var nonFungible: Bool? { get } var blockHeight: Int? { get } var mintableSupply: BigInt? { get } var transferable: String? { get } var supplyModel: String? { get } var issuer: String? { get } var created: String? { get } var transferFee: String? { get } } func nonFungible(fromJsonData jsonData: Data, tokenType: TokenType? = nil) -> NonFungibleFromJson? { if let nonFungible = try? JSONDecoder().decode(OpenSeaNonFungible.self, from: jsonData) { return nonFungible } if let nonFungible = try? JSONDecoder().decode(NonFungibleFromTokenUri.self, from: jsonData) { return nonFungible } let nonFungibleTokenType = tokenType.flatMap { TokensDataStore.functional.nonFungibleTokenType(fromTokenType: $0) } //Parse JSON strings which were saved before we added support for ERC1155. So they are might be ERC721s with missing fields if let nonFungible = try? JSONDecoder().decode(OpenSeaNonFungibleBeforeErc1155Support.self, from: jsonData) { return nonFungible.asPostErc1155Support(tokenType: nonFungibleTokenType) } if let nonFungible = try? JSONDecoder().decode(NonFungibleFromTokenUriBeforeErc1155Support.self, from: jsonData) { return nonFungible.asPostErc1155Support(tokenType: nonFungibleTokenType) } return nil }
40.6
127
0.706076
230c9d30ccefe05980e4d4a1938f26c4441bcf3f
273
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a<h{class d<T where I:a{func b{enum S<T where I:A>:a
39
87
0.739927
ab4ca1d5298cdc4913615af051b594cfbe6be423
361
import XCTest @testable import UGS final class UGSTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. XCTAssertEqual(UGS().text, "Hello, World!") } }
30.083333
91
0.584488
f7148ca920963f36de658f4556b5fcf8d6e1e299
20,336
import XCTest import Quick import Nimble import Cuckoo @testable import EthereumKit class NodeDiscoveryTests: QuickSpec { override func spec() { let privKey = Data([0x01]) let nodeId = Data(repeating: 1, count: 64) let ecKey = ECKey(privateKey: privKey, publicKeyPoint: ECPoint(nodeId: nodeId)) let mockDiscoveryStorage = MockIDiscoveryStorage() let mockClient = MockIUdpClient() let mockFactory = MockIUdpFactory() let mockNodeParser = MockINodeParser() let mockPacketParser = MockIPacketParser() let mockManager = MockINodeManager() let selfNode = Node(id: nodeId, host: NodeDiscovery.selfHost, port: NodeDiscovery.selfPort, discoveryPort: NodeDiscovery.selfPort) let node = Node(id: Data(repeating: 2, count: 64), host: "host", port: 1, discoveryPort: 2) let nodeRecord = NodeRecord(id: Data(repeating: 2, count: 64), host: "host", port: 1, discoveryPort: 2, used: false, eligible: false, score: 1, timestamp: 10) let state = NodeDiscoveryState() let discovery = NodeDiscovery(ecKey: ecKey, factory: mockFactory, discoveryStorage: mockDiscoveryStorage, state: state, nodeParser: mockNodeParser, packetParser: mockPacketParser) discovery.nodeManager = mockManager afterEach { reset(mockDiscoveryStorage, mockClient, mockFactory, mockNodeParser, mockPacketParser, mockManager) } describe("#lookup") { context("get node from storage") { it("throws error when first time return nil") { stub(mockDiscoveryStorage) { mock in when(mock.nonUsedNode()).thenReturn(nil) } do { try discovery.lookup() } catch let error as DiscoveryError { XCTAssertEqual(error, DiscoveryError.allNodesUsed) } catch { XCTFail("Unexpected error!") } verify(mockDiscoveryStorage).nonUsedNode() verifyNoMoreInteractions(mockDiscoveryStorage) } context("make node used and start find neighbors") { beforeEach { stub(mockDiscoveryStorage) { mock in when(mock.nonUsedNode()).thenReturn(nodeRecord) when(mock.setUsed(node: equal(to: nodeRecord))).thenDoNothing() } } it("can't creates client") { stub(mockFactory) { mock in when(mock.client(node: equal(to: node), timeoutInterval: NodeDiscovery.timeoutInterval)).thenThrow(UDPClientError.cantCreateAddress) } do { try discovery.lookup() } catch let error as UDPClientError { XCTAssertEqual(error, UDPClientError.cantCreateAddress) } catch { XCTFail("Unexpected error!") } verify(mockDiscoveryStorage).nonUsedNode() verify(mockDiscoveryStorage).setUsed(node: equal(to: nodeRecord)) verify(mockFactory).client(node: equal(to: node), timeoutInterval: NodeDiscovery.timeoutInterval) verifyNoMoreInteractions(mockDiscoveryStorage) verifyNoMoreInteractions(mockFactory) } context("success create client") { beforeEach { stub(mockFactory) { mock in when(mock.client(node: equal(to: node), timeoutInterval: NodeDiscovery.timeoutInterval)).thenReturn(mockClient) } stub(mockClient) { mock in when(mock.delegate.set(any())).thenDoNothing() when(mock.listen()).thenDoNothing() } } it("throws error on create pingData") { stub(mockFactory) { mock in when(mock.pingData(from: equal(to: selfNode), to: equal(to: node), expiration: NodeDiscovery.expirationInterval)).thenThrow(PackageSerializeError.wrongSerializer) } do { try discovery.lookup() } catch let error as PackageSerializeError { XCTAssertEqual(error, PackageSerializeError.wrongSerializer) } catch { XCTFail("Unexpected error!") } verify(mockClient).delegate.set(any()) verify(mockClient).listen() verify(mockFactory).pingData(from: equal(to: selfNode), to: equal(to: node), expiration: NodeDiscovery.expirationInterval) verify(mockClient, never()).send(any()) } context("success create pingData") { let pingData = Data(repeating: 9, count: 2) beforeEach { stub(mockFactory) { mock in when(mock.pingData(from: equal(to: selfNode), to: equal(to: node), expiration: NodeDiscovery.expirationInterval)).thenReturn(pingData) } } it("throws error on send pingData") { stub(mockClient) { mock in when(mock.send(equal(to: pingData))).thenThrow(UDPClientError.cantCreateAddress) } do { try discovery.lookup() } catch let error as UDPClientError { XCTAssertEqual(error, UDPClientError.cantCreateAddress) } catch { XCTFail("Unexpected error!") } verify(mockClient).send(equal(to: pingData)) verify(mockFactory, never()).findNodeData(target: any(), expiration: any()) } context("success send pingData") { beforeEach { stub(mockClient) { mock in when(mock.send(equal(to: pingData))).thenDoNothing() } } it("throws error on create findNodeData") { stub(mockFactory) { mock in when(mock.findNodeData(target: equal(to: nodeId), expiration: equal(to: NodeDiscovery.expirationInterval))).thenThrow(PackageSerializeError.wrongSerializer) } do { try discovery.lookup() } catch let error as PackageSerializeError { XCTAssertEqual(error, PackageSerializeError.wrongSerializer) } catch { XCTFail("Unexpected error!") } verify(mockFactory).findNodeData(target: equal(to: nodeId), expiration: equal(to: NodeDiscovery.expirationInterval)) // send only ping packet verify(mockClient, times(1)).send(any()) } } context("success create findNodeData") { let findNodeData = Data(repeating: 8, count: 2) beforeEach { stub(mockFactory) { mock in when(mock.findNodeData(target: equal(to: nodeId), expiration: equal(to: NodeDiscovery.expirationInterval))).thenReturn(findNodeData) } stub(mockClient) { mock in when(mock.send(equal(to: pingData))).thenDoNothing() when(mock.send(equal(to: findNodeData))).thenDoNothing() } } it("sends findNodeData and goes to second iteration with error AllNodesUsed") { stub(mockDiscoveryStorage) { mock in when(mock.nonUsedNode()).thenReturn(nodeRecord).thenReturn(nil) } do { try discovery.lookup() } catch let error as DiscoveryError { XCTAssertEqual(error, DiscoveryError.allNodesUsed) } catch { XCTFail("Unexpected error!") } verify(mockClient).send(equal(to: findNodeData)) } it("success get nodes and send to all alpha-count nodes") { stub(mockDiscoveryStorage) { mock in when(mock.nonUsedNode()).thenReturn(nodeRecord) } do { try discovery.lookup() } catch { XCTFail("Unexpected error!") } verify(mockClient, times(NodeDiscovery.alpha)).send(equal(to: findNodeData)) } } } } } } } describe("didStop(client, by error)") { let error = TestError() beforeEach { stub(mockDiscoveryStorage) { mock in when(mock.remove(node: equal(to: node))).thenDoNothing() } stub(mockClient) { mock in when(mock.delegate.set(any())).thenDoNothing() when(mock.noResponse.get).thenReturn(true) when(mock.node.get).thenReturn(node) when(mock.id.get).thenReturn(node.id) } state.removeAll() state.add(client: mockClient) } it("remove client from db if not any response") { discovery.didStop(mockClient, by: error) verify(mockDiscoveryStorage).remove(node: equal(to: node)) expect(state.clients).to(beEmpty()) } it("remove client only from state if it responses previously") { stub(mockClient) { mock in when(mock.noResponse.get).thenReturn(false) } discovery.didStop(mockClient, by: error) verify(mockDiscoveryStorage, never()).remove(node: equal(to: node)) expect(state.clients).to(beEmpty()) } } describe("#didReceive(client:data)") { let data = Data([0x01]) let hash = Data(repeating: 3, count: 2) let sig = Data(repeating: 4, count: 2) context("receive any wrong packet") { stub(mockPacketParser) { mock in when(mock.parse(data: equal(to: data))).thenThrow(PacketParseError.tooSmall) } do { try discovery.didReceive(mockClient, data: data) } catch { XCTFail("Unexpected error!") } verifyNoMoreInteractions(mockClient) verifyNoMoreInteractions(mockFactory) verifyNoMoreInteractions(mockManager) } it("can't cast packet") { let package = FindNodePackage(target: hash, expiration: Int32(NodeDiscovery.expirationInterval)) let packet = Packet(hash: hash, signature: sig, type: 1, package: package) stub(mockPacketParser) { mock in when(mock.parse(data: equal(to: data))).thenReturn(packet) } do { try discovery.didReceive(mockClient, data: data) } catch let error as PacketParseError { XCTAssertEqual(error, PacketParseError.wrongType) } catch { XCTFail("Unexpected error!") } } context("receive ping packet") { let package = PingPackage(from: node, to: selfNode, expiration: Int32(NodeDiscovery.expirationInterval)) let packet = Packet(hash: hash, signature: sig, type: 1, package: package) beforeEach { stub(mockPacketParser) { mock in when(mock.parse(data: equal(to: data))).thenReturn(packet) } } it("throws error on create pongData") { stub(mockFactory) { mock in when(mock.pongData(to: equal(to: node), hash: equal(to: hash), expiration: NodeDiscovery.expirationInterval)).thenThrow(PackageSerializeError.wrongSerializer) } do { try discovery.didReceive(mockClient, data: data) } catch let error as PackageSerializeError { XCTAssertEqual(error, PackageSerializeError.wrongSerializer) } catch { XCTFail("Unexpected error!") } verify(mockFactory).pongData(to: equal(to: node), hash: equal(to: hash), expiration: NodeDiscovery.expirationInterval) verify(mockClient, never()).send(any()) } context("success create pongData") { let pongData = Data(repeating: 9, count: 2) beforeEach { stub(mockFactory) { mock in when(mock.pongData(to: equal(to: node), hash: equal(to: hash), expiration: NodeDiscovery.expirationInterval)).thenReturn(pongData) } } it("throws error on send pongData") { stub(mockClient) { mock in when(mock.send(equal(to: pongData))).thenThrow(UDPClientError.cantCreateAddress) } do { try discovery.didReceive(mockClient, data: data) } catch let error as UDPClientError { XCTAssertEqual(error, UDPClientError.cantCreateAddress) } catch { XCTFail("Unexpected error!") } verify(mockClient).send(equal(to: pongData)) verify(mockFactory, never()).findNodeData(target: any(), expiration: any()) } context("success send pongData") { beforeEach { stub(mockClient) { mock in when(mock.send(equal(to: pongData))).thenDoNothing() } } it("throws error on create findNodeData") { stub(mockFactory) { mock in when(mock.findNodeData(target: equal(to: nodeId), expiration: equal(to: NodeDiscovery.expirationInterval))).thenThrow(PackageSerializeError.wrongSerializer) } do { try discovery.didReceive(mockClient, data: data) } catch let error as PackageSerializeError { XCTAssertEqual(error, PackageSerializeError.wrongSerializer) } catch { XCTFail("Unexpected error!") } verify(mockFactory).findNodeData(target: equal(to: nodeId), expiration: equal(to: NodeDiscovery.expirationInterval)) verify(mockClient).send(any()) } } context("success create findNodeData") { let findNodeData = Data(repeating: 8, count: 2) beforeEach { stub(mockFactory) { mock in when(mock.findNodeData(target: equal(to: nodeId), expiration: equal(to: NodeDiscovery.expirationInterval))).thenReturn(findNodeData) } stub(mockClient) { mock in when(mock.send(equal(to: pongData))).thenDoNothing() when(mock.send(equal(to: findNodeData))).thenDoNothing() } } it("sends findNodeData") { stub(mockDiscoveryStorage) { mock in when(mock.nonUsedNode()).thenReturn(nodeRecord).thenReturn(nil) } do { try discovery.didReceive(mockClient, data: data) } catch { XCTFail("Unexpected error!") } verify(mockClient).send(equal(to: findNodeData)) } it("success get nodes") { stub(mockDiscoveryStorage) { mock in when(mock.nonUsedNode()).thenReturn(nodeRecord) } do { try discovery.didReceive(mockClient, data: data) } catch { XCTFail("Unexpected error!") } verify(mockClient).send(equal(to: findNodeData)) } } } } context("receive Neighbors") { let expectedNode = Node(id: Data([1, 2, 3]), host: "host", port: 9, discoveryPort: 10) let package = NeighborsPackage(nodes: [expectedNode], expiration: Int32(NodeDiscovery.expirationInterval)) let packet = Packet(hash: hash, signature: sig, type: 4, package: package) beforeEach { stub(mockPacketParser) { mock in when(mock.parse(data: equal(to: data))).thenReturn(packet) } } it("calls nodeManager add nodes") { stub(mockManager) { mock in when(mock.add(nodes: equal(to: [expectedNode]))).thenDoNothing() } do { try discovery.didReceive(mockClient, data: data) } catch { XCTFail("Unexpected error!") } verify(mockManager).add(nodes: equal(to: [expectedNode])) } } } } }
53.096606
196
0.450826
09477b60f9ff4242b8c05eff1bf9b401583db721
779
// // ContentView.swift // StopWatch // // Copyright © 2019 keyWindow. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { let model = StopWatch() return TabView { StopWatchView(model: model).tabItem { VStack { Image(systemName: "stopwatch") Text("Stop Watch") } } SettingView(model: model).tabItem { VStack { Image(systemName: "gear") Text("Settings") } } } } } #if DEBUG struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } #endif
19.475
52
0.474968
0106a9ac2a4bc2a227df027a4b6abd3658920c84
2,699
// // UITableView+Chain.swift // iDak // // Created by Malith Nadeeshan on 4/21/20. // Copyright © 2020 Malith Nadeeshan. All rights reserved. // import UIKit extension UIKitChain where Component : UITableView{ @discardableResult public func showScollIndicators(_ isShow:Bool) -> Self { component.showsVerticalScrollIndicator = isShow component.showsHorizontalScrollIndicator = isShow return self } @discardableResult public func indicatorStyle(_ style: UIScrollView.IndicatorStyle) -> Self { component.indicatorStyle = style return self } @discardableResult public func enableScroll(_ isEnabled:Bool) -> Self { component.isScrollEnabled = isEnabled return self } @discardableResult public func bounceVertical(_ isAlwaysBounceVertically:Bool) -> Self { component.alwaysBounceVertical = isAlwaysBounceVertically return self } @discardableResult public func register(_ cellClass: AnyClass?, with identifier: String) -> Self { component.register(cellClass, forCellReuseIdentifier: identifier) return self } @discardableResult public func register(_ nib: UINib?, with identifier: String) -> Self { component.register(nib, forCellReuseIdentifier: identifier) return self } @discardableResult public func registerHeader(_ headerClass:AnyClass?,_ identifier:String) -> Self { component.register(headerClass, forHeaderFooterViewReuseIdentifier: identifier) return self } @discardableResult public func delegate(_ delegate: UITableViewDelegate?) -> Self { component.delegate = delegate return self } @discardableResult public func dataSource(_ dataSource: UITableViewDataSource?) -> Self { component.dataSource = dataSource return self } @available(iOS 11.1, *) @discardableResult public func contentInset(_ inset:UIEdgeInsets) -> Self { component.contentInset = inset component.verticalScrollIndicatorInsets = UIEdgeInsets.init(top: inset.top, left: 0, bottom: inset.bottom, right: 0) return self } @discardableResult public func seperatorStyle(_ style: UITableViewCell.SeparatorStyle) -> Self { component.separatorStyle = style return self } @discardableResult public func seperatorInset(_ inset: UIEdgeInsets) -> Self { component.separatorInset = inset return self } public var setEmptyFooter: Self { component.tableFooterView = UIView() return self } }
29.021505
124
0.670989
e4db72651f009fdb2579655481b0c65116a81daf
635
// // MovieCell.swift // MovieViewer // // Created by Golla, Chaitanya Teja on 4/1/17. // Copyright © 2017 Golla, Chaitanya Teja. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var posterView: UIImageView! 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 } }
22.678571
65
0.67874
cca01f7cd7bf8dab1514a0c4bd56fdb35add28f3
860
// // CAMUploadReqest.swift // Cameo // // Created by Westendorf, Michael on 6/27/16. // Copyright © 2016 Vimeo. All rights reserved. // import Foundation public enum CAMUploadRequest: String { case CreateVideo case UploadVideo case CreateThumbnail case UploadThumbnail case ActivateThumbnail static func orderedRequests() -> [CAMUploadRequest] { return [.CreateVideo, .UploadVideo, .CreateThumbnail, .UploadThumbnail, .ActivateThumbnail] } static func nextRequest(_ currentRequest: CAMUploadRequest) -> CAMUploadRequest? { let orderedRequests = CAMUploadRequest.orderedRequests() if let index = orderedRequests.firstIndex(of: currentRequest), index + 1 < orderedRequests.count { return orderedRequests[index + 1] } return nil } }
24.571429
104
0.669767
e994f7c44e13f4e8ecd716adf28aad699ec22171
2,537
// // FHXNavigationController.swift // sharesChonse // // Created by 冯汉栩 on 2018/7/13. // Copyright © 2018年 fenghanxuCompany. All rights reserved. // import UIKit class FHXNavigationController: UINavigationController,UINavigationControllerDelegate { /// 是否正在动画(防止连续点击) var isSwitching: Bool = false //不支持旋屏 override var shouldAutorotate: Bool { return false } //设置屏幕竖向 override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .portrait } //设置屏幕竖向 override var supportedInterfaceOrientations: UIInterfaceOrientationMask{ return .portrait } override func viewDidLoad() { super.viewDidLoad() //自己内部遵守代理方法实现需要的要求,平时外面使用的时候也有自己的要求,想TextField的封装一样 delegate = self //false 不透明 true 半透明 navigationBar.isTranslucent = false //背景颜色 navigationBar.backgroundColor = UIColor.white //隐藏导航栏下面底部的线shadowImage,(官方文档对顶设置完之后要一起设置setBackgroundImage才生效) navigationBar.shadowImage = UIImage(named: "nav-shadowImage") navigationBar.setBackgroundImage(UIImage(), for: .default) //设置tabbar标题字体(大小,颜色) 中间的标题文字 navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkText, NSFontAttributeName: UIFont.systemFont(ofSize: 17)] } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if isSwitching { return } isSwitching = true //如果导航栏集合里面不止一个控制器的话就在当前控制器的左边增加一个按键(可能会失去右滑返回手势) if self.childViewControllers.count > 0 { viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_back"), style: .plain, target: self, action: #selector(backBtnClick)) viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.blue }else { isSwitching = false } super.pushViewController(viewController, animated: animated) } // 这是导航每次发生跳转都调用该函数 func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { // 当前页控制器和跳转后的控制器 // SPLogs("当前页控制器 = \(navigationController),跳转后的控制器 = \(viewController)") isSwitching = false } } extension FHXNavigationController { @objc func backBtnClick() { self.popViewController(animated: true) } }
35.732394
142
0.672842
79840b5544c9aa95f76580b790b652823b2e481c
549
// // Undefined.swift // SplittableViewKit // // Created by marty-suzuki on 2018/10/22. // Copyright © 2018年 marty-suzuki. All rights reserved. // enum Undefined { static func object<T>(_ message: String = "Fatal Error", file: String = #file, function: String = #function, line: Int = #line) -> T { fatalError(""" message: \(message) file: \(file) function: \(function) line: \(line) """) } }
23.869565
60
0.47541
62921ee7f82399ddc7deb0fd827b3200c8bdb5f8
5,403
// // Bytes.swift // PerfectLib // // Created by Kyle Jessup on 7/7/15. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // /// A Bytes object represents an array of UInt8 and provides various utilities for importing and exporting values into and out of that array. /// The object maintains a position marker which is used to denote the position from which new export operations proceed. /// An export will advance the position by the appropriate amount. public final class Bytes { /// The position from which new export operations begin. public var position = 0 /// The underlying UInt8 array public var data: [UInt8] /// Indicates the number of bytes which may be successfully exported public var availableExportBytes: Int { return data.count - position } /// Create an empty Bytes object public init() { data = [UInt8]() } /// Initialize with existing bytes public init(existingBytes: [UInt8]) { data = existingBytes } // -- IMPORT /// Imports one UInt8 value appending it to the end of the array /// - returns: The Bytes object @discardableResult public func import8Bits(from frm: UInt8) -> Bytes { data.append(frm) return self } /// Imports one UInt16 value appending it to the end of the array /// - returns: The Bytes object @discardableResult public func import16Bits(from frm: UInt16) -> Bytes { data.append(UInt8(frm & 0xFF)) data.append(UInt8((frm >> 8) & 0xFF)) return self } /// Imports one UInt32 value appending it to the end of the array /// - returns: The Bytes object @discardableResult public func import32Bits(from frm: UInt32) -> Bytes { data.append(UInt8(frm & 0xFF)) data.append(UInt8((frm >> 8) & 0xFF)) data.append(UInt8((frm >> 16) & 0xFF)) data.append(UInt8((frm >> 24) & 0xFF)) return self } /// Imports one UInt64 value appending it to the end of the array /// - returns: The Bytes object @discardableResult public func import64Bits(from frm: UInt64) -> Bytes { data.append(UInt8(frm & 0xFF)) data.append(UInt8((frm >> 8) & 0xFF)) data.append(UInt8((frm >> 16) & 0xFF)) data.append(UInt8((frm >> 24) & 0xFF)) data.append(UInt8((frm >> 32) & 0xFF)) data.append(UInt8((frm >> 40) & 0xFF)) data.append(UInt8((frm >> 48) & 0xFF)) data.append(UInt8((frm >> 56) & 0xFF)) return self } /// Imports an array of UInt8 values appending them to the end of the array /// - returns: The Bytes object @discardableResult public func importBytes(from frm: [UInt8]) -> Bytes { data.append(contentsOf: frm) return self } /// Imports the array values of the given Bytes appending them to the end of the array /// - returns: The Bytes object @discardableResult public func importBytes(from frm: Bytes) -> Bytes { data.append(contentsOf: frm.data) return self } /// Imports an `ArraySlice` of UInt8 values appending them to the end of the array /// - returns: The Bytes object @discardableResult public func importBytes(from frm: ArraySlice<UInt8>) -> Bytes { data.append(contentsOf: frm) return self } // -- EXPORT /// Exports one UInt8 from the current position. Advances the position marker by 1 byte. /// - returns: The UInt8 value public func export8Bits() -> UInt8 { let result = data[position] position += 1 return result } /// Exports one UInt16 from the current position. Advances the position marker by 2 bytes. /// - returns: The UInt16 value public func export16Bits() -> UInt16 { let one = UInt16(data[position]) position += 1 let two = UInt16(data[position]) position += 1 return (two << 8) + one } /// Exports one UInt32 from the current position. Advances the position marker by 4 bytes. /// - returns: The UInt32 value public func export32Bits() -> UInt32 { let one = UInt32(data[position]) position += 1 let two = UInt32(data[position]) position += 1 let three = UInt32(data[position]) position += 1 let four = UInt32(data[position]) position += 1 return (four << 24) + (three << 16) + (two << 8) + one } /// Exports one UInt64 from the current position. Advances the position marker by 8 bytes. /// - returns: The UInt64 value public func export64Bits() -> UInt64 { let one = UInt64(data[position]) position += 1 let two = UInt64(data[position]) << 8 position += 1 let three = UInt64(data[position]) << 16 position += 1 let four = UInt64(data[position]) << 24 position += 1 let five = UInt64(data[position]) << 32 position += 1 let six = UInt64(data[position]) << 40 position += 1 let seven = UInt64(data[position]) << 48 position += 1 let eight = UInt64(data[position]) << 56 position += 1 return (one+two+three+four)+(five+six+seven+eight) } /// Exports the indicated number of bytes public func exportBytes(count cnt: Int) -> [UInt8] { var sub = [UInt8]() let end = position + cnt while position < end { sub.append(data[position]) position += 1 } return sub } }
27.287879
141
0.655747
abd1e789eaae2e0ff64d3ff928327a3fc8a5ec20
906
// // DisableAdsPurchaseCoordinator.swift // MacroCosm // // Created by Антон Текутов on 21.05.2021. // import UIKit final class DisableAdsPurchaseCoordinator: DefaultCoordinator { static func createModule(_ configuration: ((CustomizableDisableAdsPurchaseViewModel) -> Void)? = nil) -> UIViewController { let view = DisableAdsPurchaseViewController() let viewModel = DisableAdsPurchaseViewModel() let coordinator = DisableAdsPurchaseCoordinator() view.viewModel = viewModel view.coordinator = coordinator coordinator.transition = view viewModel.purchaseManager = PurchaseManager.shared if let configuration = configuration { configuration(viewModel) } return view } } // MARK: - Interface for view extension DisableAdsPurchaseCoordinator: DisableAdsPurchaseCoordinatorProtocol { }
25.166667
127
0.703091
6124276a8d5d680e8434eaa9654e6b553bbe2d2b
2,180
// // AppDelegate.swift // SwiftShareModule // // Created by 2360219637 on 10/08/2021. // Copyright (c) 2021 2360219637. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.382979
285
0.755505
092c0b47f1e326b3c829d3757759806d75390576
840
// Copyright 2020 Carton contributors // // 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 ArgumentParser struct CartonRelease: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Carton release automation utility", subcommands: [Formula.self, HashArchive.self] ) } CartonRelease.main()
33.6
75
0.755952
f800b163bf85b7dbf29a396e52ffff891b005715
2,214
// // YCShowMoreTitleView.swift // qichehui // // Created by SMART on 2019/12/9. // Copyright © 2019 SMART. All rights reserved. // import UIKit class YCShowMoreTitleView: UICollectionReusableView { private var selectedIndex = 0 var categories:[YCShowMoreCategoryModel]?{didSet{setCategories()}} private var titleBtnArr = [UIButton]() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setCategories(){ guard let models = categories else{return} if titleBtnArr.count < models.count { for _ in titleBtnArr.count ..< models.count { let btn = UIButton() btn.isHighlighted = false btn.titleLabel?.font = FONT_SIZE_13 btn.setTitleColor(UIColor.white, for: UIControl.State.selected) btn.setTitleColor(UIColor.darkGray, for: UIControl.State.normal) titleBtnArr.append(btn) addSubview(btn) } }else{ for index in models.count ..< titleBtnArr.count { let btn = titleBtnArr[index] btn.isHidden = true } } let BTN_W = (SCREEN_WIDTH - 2*MARGIN_20 - CGFloat(models.count)*MARGIN_15) / CGFloat(models.count) let BTN_H = 25*APP_SCALE for (index,model) in models.enumerated() { let btn = titleBtnArr[index] btn.isHidden = false btn.setTitle(model.name, for: UIControl.State.normal) btn.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(MARGIN_20+CGFloat(index)*(MARGIN_15 + BTN_W)) make.centerY.equalToSuperview() make.height.equalTo(BTN_H) make.width.equalTo(BTN_W) } } let btn = titleBtnArr[selectedIndex] btn.backgroundColor = THEME_COLOR btn.layer.cornerRadius = BTN_H*0.5 btn.layer.masksToBounds = true btn.isSelected = true } }
32.558824
106
0.580397
e42f013c701c9948262f4297d146548f522167cc
664
// // ControlProperty+Driver.swift // RxCocoa // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift extension ControlProperty { /// Converts `ControlProperty` to `Driver` trait. /// /// `ControlProperty` already can't fail, so no special case needs to be handled. public func asDriver() -> Driver<Element> { return self.asDriver { _ -> Driver<Element> in #if DEBUG rxFatalError("Somehow driver received error from a source that shouldn't fail.") #else return Driver.empty() #endif } } }
26.56
96
0.608434
1c62cb24a6aeaa4d3bc049ed9cb6fdcde8792e8f
249
// // SimpleMessagePrinter.swift // // import Foundation class SimpleMessagePrinter { private(set) var message: String? init() { } func show(message: String) { self.message = message print(message) } }
13.833333
37
0.590361
646bd77b544e07be422d571c3179fcd93e81a44f
3,595
// // MemoryHistoryStorageTests.swift // WebimClientLibrary_Tests // // Created by Nikita Lazarev-Zubov on 20.02.18. // Copyright © 2018 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation @testable import WebimClientLibrary import XCTest class MemoryHistoryStorageTests: XCTestCase { // MARK: - Constants private static let SERVER_URL_STRING = "http://demo.webim.ru" // MARK: - Methods // MARK: Private methods private static func generateMessages(ofCount numberOfMessages: Int) -> [MessageImpl] { var messages = [MessageImpl]() for index in 1 ... numberOfMessages { messages.append(MessageImpl(serverURLString: MemoryHistoryStorageTests.SERVER_URL_STRING, id: String(index), keyboard: nil, keyboardRequest: nil, operatorID: "1", senderAvatarURLString: nil, senderName: "Name", type: MessageType.OPERATOR, data: nil, text: "Text", timeInMicrosecond: Int64(index), attachment: nil, historyMessage: true, internalID: String(index), rawText: nil, read: false, messageCanBeEdited: false)) } return messages } // MARK: - Tests func testGetFullHistory() { let memoryHistoryStorage = MemoryHistoryStorage() let messagesCount = 10 memoryHistoryStorage.receiveHistoryBefore(messages: MemoryHistoryStorageTests.generateMessages(ofCount: messagesCount), hasMoreMessages: false) let expectation = XCTestExpectation() var gettedMessages = [Message]() memoryHistoryStorage.getFullHistory() { messages in gettedMessages = messages expectation.fulfill() } wait(for: [expectation], timeout: 1.0) XCTAssertEqual(gettedMessages.count, messagesCount) } }
42.294118
127
0.566898
091117410b1a629994b4191fa19562bb1a3138bf
1,495
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import Foundation import GRPC import NIOHPACK enum CallSwiftMethodNatively: UserInfo.Key { typealias Value = Bool } final class ProxyDeterminatorInterceptor<Request, Response>: ServerInterceptor<Request, Response> { override func receive(_ part: GRPCServerRequestPart<Request>, context: ServerInterceptorContext<Request, Response>) { switch part { case let .metadata(headers): if ProcessInfo.processInfo.environment["IDB_HANDLE_ALL_GRPC_SWIFT"] == "YES" { context.userInfo[CallSwiftMethodNatively.self] = true } else { context.userInfo[CallSwiftMethodNatively.self] = swiftMethodsHeaderContainsCurrentMethod(headers: headers, context: context) } default: break } context.receive(part) } private func swiftMethodsHeaderContainsCurrentMethod(headers: HPACKHeaders, context: ServerInterceptorContext<Request, Response>) -> Bool { let swiftMethodsValue = headers["idb-swift-methods"] let methodName = extractMethodName(path: context.path) let swiftMethods = swiftMethodsValue .reduce("", +) .split(separator: ",") return swiftMethods.contains(methodName) } private func extractMethodName(path: String) -> Substring { path .suffix(from: path.lastIndex(of: "/")!) .dropFirst() } }
28.207547
141
0.72107
6202c7afefa5cbd46263fe5e58ad77c8b28a2372
1,584
// // ExchangeUpdater.swift // breadwallet // // Created by Adrian Corscadden on 2017-01-27. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import Foundation class ExchangeUpdater: Subscriber { private var lastUpdate = Date.distantPast private let requestThrottleSeconds: TimeInterval = 5.0 // MARK: - Public init() { Store.lazySubscribe(self, selector: { $0.defaultCurrencyCode != $1.defaultCurrencyCode }, callback: { _ in self.forceRefresh() }) } func refresh() { guard Date().timeIntervalSince(lastUpdate) > requestThrottleSeconds else { return } self.forceRefresh() } private func forceRefresh() { guard !Store.state.currencies.isEmpty else { return } lastUpdate = Date() Backend.apiClient.fetchPriceInfo(currencies: Store.state.currencies) { result in guard case .success(let priceInfo) = result else { return } Store.state.currencies.forEach { guard let info = priceInfo[$0.code.uppercased()] else { return } Store.perform(action: WalletChange($0).setFiatPriceInfo(info)) let fiatCode = Store.state.defaultCurrencyCode let rate = Rate(code: fiatCode, name: $0.name, rate: info.price, reciprocalCode: $0.code) Store.perform(action: WalletChange($0).setExchangeRate(rate)) } } } }
31.058824
105
0.577652
878ed9f0a33d3782d83b56b83c4b1bd415497959
2,207
// // LoginViewController.swift // login // // Created by doug on 5/23/16. // Copyright © 2016 fireunit. All rights reserved. // import UIKit import Material class LoginViewController: UIViewController { let emailTextField: TextField = TextField() override func viewDidLoad() { super.viewDidLoad() prepareNavigationController() prepareView() prepareEmailField() prepareNextButton() } private func prepareNavigationController() { let _ = navigationController?.navigationBar.subviews.map { $0.subviews.map { if $0 is UIImageView { $0.removeFromSuperview() } } } navigationController?.navigationBar.barTintColor = MaterialColor.white } private func prepareView() { view.backgroundColor = MaterialColor.white } private func prepareEmailField() { emailTextField.placeholder = "Email" emailTextField.font = RobotoFont.regularWithSize(16) emailTextField.textColor = MaterialColor.black view.addSubview(emailTextField) let margin = CGFloat(16) emailTextField.translatesAutoresizingMaskIntoConstraints = false MaterialLayout.size(view, child: emailTextField, width: view.frame.width - margin * 2, height: 25) MaterialLayout.alignFromTopLeft(view, child: emailTextField, top:160 , left: margin) } private func prepareNextButton() { let nextButton: RaisedButton = RaisedButton(frame: CGRectMake(107, 207, 100, 35)) nextButton.setTitle("Next", forState: .Normal) nextButton.titleLabel!.font = RobotoFont.mediumWithSize(14) nextButton.backgroundColor = MaterialColor.cyan.darken2 nextButton.pulseColor = MaterialColor.white nextButton.addTarget(self, action: #selector(handleNextButton), forControlEvents: .TouchUpInside) view.addSubview(nextButton) } internal func handleNextButton() { if let email = emailTextField.text { let passwordVC = PasswordViewController() passwordVC.email = email navigationController?.pushViewController(passwordVC, animated: true) } } }
32.940299
138
0.674671
9baef4a9aa0db55aeb120b0279566273b525a31f
14,806
// // PictureOfTheDayViewController.swift // // // Created by Ravikant Kumar on 03/12/21. // import UIKit import SDWebImage import DeckTransition import CoreData import Network class PictureOfTheDayViewController: UIViewController { var sharedStack: CoreDataStackManager { let delegate = UIApplication.shared.delegate as! AppDelegate return delegate.dataStack } var sharedContext: NSManagedObjectContext { return sharedStack.context } //if #available(iOS 12.0, *) { let monitor = NWPathMonitor() // } var pictures = [Picture]() var collectionView: UICollectionView? var activityIndicator: UIActivityIndicatorView? var startDateLoaded: Date? var endDateLoaded: Date? let refreshControl = UIRefreshControl() var insertedIndexPaths: [IndexPath]! var deletedIndexPaths : [IndexPath]! var updatedIndexPaths : [IndexPath]! override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } lazy var fetchedResultsController: NSFetchedResultsController<Picture> = { let fetchRequest = NSFetchRequest<Picture>(entityName: Picture.entityName()) let sortDescriptor = NSSortDescriptor(key: "dateString", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] let fetchedResultsController = NSFetchedResultsController<Picture>(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController.delegate = self as NSFetchedResultsControllerDelegate return fetchedResultsController }() override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.prefersLargeTitles = true self.navigationItem.largeTitleDisplayMode = .always } override func viewDidLoad() { super.viewDidLoad() self.startDateLoaded = UserDefaults.standard.object(forKey: "startDate") as? Date self.endDateLoaded = UserDefaults.standard.object(forKey: "fromDate") as? Date self.view.backgroundColor = UIColor.white self.collectionView?.backgroundColor = UIColor.red self.navigationController?.view.backgroundColor = UIColor.white let flowLayout = UICollectionViewFlowLayout() self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout) self.collectionView?.delegate = self self.collectionView?.dataSource = self let cellNib = UINib(nibName: "PictureOfTheDayCell", bundle: nil) self.collectionView?.register(cellNib, forCellWithReuseIdentifier: PictureOfTheDayCell.reuseIdentifier) self.collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "loaderView") self.view.addSubview(self.collectionView!) self.collectionView?.alwaysBounceVertical = true refreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged) if #available(iOS 10.0, *) { collectionView?.refreshControl = refreshControl } else { collectionView?.addSubview(refreshControl) } performFetch() self.pictures = fetchedResultsController.fetchedObjects! if (self.pictures.count > 0) { let dateString = self.pictures[0].dateString let systemDate = Date() let systemDateString = dateToString(systemDate: systemDate) guard let systemDateData = systemDateString.toDate() else {return} guard let savedDate = dateString?.toDate() else {return} let isSame = systemDateData.compare(savedDate) == ComparisonResult.orderedSame if isSame == false && self.pictures.count > 0 { let alertController = UIAlertController(title: "Error", message: "We are not connected to the internet, showing you the last image we have.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Close Alert", style: .default, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } } else { monitor.pathUpdateHandler = { path in if path.status == .satisfied { self.calledFromNetwork() } else { let alertController = UIAlertController(title: "Error", message: "We are not connected to the internet.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Close Alert", style: .default, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } } let queue = DispatchQueue(label: "Monitor") monitor.start(queue: queue) } } func calledFromNetwork() { if pictures.isEmpty { DispatchQueue.main.async { self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) self.activityIndicator?.frame = self.view.bounds self.view.addSubview(self.activityIndicator!) self.activityIndicator?.startAnimating() } getNextPhotos(fromDate: Date()) } } func dateToString(systemDate: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let dateString = dateFormatter.string(from: systemDate) return dateString } private func performFetch() { do { try fetchedResultsController.performFetch() } catch (let error) { print(error.localizedDescription) } } @objc private func refreshData(_ sender: Any) { // Fetch Weather Data monitor.pathUpdateHandler = { path in if path.status == .satisfied { self.getNextPhotos(fromDate: Date()) } } let queue = DispatchQueue(label: "Monitor") monitor.start(queue: queue) } func getNextPage() { if self.startDateLoaded != nil { getNextPhotos(fromDate: self.startDateLoaded!) } } func getNextPhotos(fromDate: Date) { var timeInterval = DateComponents() timeInterval.day = -27 let startDate = Calendar.current.date(byAdding: timeInterval, to: fromDate)! self.activityIndicator?.startAnimating() NASAAPODClient.sharedInstance().getPhotos(startDate: startDate, endDate: fromDate) { (success, error) in DispatchQueue.main.async { self.collectionView?.isHidden = false self.activityIndicator?.stopAnimating() } if(!success && error != nil) { performUIUpdatesOnMain { self.activityIndicator?.stopAnimating() let alertController = UIAlertController(title: "Error", message: "App failed to get photos, try checking your internet connection.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Close Alert", style: .default, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } } else { performUIUpdatesOnMain { self.performFetch() if(self.pictures.count == 0) { self.activityIndicator?.stopAnimating() } self.collectionView?.reloadData() self.refreshControl.endRefreshing() } self.pictures = self.fetchedResultsController.fetchedObjects! UserDefaults.standard.set(startDate, forKey: "startDate") self.startDateLoaded = startDate self.endDateLoaded = fromDate } } } } extension PictureOfTheDayViewController : UICollectionViewDataSource, UICollectionViewDelegate { func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if self.collectionView != nil { let currentOffset = self.collectionView!.contentOffset.y; let maximumOffset = self.collectionView!.contentSize.height - scrollView.frame.size.height; if (maximumOffset - currentOffset <= 900) { // getNextPage() } } } func numberOfSections(in collectionView: UICollectionView) -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 0 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let picture = self.pictures[indexPath.row] let detailViewController = PictureOfTheDayDetailViewController(picture: picture) self.navigationController?.pushViewController(detailViewController, animated: true) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { let currentSection = sections[section] return currentSection.numberOfObjects } return 0 } func pictureForIndexPath(_ indexPath : IndexPath) -> Picture? { if (!pictures.isEmpty) { return pictures[indexPath.row] } else { return Picture() } } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PictureOfTheDayCell let picture = fetchedResultsController.object(at: indexPath) if picture.title != nil { cell.title?.text = picture.title } if picture.urlString != nil { let url = URL(string: picture.urlString!)! // if(picture.mediaType == "image") { cell.pictureOfTheDay?.sd_setIndicatorStyle(.gray) cell.pictureOfTheDay?.sd_addActivityIndicator() cell.pictureOfTheDay?.sd_imageTransition = .fade cell.pictureOfTheDay.sd_setImage(with: url, completed: { (image, error, cacheType, imageURL) in cell.pictureOfTheDay?.sd_removeActivityIndicator() cell.pictureOfTheDay.image = image }) cell.pictureOfTheDay?.sd_setImage(with:url) // cell.pictureOfTheDay?.kf.setImage(with: url) // cell.pictureOfTheDay?.sd_removeActivityIndicator() cell.pictureOfTheDay.contentMode = .scaleAspectFill // } // if(picture.mediaType == "video") { // // } } if picture.explanation != nil { cell.descriptionView?.text = picture.explanation } return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "loaderView", for: indexPath) as! UICollectionViewCell // let loader = UIActivityIndicatorView(activityIndicatorStyle: .gray) // loader.center = view.contentView.center // view.backgroundColor = .white // view.addSubview(loader) // loader.startAnimating() return view } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout let totalSpace = flowLayout.sectionInset.left + flowLayout.sectionInset.right // / CGFloat(1) let size = Int((collectionView.bounds.width - totalSpace)) if(self.pictures.count > 0) { return CGSize(width: size, height: 60) } else { return CGSize.zero } } } extension PictureOfTheDayViewController : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cvRect = collectionView.frame return CGSize(width: cvRect.width, height: cvRect.height-50) } } extension PictureOfTheDayViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { insertedIndexPaths = [IndexPath]() deletedIndexPaths = [IndexPath]() updatedIndexPaths = [IndexPath]() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: insertedIndexPaths.append(newIndexPath!) case .update: updatedIndexPaths.append(indexPath!) case .delete: deletedIndexPaths.append(indexPath!) default: break } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { collectionView?.performBatchUpdates({ for indexPath in self.insertedIndexPaths { self.collectionView?.insertItems(at: [indexPath]) } for indexPath in self.deletedIndexPaths { self.collectionView?.deleteItems(at: [indexPath]) } for indexPath in self.updatedIndexPaths { self.collectionView?.reloadItems(at: [indexPath]) } }, completion: nil) } } extension String { func toDate() -> Date? { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter.date(from: self) } }
41.473389
200
0.637985
01f77051182d774d793904775a3905b50c1670de
1,263
// // InputTextField.swift // IoT // // Created by Mateusz Bąk on 1/19/20. // Copyright © 2020 Mateusz Bąk. All rights reserved. // import UIKit class InputTextField: UITextField { override var placeholder: String? { didSet { if let placeholder = placeholder { attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: UIColor.systemPink.withAlphaComponent(0.7)]) } } } override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension InputTextField { private func setupView() { backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) layer.cornerRadius = 22.0 layer.borderColor = UIColor.systemPink.cgColor layer.borderWidth = 2.0 textColor = .systemPink let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 22.0, height: 44.0)) leftViewMode = .always leftView = paddingView snp.makeConstraints { (make) in make.height.equalTo(44) } } }
26.3125
177
0.604909
bff966b2571a16af98b23aa271bc007e9c05b85e
21,186
// // AHDatabase.swift // AHDB2 // // Created by Andy Tong on 6/28/17. // Copyright © 2017 Andy Tong. All rights reserved. // import CSQLite public enum AHDBDataType: String, CustomStringConvertible { case integer = "Integer" case real = "Real" case text = "Text" public var description: String { return self.rawValue } } private let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self) public enum AHDBError: Error, CustomStringConvertible { case open(message: String) case preapre(message: String) case step(message: String) case bind(message: String) case transaction(message: String) case `internal`(message: String) case other(message: String) public var description: String { switch self { case .open(let message): return "AHDB open error: \(message)" case .preapre(let message): return "AHDB preapre error: \(message)" case .step(let message): return "AHDB step error: \(message)" case .bind(let message): return "AHDB bind error: \(message)" case .transaction(let message): return "AHDB transaction error: \(message)" case .internal(message: let message): return "AHDB internal error: \(message)" case .other(let message): return "AHDB other error: \(message)" } } } /// This struct stores a column's key/value and its infomations when created internal struct AHDBAttribute: CustomStringConvertible, Equatable { var key: String var value: Any? var type: AHDBDataType? var isPrimaryKey = false var isForeginKey = false init(key: String, value: Any?, type: AHDBDataType?) { self.value = value self.type = type self.key = key } var description: String { return "AHDBAttribute{key: \(key) value: \(value ?? "undefined") type:\(String(describing: type)) isPrimaryKey:\(isPrimaryKey) isForeginkey:\(isForeginKey)}" } static func ==(lhs: AHDBAttribute, rhs: AHDBAttribute) -> Bool { let keysEqual = lhs.key == rhs.key let typeEqual = lhs.type == rhs.type let primaryEqual = lhs.isPrimaryKey == rhs.isPrimaryKey let foreginEqual = lhs.isForeginKey == rhs.isForeginKey if keysEqual && typeEqual && primaryEqual && foreginEqual { if let valueA = lhs.value, let valueB = rhs.value { return valuesEqual(valueA, valueB, lhs.type) }else if lhs.value == nil && rhs.value == nil{ return true }else{ return false } }else{ return false } } private static func valuesEqual(_ valueA: Any, _ valueB: Any, _ type: AHDBDataType?) -> Bool { guard let type = type else { if let valueANum = valueA as? NSNumber, let valueBNum = valueB as? NSNumber{ return valueANum == valueBNum } if let valueAStr = valueA as? String, let valueBStr = valueB as? String{ return valueAStr == valueBStr } return false } switch type { case .integer, .real: if let valueANum = valueA as? NSNumber, let valueBNum = valueB as? NSNumber{ return valueANum == valueBNum } case .text: if let valueAStr = valueA as? String, let valueBStr = valueB as? String{ return valueAStr == valueBStr } } return false } } class AHDatabase { fileprivate(set) var dbPath: String? fileprivate static var dbArray = [String : AHDatabase]() var latestError: String { if let message = String(cString: sqlite3_errmsg(dbPointer), encoding: .utf8) { return message }else{ return "No msg provided from sqlite" } } fileprivate var dbPointer: OpaquePointer? fileprivate init(dbPointer: OpaquePointer) { self.dbPointer = dbPointer } deinit { if let dbPointer = dbPointer { // It returns SQLITE_OK if the db is actually being terminated // returns SQLITE_BUSY, the db keeps open, when a prepareStmt or sqlite3_backup is unfinalized. sqlite3_close(dbPointer) } } } //MARK:- APIs extension AHDatabase { /// One db file for one db connection!! static func connection(path: String) throws -> AHDatabase { if let db = dbArray[path] { return db } var dbPointer: OpaquePointer? = nil // SQLITE_OPEN_NOMUTEX: multi-thread mode, each connection can be used in one single thread // SQLITE_OPEN_FULLMUTEX: serialized mode, all operations are serialized if sqlite3_open_v2(path, &dbPointer, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK { // 1. open // if sqlite3_open(path, &dbPointer) == SQLITE_OK { let db = AHDatabase(dbPointer: dbPointer!) // turn on foreign_keys by default do { try db.executeSQL(sql: "PRAGMA foreign_keys = ON;", bindings: []) } catch _ { throw AHDBError.open(message: "Setting 'foreign_keys = On' failed") } db.dbPath = path dbArray[path] = db return db }else{ // 2. a 'defer' block is called everytime a method block ends. It acts like a clean-up block. // Note: defer has to go before the following error-throwing code. defer { if dbPointer != nil { // even the open is failed, the pointer is still needed to be close sqlite3_close(dbPointer!) } if let db = dbArray[path] { db.close() } } // 3. throw error for open failture // sqlite3_errmsg always returns the latest error message if let message = String(cString: sqlite3_errmsg(dbPointer), encoding: .utf8) { throw AHDBError.open(message: message) }else{ throw AHDBError.open(message: "DB open faliture without system error message") } } } @discardableResult func turnOnForeignKey() -> Bool { do { try self.executeSQL(sql: "PRAGMA foreign_keys = ON;", bindings: []) return true } catch let error { print("turnOnForeignKey error:\(error)") } return false } @discardableResult func turnOffForeinKey() -> Bool { do { try self.executeSQL(sql: "PRAGMA foreign_keys = OFF;", bindings: []) return true } catch let error { print("turnOffForeinKey error:\(error)") } return false } func close() { if dbPointer != nil { sqlite3_close(dbPointer!) AHDatabase.dbArray.removeValue(forKey: self.dbPath!) } } func createTable(tableName: String, columns: [AHDBColumnInfo]) throws { guard columns.count > 0 else { throw AHDBError.other(message: "Columns.cout must not be zero!") } // 1. create sql statement let clearnTableName = cleanUpString(str: tableName) var createTableSql = "CREATE TABLE IF NOT EXISTS \(clearnTableName) (" // NOTE: Binding parameters may not be used for column or table names. // So here we hardcoded the table name and column names. // see https://www.sqlite.org/cintro.html and search 'Parameters may not be used for column or table names.' for i in 0..<columns.count { let columnInfo = columns[i] if i == (columns.count - 1) { createTableSql.append("\(columnInfo.bindingSql));") }else{ createTableSql.append("\(columnInfo.bindingSql),") } } var stmt: OpaquePointer? = nil // 2. try, if there's an error in prepareStatement, let it throws since this method is throwing error too let createStmt = try prepareStatement(sql: createTableSql) // 3. finalize stmt everytime you finish using it defer { sqlite3_finalize(createStmt) } // 4. use sqlite3_step to execute the sql statement guard sqlite3_step(createStmt) == SQLITE_DONE else { throw AHDBError.step(message: latestError) } } func tableExists(tableName: String) -> Bool { let sql = "select 1 from sqlite_master where type='table' and name=?" let property = AHDBAttribute(key: "",value: tableName, type: .text) let binding = [property] do { let results = try query(sql: sql, bindings: binding) return results.count > 0 } catch _ { } return false } /// read/write exclusively without other process or thread to read or write func beginExclusive() throws { try executeSQL(sql: "BEGIN EXCLUSIVE", bindings: []) } func rollback() throws { try executeSQL(sql: "ROLLBACK", bindings: []) } func commit() throws { try executeSQL(sql: "COMMIT", bindings: []) } /// bindings could be empty, i.e. [] func insert(table:String, bindings: [AHDBAttribute]) throws { // INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) // VALUES (value1, value2, value3,...valueN); var bindingHolders = "" var names = "" var shouldSkippedPK: AHDBAttribute? for i in 0..<bindings.count { let attribute = bindings[i] if attribute.isPrimaryKey && attribute.value == nil { // It's ok to ignore primary key and keep inserting since Sqlite will take care of it if it's a integer if attribute.type == .integer{ // remove this PK attribute, otherswise the binding would fail. shouldSkippedPK = attribute continue }else{ throw AHDBError.other(message: "\(table) must have at least an integer primary key") } } let name = attribute.key let cleanName = cleanUpString(str: name) if i == (bindings.count - 1) { names += "\(cleanName)" bindingHolders = bindingHolders + "?" }else{ names += "\(cleanName), " bindingHolders = bindingHolders + "?, " } } let cleanTableName = cleanUpString(str: table) let sql = "INSERT INTO \(cleanTableName) (\(names)) VALUES(\(bindingHolders))" var bindings = bindings if shouldSkippedPK != nil { if let index = bindings.index(of: shouldSkippedPK!) { bindings.remove(at: index) } } try executeSQL(sql: sql, bindings: bindings) } /// Won't use AHDBAttribute'key. You should include attributes keys into the sql String. func query(sql: String, bindings: [AHDBAttribute]) throws -> [[AHDBAttribute]] { let stmt = try prepareStatement(sql: sql) defer { sqlite3_finalize(stmt) } try bind(stmt: stmt, bindings: bindings) var results = [[AHDBAttribute]]() while (sqlite3_step(stmt) == SQLITE_ROW) { let columnCount = sqlite3_column_count(stmt) var singleRow = [AHDBAttribute]() for i in 0..<columnCount { guard let columnName = String(utf8String: sqlite3_column_name(stmt, i)) else {continue} let columnType = sqlite3_column_type(stmt, i) var value: Any? var type: AHDBDataType? switch columnType { case SQLITE_INTEGER: type = .integer value = Int(sqlite3_column_int(stmt, i)) case SQLITE_FLOAT: type = .real value = Double(sqlite3_column_double(stmt, i)) case SQLITE3_TEXT: if let tempValue = sqlite3_column_text(stmt, i) { type = .text value = String(cString: tempValue) }else{ throw AHDBError.other(message: "Can not extract string from database") } case SQLITE_NULL: type = nil value = nil default: continue } let property = AHDBAttribute(key: columnName, value: value, type: type) singleRow.append(property) } results.append(singleRow) } return results } func delete(tableName: String, primaryKey: AHDBAttribute) throws { let cleanTableName = cleanUpString(str: tableName) let sql: String = "DELETE FROM \(cleanTableName) WHERE \(primaryKey.key) = ?" try executeSQL(sql: sql, bindings: [primaryKey]) } func delete(tableName: String, conditions: [AHDBAttribute]) throws { guard conditions.count > 0 else { return } let cleanTableName = cleanUpString(str: tableName) var sql = "DELETE FROM \(cleanTableName) WHERE " for i in 0..<conditions.count { let property = conditions[i] if i == conditions.count - 1 { sql += "\(property.key) = ?" }else{ sql += "\(property.key) = ? AND " } } try executeSQL(sql: sql, bindings: conditions) } func update(tableName: String, bindings: [AHDBAttribute], conditions: [AHDBAttribute]) throws { guard bindings.count > 0 else { return } let cleanTableName = cleanUpString(str: tableName) var sql = "UPDATE \(cleanTableName) SET " for i in 0..<bindings.count { let binding = bindings[i] if binding.isPrimaryKey && binding.value == nil { throw AHDBError.other(message: "primary must not be nil") } if i == bindings.count - 1 { sql += "\(binding.key) = ? " }else{ sql += "\(binding.key) = ?, " } } sql += "WHERE " for i in 0..<conditions.count { let condition = conditions[i] if condition.isPrimaryKey && condition.value == nil { throw AHDBError.other(message: "primary must not be nil") } if i == bindings.count - 1 { sql += "\(condition.key) = ? " }else{ sql += "\(condition.key) = ? AND " } } var newBindings = bindings newBindings.append(contentsOf: conditions) try executeSQL(sql: sql, bindings: newBindings) } func update(tableName: String, bindings: [AHDBAttribute], primaryKey: AHDBAttribute) throws { guard bindings.count > 0 else { return } let cleanTableName = cleanUpString(str: tableName) var sql = "UPDATE OR FAIL \(cleanTableName) SET " for i in 0..<bindings.count { let property = bindings[i] if i == bindings.count - 1 { sql += "\(property.key) = ? " }else{ sql += "\(property.key) = ?, " } } sql += "WHERE \(primaryKey.key) = ?" var newBindings = bindings newBindings.append(primaryKey) try executeSQL(sql: sql, bindings: newBindings) } func deleteTable(name: String) throws { let cleanTableName = cleanUpString(str: name) let sql: String = "DROP TABLE IF EXISTS \(cleanTableName)" try executeSQL(sql: sql, bindings: []) } /// Binding attributes's key is not required. It only binds values to '?'. /// Yet, attributes's type IS required if the value is one of real, integer, text. /// Attributes's type could be nil when NULL value needed. public func executeSQL(sql: String, bindings: [AHDBAttribute]) throws{ let stmt = try prepareStatement(sql: sql) defer { sqlite3_finalize(stmt) } try bind(stmt: stmt, bindings: bindings) guard sqlite3_step(stmt) == SQLITE_DONE else { throw AHDBError.step(message: latestError) } } private func bind(stmt: OpaquePointer, bindings: [AHDBAttribute]) throws { for i in 0..<bindings.count { let property = bindings[i] let type = property.type let valueRaw = property.value let position: Int32 = Int32(i + 1) try bindVaue(value: valueRaw, type: type, position: position, stmt: stmt) } } private func bindVaue(value: Any?, type: AHDBDataType?, position: Int32, stmt:OpaquePointer) throws { if value == nil{ let code = sqlite3_bind_null(stmt, position) if code != SQLITE_OK { throw AHDBError.bind(message: "Binding error") } return } guard let type = type else { throw AHDBError.bind(message: "Type must not be nil if the value is not nil") } var valueRaw: Any? if let value = value as? Bool { valueRaw = value ? 1 : 0 }else{ valueRaw = value } switch type { case .integer: if let valueInt = valueRaw as? Int { if let value = Int64(exactly: valueInt) { let code = sqlite3_bind_int64(stmt, position, Int64(value)) if code != SQLITE_OK { throw AHDBError.bind(message: "Binding error") } } }else{ throw AHDBError.bind(message: "Type error: can't convert value to Int64") } case .real: if let value = valueRaw as? Double { let code = sqlite3_bind_double(stmt, position, value) if code != SQLITE_OK { throw AHDBError.bind(message: "Binding error") } }else{ throw AHDBError.bind(message: "Type error: can't convert value to Double") } case .text: if let value = valueRaw as? String { /* https://stackoverflow.com/questions/1229102/when-to-use-sqlite-transient-vs-sqlite-static SQLITE_TRANSIENT tells SQLite to copy your string. Use this when your string('s buffer) is going to go away before the query is executed. SQLITE_STATIC tells SQLite that you promise that the pointer you pass to the string will be valid until after the query is executed. Use this when your buffer is, um, static, or at least has dynamic scope that exceeds that of the binding. */ let code = sqlite3_bind_text(stmt, position, value.cString(using: .utf8), -1, SQLITE_TRANSIENT) if code != SQLITE_OK { throw AHDBError.bind(message: "Binding error") } }else{ throw AHDBError.bind(message: "Type error: can't convert value to String") } } } } //MARK:- Private Methods extension AHDatabase { fileprivate func cleanUpString(str: String) -> String{ return str.replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "'", with: "").replacingOccurrences(of: ",", with: "") } fileprivate func prepareStatement(sql: String) throws -> OpaquePointer { guard let dbPointer = dbPointer else { throw AHDBError.preapre(message: "DB is not connected") } var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(dbPointer, sql, -1, &stmt, nil) == SQLITE_OK else { throw AHDBError.preapre(message: latestError) } // don't need to finalize stmt since this stmt is supposed to be used by the caller, e.g. bind or step return stmt! } }
34.170968
255
0.539932
2fe579fb7b5608ee54cacef547cd7cd1f7dab3a5
419
// // CustomCollectionViewCell.swift // AMScrollingCards_Example // // Created by ahmed.ehab on 3/19/19. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { @IBOutlet weak var myView: UIView! @IBOutlet weak var myLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
19.952381
54
0.696897
ddc3322c6a3144744ca8816344ff93a33899ff34
7,721
// github: https://github.com/MakeZL/MLSwiftBasic // author: @email <[email protected]> // // MBNavigationBarView.swift // MakeBolo // // Created by 张磊 on 15/6/22. // Copyright (c) 2015年 MakeZL. All rights reserved. // import UIKit protocol MBNavigationBarViewDelegate:NSObjectProtocol{ func goBack() } class MBNavigationBarView: UIView { var titleImage,leftImage,rightImage:String! var rightTitleBtns:NSMutableArray = NSMutableArray() var delegate:MBNavigationBarViewDelegate! var rightItemWidth:CGFloat{ set{ if (self.rightTitleBtns.count > 0 || self.rightImgs.count > 0) { var count = self.rightTitleBtns.count ?? self.rightImgs.count for (var i = 0; i < count; i++){ if var button = self.rightTitleBtns[i] as? UIButton ?? self.rightImgs[i] as? UIButton { button.frame.size.width = newValue var x = self.frame.size.width - newValue * CGFloat(i) - newValue button.frame = CGRectMake(x, NAV_BAR_Y, newValue, NAV_BAR_HEIGHT) ; } } }else { self.rightButton.frame.size.width = newValue self.rightButton.frame.origin.x = self.frame.size.width - newValue } } get{ return self.rightItemWidth } } var leftItemWidth:CGFloat { set{ } get{ return self.leftItemWidth } } var title:String{ set { self.titleButton.setTitle(newValue, forState: .Normal) } get { if (self.titleButton.currentTitle != nil) { return self.titleButton.currentTitle! }else{ return "" } } } var leftStr:String{ set { self.leftButton.setTitle(newValue, forState: .Normal) } get { if (self.leftButton.currentTitle != nil) { return self.leftButton.currentTitle! }else{ return "" } } } var rightImgs:NSArray{ set{ var allImgs = newValue.reverseObjectEnumerator().allObjects for (var i = 0; i < allImgs.count; i++){ var rightButton = UIButton.buttonWithType(.Custom) as! UIButton rightButton.tag = i rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) var x = self.frame.size.width - CGFloat(NAV_ITEM_RIGHT_W) * CGFloat(i) - NAV_ITEM_LEFT_W rightButton.setImage(UIImage(named: allImgs[i] as! String), forState: .Normal) rightButton.frame = CGRectMake(x, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ; rightButton.titleLabel?.font = NAV_ITEM_FONT self.addSubview(rightButton) rightTitleBtns.addObject(rightButton) } if (newValue.count > 1){ self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + newValue.count)) } } get{ return ( rightTitleBtns != false && rightTitleBtns.count > 0) ? rightTitleBtns: [] } } var rightTitles:NSArray{ set{ for (var i = 0; i < newValue.count; i++){ var rightButton = UIButton.buttonWithType(.Custom) as! UIButton rightButton.tag = i rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) var x = self.frame.size.width - CGFloat(NAV_ITEM_LEFT_W) * CGFloat(i) - NAV_ITEM_RIGHT_W rightButton.setTitle(newValue[i] as! NSString as String, forState: .Normal) rightButton.frame = CGRectMake(x, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ; rightButton.titleLabel?.font = NAV_ITEM_FONT self.addSubview(rightButton) self.rightTitleBtns.addObject(rightButton) } if (newValue.count > 1){ self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + newValue.count)) } } get{ return ( rightTitleBtns != false && rightTitleBtns.count > 0) ? rightTitleBtns: [] } } var rightStr:String{ set { self.rightButton.setTitle(newValue, forState: .Normal) } get { if (self.rightButton.currentTitle != nil) { return self.rightButton.currentTitle! }else{ return "" } } } var titleButton:UIButton{ get{ var titleButton = UIButton.buttonWithType(.Custom) as! UIButton titleButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) titleButton.frame = CGRectMake(NAV_ITEM_LEFT_W, NAV_BAR_Y, self.frame.size.width - NAV_ITEM_RIGHT_W - NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT); if (self.rightTitles.count > 1){ titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + self.rightTitles.count)) titleButton.frame.origin.x = CGFloat(self.frame.size.width - titleButton.frame.size.width) * 0.5 } titleButton.titleLabel?.font = NAV_TITLE_FONT self.addSubview(titleButton) return titleButton } } var leftButton:UIButton{ get{ var leftButton = UIButton.buttonWithType(.Custom) as! UIButton leftButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) leftButton.frame = CGRectMake(0, NAV_BAR_Y, NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT); leftButton.titleLabel?.font = NAV_ITEM_FONT self.addSubview(leftButton) return leftButton } } lazy var rightButton:UIButton = { var rightButton = UIButton.buttonWithType(.Custom) as! UIButton rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) rightButton.frame = CGRectMake(self.frame.size.width - NAV_ITEM_RIGHT_W, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ; rightButton.titleLabel?.font = NAV_ITEM_FONT self.addSubview(rightButton) return rightButton }() var back:Bool{ set{ if (newValue && (count(self.leftStr) <= 0 && self.leftStr.isEmpty)) { var backBtn = UIButton.buttonWithType(.Custom) as! UIButton backBtn.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) backBtn.setImage(UIImage(named: BACK_NAME), forState: .Normal) backBtn.titleLabel!.textAlignment = .Left backBtn.frame = CGRectMake(0, NAV_BAR_Y, NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT); backBtn.addTarget(self, action:"goBack", forControlEvents: .TouchUpInside) self.addSubview(backBtn) } } get{ return self.back } } func goBack(){ if self.delegate.respondsToSelector(Selector("goBack")) { self.delegate.goBack() } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } required override init(frame: CGRect) { super.init(frame: frame) self.setup() } func setup(){ } }
33.716157
147
0.553685
6a0d8ac2eb7b2784cf7fa8f742dac090bd9353c3
3,941
// // ViewController.swift // PornForTV // // Created by Tomoya_Hirano on H28/01/12. // Copyright © 平成28年 noppefoxwolf. All rights reserved. // import UIKit import Ji import AlamofireImage class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! let url = "http://jp.xvideos.com" var contents:[Content] = [] override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self let jiDoc = Ji(htmlURL: NSURL(string: url)!) let thumbBlocks = jiDoc?.xPath("//div[@class='thumbBlock']") for thumbBlock in thumbBlocks! { let thumbInside = thumbBlock.xPath("div[@class='thumbInside']").first let thumb = thumbInside?.xPath("div[@class='thumb']").first let title = thumbInside?.xPath("p/a").first?.content let image = thumb?.xPath("a/img").first?["src"] guard let link = thumbInside?.xPath("p/a").first?["href"] else {continue} let content = Content() content.title = title content.image = image content.link = url + link contents.append(content) } collectionView.reloadData() } func getDetails(content:Content){ print(content.link) let jiDoc = Ji(htmlURL: NSURL(string: content.link)!) let scripts = jiDoc?.xPath("//script") for script in scripts! { let pattern = "new HTML5Player\\((.+?)\\)+" let str:String = script.content! if Regexp(pattern).isMatch(str) { if let js = Regexp(pattern).matches(str)?.first { let alert = UIAlertController(title: content.title, message: "select source", preferredStyle: .Alert) for data in js.componentsSeparatedByString(",") { let raw = data.stringByReplacingOccurrencesOfString("'", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "") if let url = NSURL(string: raw) { if let _ = url.host { alert.addAction(UIAlertAction(title: url.absoluteString, style: .Default, handler: { (_) -> Void in self.showVideoVC(url) })) } } } alert.addAction(UIAlertAction(title: nil, style: .Cancel, handler: nil)) presentViewController(alert, animated: true, completion: nil) } } } } func showVideoVC(url:NSURL){ let vc = VideoViewController.viewController(url) presentViewController(vc, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return contents.count } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let content = contents[indexPath.row] getDetails(content) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionCell let content = contents[indexPath.row] cell.imageView.backgroundColor = UIColor.lightGrayColor() if let image = content.image,url = NSURL(string: image) { cell.imageView.af_setImageWithURL(url) } cell.label.text = content.title return cell } } class CollectionCell :UICollectionViewCell{ @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! } class Content:NSObject{ var title:String? var image:String? var link = "" }
31.782258
142
0.667597