blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
5e7a34a88e221a779ff410dc8ad63d4278a7c80e
Swift
yida98/RandomReminder
/RandomReminder/Views/ContentViewModel.swift
UTF-8
2,141
2.578125
3
[]
no_license
// // ContentViewModel.swift // RandomRemainder // // Created by Yida Zhang on 2021-05-03. // import Foundation import UIKit import SwiftUI import UserNotifications import Combine class ContentViewModel: ObservableObject { @Published var location: CGPoint = CGPoint(x: 0, y: 0) @Published var isReady: Bool = false { willSet { if newValue == true { Constants.hapticFeedback(.medium) } } } @Published var isPresenting: Bool = false @Published var adding: Bool = true @Published var allowsNotification: Bool = true var tappedAlarm: Alarm? { willSet { if newValue != nil { adding = false isPresenting = true } } } init() { UISetup() LocalNotificationManager.requestNotificationPermission { success, error in Just(success) .receive(on: RunLoop.main) .assign(to: &self.$allowsNotification) } } private func UISetup() { UIView.appearance().overrideUserInterfaceStyle = .light UITableView.appearance().backgroundColor = .clear UITableViewCell.appearance().backgroundColor = .clear } func openSettings() { UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:]) { value in } } var scale: CGFloat { var scale: CGFloat = 0 let difference = (location.y - Constants.scrollViewOffset) if difference > 0 && difference <= 120 { scale = (120 - difference)/120 } return scale } // func deleteAlarm(offsets: IndexSet) { // let objects = offsets.map { Storage.shared.alarms[$0] } // Storage.shared.alarms = Storage.shared.alarms.filter { object in // !objects.contains { alarm in // return object.id == alarm.id // } // } // } func addAlarm() { // let newAlarm = Alarm(text: "Whaaps") // Storage.shared.addAlarm(alarm: newAlarm) } }
true
f1f7f882792e6a204d6c56df362ef2b73a829742
Swift
akupriianets/nearbyPlaces
/NearbyPlaces/Modules/Home/HomeAssembly.swift
UTF-8
1,083
2.625
3
[]
no_license
// // HomeAssembly.swift // NearbyPlaces // // Created by Artem Kupriianets on 29.05.2021. // // import UIKit protocol HomeAssembling { func makeHome() -> UIViewController } // MARK: - final class HomeAssembly { private let placesListAssembly: PlacesListAssembling private let placesService: PlacesServiceProtocol init( placesListAssembly: PlacesListAssembling, placesService: PlacesServiceProtocol ) { self.placesListAssembly = placesListAssembly self.placesService = placesService } } // MARK: - HomeAssembling extension HomeAssembly: HomeAssembling { func makeHome() -> UIViewController { let coordinator = HomeCoordinator(makePlacesList: placesListAssembly.makePlacesList) let controller = HomeController( coordinator: coordinator, placesService: placesService ) let viewController = HomeViewController(controller: controller) controller.view = viewController coordinator.viewController = viewController return viewController } }
true
2ebdc6c78b7127c3e3914ff36749eb20cf8e34f7
Swift
AlexUmarovM/Chuck-Norris-Jokes
/Chuck Norris Jokes/TableViewControllers/JokeListTableViewCell.swift
UTF-8
739
2.625
3
[]
no_license
// // JokeListTableViewCell.swift // Chuck Norris Jokes // // Created by Александр Умаров on 20.06.2020. // Copyright © 2020 Александр Умаров. All rights reserved. // import UIKit class JokeListTableViewCell: UITableViewCell { @IBOutlet var cellLabel: UILabel! @IBOutlet var cellView: UIImageView! func getProperties(){ DispatchQueue.global().async { guard let stringURL = JokesList.shared.imageURL else { return } guard let imageURL = URL(string: stringURL) else { return } guard let imageData = try? Data(contentsOf: imageURL) else { return } DispatchQueue.main.async { self.cellView.image = UIImage(data: imageData) } } } }
true
7db71291c0f0ca37862d68b20231fbc89429131e
Swift
eric9102/SwiftPlayground
/SwiftTips.playground/Pages/@escaping.xcplaygroundpage/Contents.swift
UTF-8
1,146
4.4375
4
[ "Apache-2.0" ]
permissive
//: [Previous](@previous) import Foundation func doWork(block: ()->()) { //block()在方法内是同步执行的 block() } doWork { print("work") } // MARK: - @escaping 逃逸闭包 func doWorkAsync(block: @escaping ()->()) { DispatchQueue.main.async { block() } } class S { var foo = "foo" func method1() { doWork { print(foo) } foo = "bar" } func method2() { doWorkAsync { print(self.foo) // Reference to property 'foo' in closure requires explicit 'self.' to make capture semantics explicit } foo = "bar" } // MARK: - 如果不想在闭包中持有self,可以使用[weak self]的方式来表达 func method3() { doWorkAsync { [weak self] in print(self?.foo ?? "nil") } foo = "bar" } } S().method1() // foo S().method2() //闭包持有了self,打印的事最后对foo赋值后的内容bar S().method3() //: [Next](@next)
true
911baced8abe825df29d05181a140561ba9d8123
Swift
MorganTrudeau/Huddl
/Helloquent/Model/CodableStructs.swift
UTF-8
844
2.703125
3
[]
no_license
// // CodableStructs.swift // Helloquent // // Created by Morgan Trudeau on 2018-02-01. // Copyright © 2018 Morgan Trudeau. All rights reserved. // import Foundation struct User: Codable { let id: String var name: String var color: String var avatar: String var chats: [String:String] } struct Chat: Codable { let id: String let name: String let avatar: String } struct Room: Codable { var name: String var description: String let id: String var password: String var likes: Int } struct LocationRoom: Codable { var name: String var description: String let id: String var password: String var likes: Int var latitude: String var longitude: String } struct Message: Codable { let senderID: String let senderName: String let text: String let url: String }
true
02634b66210e567efe834c8dd50813ad025c9c0e
Swift
DuckSowl/AnyTask
/AnyTask/Model/CoreData/TaskCoreDataManager/Task(MO)+.swift
UTF-8
1,352
2.765625
3
[]
no_license
// // Task(MO)+.swift // AnyTask // // Created by Anton Tolstov on 06.08.2020. // Copyright © 2020 Anton Tolstov. All rights reserved. // import Foundation // MARK: Task Extensions extension Task: IdentifiableObject { } extension Task: ManagedObjectInitializable { init(managedObject taskMO: TaskMO) { id = taskMO.id.unsafeUUID() title = taskMO.title comment = taskMO.comment deadline = taskMO.deadline if let projectMO = taskMO.project { project = Project(managedObject: projectMO) } completed = taskMO.completed time = Time(expected: taskMO.expectedTime, spent: taskMO.spentTime) } } // MARK: TaskMO Extensions extension TaskMO: IdentifiableObject { typealias IdentityType = Data } // MARK: Time Extensions extension Task.Time { var expectedForMO: Int32 { expected.int32OrMinusOne } var spentForMO: Int32 { spent.int32OrMinusOne } init(expected: Int32, spent: Int32) { self.init(expected: (expected != -1) ? (UInt)(expected) : nil, spent: (spent != -1) ? (UInt)(spent) : nil) } } // MARK: Optional(UInt) Fileprivate Extensions fileprivate extension Optional where Wrapped == UInt { var int32OrMinusOne: Int32 { return (self != nil && self! < Int32.max) ? (Int32)(self!) : -1 } }
true
2a694ff81149fe5d79683d27f31b3c92ccb91d4c
Swift
kylestremdev/selfiewars
/selfieCompetition/OutlinedText.swift
UTF-8
1,267
2.78125
3
[]
no_license
// // OutlinedText.swift // selfieCompetition // // Created by Kyle Strem on 4/24/17. // Copyright © 2017 Kyle Strem. All rights reserved. // import UIKit @IBDesignable class OutlinedText: UILabel { var strokeTextAttributes = [ NSStrokeColorAttributeName : UIColor.black, NSForegroundColorAttributeName : UIColor.white, NSStrokeWidthAttributeName : -1.0, ] as [String : Any] @IBInspectable var outlineColor: UIColor = UIColor.black { didSet{ strokeTextAttributes["NSStrokeColorAttributeName"] = outlineColor self.attributedText = NSAttributedString(string: self.text!, attributes: strokeTextAttributes) } } @IBInspectable var inlineColor: UIColor = UIColor.white { didSet{ strokeTextAttributes["NSForegroundColorAttributeName"] = inlineColor self.attributedText = NSAttributedString(string: self.text!, attributes: strokeTextAttributes) } } @IBInspectable var outlineWidth: Float = -1.0 { didSet{ strokeTextAttributes["NSStrokeWidthAttributeName"] = outlineWidth self.attributedText = NSAttributedString(string: self.text!, attributes: strokeTextAttributes) } } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() } }
true
003dcef8a6dd009b36ee2623ec415634946c1465
Swift
eastsss/ErrorDispatching
/ErrorDispatching/Classes/Core/MethodProposers/DebugMethodProposer.swift
UTF-8
686
2.703125
3
[ "MIT" ]
permissive
// // DebugMethodProposer.swift // ErrorDispatching // // Created by Anatoliy Radchenko on 04/03/2017. // // import Foundation public class DebugMethodProposer: MethodProposing { public init() {} public func proposeMethod(toHandle error: Error) -> Proposition? { let format = StandardErrorString.message(forKey: "debug-format") let message = String(format: format, "\(error)") let config = SystemAlertConfiguration( title: StandardErrorString.title(forKey: "debug"), message: message, actionTitle: StandardErrorString.action(forKey: "ok") ) return .single(.systemAlert(config)) } }
true
6b08e5464f7405d0c1411764184329dca1620f2c
Swift
daniel-jd/SongBook
/SongsBook/SongList/SongsListViewController.swift
UTF-8
4,229
2.671875
3
[]
no_license
// // TableViewController.swift // TableViewTest // // Created by Daniel Yamrak on 15.09.2020. // Copyright © 2020 DanielYarmak. All rights reserved. // import UIKit import Firebase class SongsListViewController: UITableViewController, AddSongDelegate { public var songsList = [Song]() //var numberOfSongs: Int? // This should change status bar to light color override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent } override func viewDidLoad() { super.viewDidLoad() setTableView() print("🍄 viewDidLoad called") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setNeedsStatusBarAppearanceUpdate() // DOSEN'T WORK!!! loadSongsFromDatabase() } deinit { print("🔥 deinit \(K.ViewController.SongsList)") } @IBAction func didTapMenuButton(_ sender: UIBarButtonItem) { panel?.openLeft(animated: true) } @IBAction func addSongButton(_ sender: UIBarButtonItem) { let storyboard = UIStoryboard(name: K.Storyboard.AddSong, bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: K.ViewController.AddSong) as! AddSongViewController vc.addSongDelegate = self navigationController?.pushViewController(vc, animated: true) } private func loadSongsFromDatabase() { let songManager = SongManager() songManager.fetchSongs({ [weak self] songs in self?.songsList = songs self?.tableView.reloadData() }) } func addNewSong(song: Song) { songsList.append(song) let newIndexPath = IndexPath(row: songsList.count - 1, section: 0) tableView.beginUpdates() tableView.insertRows(at: [newIndexPath], with: .automatic) tableView.endUpdates() } // TODO: - Save local songsList func saveSongsListToUserDefaults() { print("saveSongsListToUserDefaults() called") } private func setTableView() { tableView.rowHeight = UITableView.automaticDimension //tableView.estimatedRowHeight = 72.0 tableView.rowHeight = 72 title = "Songs" } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return songsList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Say that we'll use our own custom cell from SongCell class let cell = tableView.dequeueReusableCell(withIdentifier: K.Cell.SongCell, for: indexPath) as! SongCell let song = songsList[indexPath.row] cell.set(song: song) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) // Programmatic way of transition to another screen let storyboard = UIStoryboard(name: K.Storyboard.SongDisplay, bundle: nil) let vc = storyboard.instantiateViewController(identifier: K.ViewController.SongDisplay) as! SongDisplayViewController // TODO: Probably this could be substitute with a delegate or another function vc.song.title = songsList[indexPath.row].title vc.song.artist = songsList[indexPath.row].artist vc.song.key = songsList[indexPath.row].key vc.song.tempo = songsList[indexPath.row].tempo vc.song.songBody = songsList[indexPath.row].songBody navigationController?.pushViewController(vc, animated: true) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { songsList.remove(at: indexPath.row) tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: .automatic) tableView.endUpdates() } } } // Class
true
0ddc1bce33c162c7827349c5f99746f1752c3d53
Swift
Flawlesboy/SpiritFilm
/TheMovieList/1. PresentationLayer/Modules/MovieList/Presenter/MovieListPresenter.swift
UTF-8
1,460
2.734375
3
[]
no_license
// // MovieListPresenter.swift // TheMovieList // // Created by omar on 01/08/2019. // Copyright © 2019 zagid. All rights reserved. // import Foundation class MovieListPresenter { weak var view: MovieListViewInput! var interactor: MovieListInteractorInput! var router: MovieListRouterInput! } extension MovieListPresenter: MovieListViewOutput { func viewIsReady() { view.setupInitialState() interactor.loadMovies(page: 1) interactor.loadPopularMovies(page: 1) interactor.loadTopRatedMovies(page: 1) } func buttonIsReady() { router.presentSearchView() } func didSelect(movie: Movie) { router.presentDetailView(movies: movie) } } extension MovieListPresenter: MovieListInteractorOutput { func didLoadPopularMoviesSuccessfully(movies: [Movie]) { let movies = movies.filter { $0.posterPath != nil && $0.backdropPath != nil && $0.overview != nil } view.showPopular(movies: movies) } func didLoadTopRatedMoviesSuccessfully(movies: [Movie]) { let movies = movies.filter { $0.posterPath != nil && $0.backdropPath != nil && $0.overview != nil } view.showTopRaited(movies: movies) } func didLoadMoviesSuccessfully(movies: [Movie]) { let movies = movies.filter { $0.posterPath != nil && $0.backdropPath != nil && $0.overview != nil } view.show(movies: movies) } }
true
d8d94ae2360f34ad7b6a84192b752515e72e0819
Swift
Alamofire/Alamofire
/Source/Result+Alamofire.swift
UTF-8
4,629
3
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Result+Alamofire.swift // // Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type. public typealias AFResult<Success> = Result<Success, AFError> // MARK: - Internal APIs extension Result { /// Returns whether the instance is `.success`. var isSuccess: Bool { guard case .success = self else { return false } return true } /// Returns whether the instance is `.failure`. var isFailure: Bool { !isSuccess } /// Returns the associated value if the result is a success, `nil` otherwise. var success: Success? { guard case let .success(value) = self else { return nil } return value } /// Returns the associated error value if the result is a failure, `nil` otherwise. var failure: Failure? { guard case let .failure(error) = self else { return nil } return error } /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. /// /// - Parameters: /// - value: A value. /// - error: An `Error`. init(value: Success, error: Failure?) { if let error = error { self = .failure(error) } else { self = .success(value) } } /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. /// /// Use the `tryMap` method with a closure that may throw an error. For example: /// /// let possibleData: Result<Data, Error> = .success(Data(...)) /// let possibleObject = possibleData.tryMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance. /// /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the /// same failure. func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> Result<NewSuccess, Error> { switch self { case let .success(value): do { return try .success(transform(value)) } catch { return .failure(error) } case let .failure(error): return .failure(error) } } /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. /// /// Use the `tryMapError` function with a closure that may throw an error. For example: /// /// let possibleData: Result<Data, Error> = .success(Data(...)) /// let possibleObject = possibleData.tryMapError { /// try someFailableFunction(taking: $0) /// } /// /// - Parameter transform: A throwing closure that takes the error of the instance. /// /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns /// the same success. func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> Result<Success, Error> { switch self { case let .failure(error): do { return try .failure(transform(error)) } catch { return .failure(error) } case let .success(value): return .success(value) } } }
true
2c7026c76dd17df50c0dd4e0854a708d3c14f74e
Swift
imagineon/ViewConfigurator
/Tests/UIImageViewSpecs.swift
UTF-8
2,320
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
import Quick import Nimble import ViewConfigurator class UIImageViewSpec: QuickSpec { override func spec() { describe("UIViewConfigurator") { it("can set image") { let image = UIImage() let testViewConfig = UIImageView.config .image(image) let testView = UIImageView().apply(testViewConfig) expect(testView.image).to(equal(image)) } it("can set highlighted image") { let image = UIImage() let testViewConfig = UIImageView.config .highlightedImage(image) let testView = UIImageView().apply(testViewConfig) expect(testView.highlightedImage).to(equal(image)) } it("can set animation images") { let images = [UIImage(), UIImage()] let testViewConfig = UIImageView.config .animationImages(images) let testView = UIImageView().apply(testViewConfig) expect(testView.animationImages).to(equal(images)) } it("can set highlighted animation images") { let images = [UIImage(), UIImage()] let testViewConfig = UIImageView.config .highlightedAnimationImages(images) let testView = UIImageView().apply(testViewConfig) expect(testView.highlightedAnimationImages).to(equal(images)) } it("can set animation duration") { let duration = TimeInterval(50) let testViewConfig = UIImageView.config .animationDuration(duration) let testView = UIImageView().apply(testViewConfig) expect(testView.animationDuration).to(equal(duration)) } it("can set animation duration") { let count = 50 let testViewConfig = UIImageView.config .animationRepeatCount(count) let testView = UIImageView().apply(testViewConfig) expect(testView.animationRepeatCount).to(equal(count)) } } } }
true
08f3c1c0cf3db129d6e7b23d81a673cea620dfb1
Swift
lyp1992/OBJECT_BASIC
/Swift/道长-算法/道长-算法/ArrayToStack.swift
UTF-8
627
3.03125
3
[]
no_license
// // ArrayToStack.swift // 道长-算法 // // Created by 赖永鹏 on 2019/4/16. // Copyright © 2019年 LYP. All rights reserved. // import Cocoa class ArrayToStack: NSObject { var stack : [AnyObject] var isEmpty : Bool { return stack.isEmpty } var peek : AnyObject? { return stack.last } override init() { stack = [AnyObject]() } func push(_ object: AnyObject) { stack.append(object) } func pop() -> AnyObject? { if !isEmpty { return stack.removeLast() }else{ return nil } } }
true
f742a5ec98f1f05a5edbd756e6cbd883b709739d
Swift
vctrsmelo/SongList
/Shuffle Songs/Shuffle Songs/Flows/Shuffle List/ShuffleListViewModel.swift
UTF-8
5,615
3.375
3
[]
no_license
// // ShuffleListViewModel.swift // Shuffle Songs // // Created by Victor S Melo on 30/08/19. // Copyright © 2019 Victor S Melo. All rights reserved. // import Foundation import UIKit //only imported for UIImage in CellData protocol ShuffleListViewModelDelegate { func didUpdateSongs(viewModel: ShuffleListViewModel) func updateView(_ state: ViewState, viewModel: ShuffleListViewModel) } class ShuffleListViewModel { // MARK: - Subelements struct CellData { let title: String let subtitle: String let image: UIImage init(song: Song) { self.title = song.trackName self.subtitle = song.artistName guard let data = song.artworkData, let image = UIImage(data: data) else { self.image = UIImage() return } self.image = image } } // MARK: - Properties let artistsIDs: [String] let service: SongsService var delegate: ShuffleListViewModelDelegate? var viewState: ViewState = .empty { didSet { self.delegate?.updateView(viewState, viewModel: self) } } // all songs received from service private var cacheSongs: [Song]? = [] // songs to be displayed to user private var shuffledItems: [CellData] = [] { didSet { self.delegate?.didUpdateSongs(viewModel: self) } } var itemLength: Int { return shuffledItems.count } // MARK: - Init init(artistsIDs: [String], service: SongsService) { self.service = service self.artistsIDs = artistsIDs loadSongs() } // MARK: - Service func fetchSongs(completion: @escaping ([Song]?) -> Void) { service.fetchSongs(artistsIds: artistsIDs) { [weak self] result in guard let self = self else { return } switch result { case .success(let songs): self.cacheSongs = songs self.syncIfNeeded { completion(songs) } case .failure(let error): print("[ShuffleListViewModel Error] \(error.localizedDescription)") completion(nil) } } } private func fetchArtworks(_ songs: [Song], completion: @escaping ([Song]) -> Void) { let fetchArtworkGroup = DispatchGroup() var returnSongs = songs for i in 0 ..< songs.count { // should not fetch again previously fetched artworkData if songs[i].artworkData != nil { continue } fetchArtworkGroup.enter() service.fetchAlbumImageData(imageURL: songs[i].artworkUrl) { result in switch result { case .failure(let error): print("could not fetch artwork from URL: \(songs[i].artworkUrl). Error: \(error.localizedDescription)") case .success(let data): returnSongs[i].artworkData = data } fetchArtworkGroup.leave() } } // wait all artworks to be fetched before completion fetchArtworkGroup.notify(queue: .main) { completion(returnSongs) } } // MARK: - User Actions func didTapShuffleButton() { guard let cacheSongs = cacheSongs else { return } viewState = .loading // async to prevent shuffle algorithm freezing UI DispatchQueue.global().async { [weak self] in guard let self = self else { return } let items = self.getShuffled(cacheSongs).map { CellData(song: $0) } DispatchQueue.main.sync { self.shuffledItems = items self.viewState = .showing } } } // MARK: - Others func loadSongs() { self.viewState = .loading fetchSongs { [weak self] maybeSongs in guard let self = self else { return } guard let songs = maybeSongs else { self.viewState = .error(title: "Network Error", description: "Could not display songs. Please, try again later.") return } self.fetchArtworks(songs, completion: { songs in self.cacheSongs = songs self.shuffledItems = songs.map { CellData(song: $0) } self.viewState = .showing }) } } func getItem(at index: Int) -> CellData { return shuffledItems[index] } /** - Returns: Return songs shuffled, where two songs from same artist aren't next each other, if possible. */ public func getShuffled(_ songs: [Song]) -> [Song] { let customShuffle = CustomShuffle(from: songs) return customShuffle.shuffled() } /// Sync closure to main thread for UI updates. /// - Important: This logic is here because it is not Service responsibility to keep it sync, as it is something importante for view update, and ViewController (delegate) should not know that something is being updated in background thread or not. func syncIfNeeded(_ closure: () -> Void) { // unit tests uses main thread, as service is mocked. if Thread.isMainThread { closure() } else { DispatchQueue.main.sync{ closure() } } } }
true
70a0fc29cca39f313822c757d22a44823dde646b
Swift
NavneetSinghGill/Peruze
/Peruze/Main View Controllers/Upload/DeleteItemOperation.swift
UTF-8
6,023
2.65625
3
[]
no_license
// // File.swift // Peruze // // Created by stplmacmini11 on 16/11/15. // Copyright © 2015 Peruze, LLC. All rights reserved. // import Foundation import CloudKit import SwiftLog private let logging = true class DeleteItemOperation: GroupOperation{ private struct Constants { static let locationAccuracy: CLLocationAccuracy = 2000 //meters } let operationQueue = OperationQueue() let presentationContext: UIViewController let errorCompletionHandler: (Void -> Void) init(recordIDName: String? = nil, presentationContext: UIViewController, database: CKDatabase = CKContainer.defaultContainer().publicCloudDatabase, context: NSManagedObjectContext = managedConcurrentObjectContext, completionHandler: (Void -> Void) = { }, errorCompletionHandler: (Void -> Void) = { }) { if logging { logw("DeleteItemOperation " + __FUNCTION__ + " in " + __FILE__ + ". ") } let item = Item.MR_findFirstByAttribute("recordIDName", withValue: recordIDName, inContext: context) /* This operation is made of four child operations: 1. the operation to delete the item from the cloud kit key value storage 2. the operation to delete the item from core data storage 3. finishing operation that calls the completion handler */ let deleteFromCloudItemOp = DeleteItemFromLocalStorageToCloudOperation( objectID: item.objectID, database: database, context: context ) let deleteFromLocalItemOp = DeleteItemFromLocalStorageOperation( objectID: item.objectID, context: context ) let finishOp = BlockOperation(block: { (continueWithError) -> Void in completionHandler() }) let presentNoLocOperation = AlertOperation(presentationContext: presentationContext) presentNoLocOperation.title = "No Location" presentNoLocOperation.message = "We were unable to access your location. We need your location to be able to show your item to the most relevant people! Please navigate to your Settings and allow location services for Peruze to upload an item." //add dependencies deleteFromLocalItemOp.addDependency(deleteFromCloudItemOp) finishOp.addDependency(deleteFromLocalItemOp) finishOp.addDependency(deleteFromCloudItemOp) var operationsToInit = [Operation]() operationsToInit = [deleteFromLocalItemOp, deleteFromCloudItemOp, finishOp] //setup local vars operationQueue.name = "Post Item Operation Queue" self.presentationContext = presentationContext self.errorCompletionHandler = errorCompletionHandler //initialize super.init(operations: operationsToInit) //add observers addObserver(NetworkObserver()) } override func finished(errors: [NSError]) { if errors.first != nil { let alert = AlertOperation(presentationContext: presentationContext) alert.title = "Ouch :(" alert.message = "There was a problem uploading your item to the server." produceOperation(alert) errorCompletionHandler() } } } /// Saves the given item to the local core data storage class DeleteItemFromLocalStorageOperation: Operation { let context: NSManagedObjectContext let objectID: NSManagedObjectID init(objectID: NSManagedObjectID, context: NSManagedObjectContext = managedConcurrentObjectContext) { if logging { logw("DeleteItemFromLocalStorageOperation " + __FUNCTION__ + " in " + __FILE__ + ". ") } self.context = context self.objectID = objectID super.init() } override func execute() { if logging { logw("DeleteItemFromLocalStorageOperation " + __FUNCTION__ + " in " + __FILE__ + ". ") } do { let localItem = try context.existingObjectWithID(self.objectID) context.deleteObject(localItem) } catch { logw("DeleteItemFromLocalStorageOperation failed with error: \(error)") } logw("Deleting Item from Persistent Store and Waiting...") context.MR_saveToPersistentStoreAndWait() finish() } override func finished(errors: [NSError]) { if let firstError = errors.first { logw("DeleteItemFromLocalStorageOperation finished with an error: \(firstError)") } else { logw("DeleteItemFromLocalStorageOperation finished successfully") } } } /// Uploads the given item record ID from local storage to CloudKit class DeleteItemFromLocalStorageToCloudOperation: Operation { let database: CKDatabase let context: NSManagedObjectContext let objectID: NSManagedObjectID init(objectID: NSManagedObjectID, database: CKDatabase, context: NSManagedObjectContext = managedConcurrentObjectContext) { if logging { logw("DeleteItemFromLocalStorageToCloudOperation " + __FUNCTION__ + " in " + __FILE__ + ". ") } self.database = database self.context = context self.objectID = objectID super.init() addObserver(NetworkObserver()) } override func execute() { if logging { logw("DeleteItemFromLocalStorageToCloudOperation " + __FUNCTION__ + " in " + __FILE__ + ". ") } do { let itemToDelete = try context.existingObjectWithID(objectID) //update server storage let recordIDName = itemToDelete.valueForKey("recordIDName") as? String let deleteItemRecordOp = CKModifyRecordsOperation(recordsToSave: nil, recordIDsToDelete: [CKRecordID(recordName: recordIDName!)]) deleteItemRecordOp.modifyRecordsCompletionBlock = { (savedRecords, _, error) -> Void in //print any returned errors if error != nil { logw("UploadItem returned error: \(error)") } self.finish() } deleteItemRecordOp.qualityOfService = qualityOfService database.addOperation(deleteItemRecordOp) } catch { logw("DeleteItemFromLocalStorageToCloudOperation failed with error: \(error)") self.finish() } } }
true
ccae629be4ef1eea452bd0bce04987dfaa6d16d1
Swift
elongmusk39/GoChat1
/GoChat1/ViewControllers/screen2/Photo and location/PhotoArrayViewController.swift
UTF-8
8,297
2.734375
3
[]
no_license
// // PhotoArrayViewController.swift // GoChat // // Created by Long Nguyen on 8/16/21. // import UIKit import Firebase private let cellArrayID = "cellArrayID" class PhotoArrayViewController: UIViewController { private var photoArray = [Picture]() var userEmail = "" private var indexItem: Int! //got value from ImagesVC to scroll to the right img private var justDelete = false //MARK: - Components //"lazy var" since we gotta register the cell after loading private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.delegate = self cv.dataSource = self cv.backgroundColor = .black cv.register(PhotoItem.self, forCellWithReuseIdentifier: cellArrayID) cv.showsVerticalScrollIndicator = false cv.showsHorizontalScrollIndicator = false cv.isPagingEnabled = true return cv }() //MARK: - View Scenes //got value from PhotoVC init(imgArray: [Picture], indexValue: Int) { self.photoArray = imgArray self.indexItem = indexValue super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureUI() swipeGesture() scrollToImage(value: indexItem) } //let's set default color for status bar override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } private func configureUI() { view.addSubview(collectionView) collectionView.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor) } //MARK: - Actions private func swipeGesture() { let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(dismissPhotoArray)) swipeDown.direction = .down view.addGestureRecognizer(swipeDown) } private func scrollToImage(value: Int) { print("DEBUG-PhotoArrayVC: scrolling to img \(value)..") collectionView.scrollToItem(at: IndexPath(item: value, section: 0), at: .centeredHorizontally, animated: true) } @objc func dismissPhotoArray() { dismiss(animated: true, completion: nil) if justDelete { NotificationCenter.default.post(name: .deleteItem, object: nil) } } //MARK: - Deletion private func deleteAlert(rowIndex: Int) { let alert = UIAlertController (title: "Deleted this item?", message: "This photo will be permanently deleted from the server", preferredStyle: .alert) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) let delete = UIAlertAction (title: "Delete", style: .destructive) { delete in self.nowDelete(rowNumber: rowIndex) } alert.addAction(cancel) alert.addAction(delete) present(alert, animated: true, completion: nil) } private func nowDelete(rowNumber: Int) { print("DEBUG-PhotoArrayVC: deletion \(rowNumber) confirmed..") self.showLoadingView(true, message: "Deleting..") let timeTaken = photoArray[rowNumber].timestamp let nameStorage = "\(photoArray[rowNumber].timestamp)-\(photoArray[rowNumber].city)" let ref = Storage.storage().reference(withPath: "/library/\(userEmail)/\(nameStorage)") ref.delete { error in if let e = error?.localizedDescription { self.alert(error: e, buttonNote: "Try Again") return } print("DEBUG-PhotoArrayVC: done delete in storage, now in firestore..") Firestore.firestore().collection("users").document(self.userEmail).collection("library").document(timeTaken).delete { error in self.showLoadingView(false, message: "Deleting..") if let e = error?.localizedDescription { self.alert(error: e, buttonNote: "Try again") return } print("DEBUG-PhotoArrayVC: sucessfully deleting item") self.justDelete = true self.doneDeletion(idx: rowNumber) } } } private func doneDeletion(idx: Int) { if idx == 0 && photoArray.count > 1 { photoArray.remove(at: idx) collectionView.reloadData() scrollToImage(value: idx) //should be idx+1 but we reload data } else if idx == photoArray.count-1 && photoArray.count>1 { photoArray.remove(at: idx) collectionView.reloadData() scrollToImage(value: idx) //should be idx-1 but we reload data } else if photoArray.count == 1 { dismissPhotoArray() } else if photoArray.count > 2 && idx>0 && idx<photoArray.count-1 { photoArray.remove(at: idx) collectionView.reloadData() scrollToImage(value: idx) //should be idx+1 or -1 but we reload data } } } //MARK: - collectionView datasource //remember to write ".delegate = self" to enable all of extensions extension PhotoArrayViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photoArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellArrayID, for: indexPath) as! PhotoItem cell.photoInfo = photoArray[indexPath.row] cell.numberArray = photoArray.count cell.photoIndex = indexPath.row //assign the index to each item cell.delegate = self //to make protocols work return cell } } //MARK: - DelegateFlowlayout and Delegate extension PhotoArrayViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } //spacing for row (horizontally) between items func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0.0 } //spacing for collumn (vertically) between items func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0.0 } //set size for each item func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let size = collectionView.frame.size return CGSize(width: size.width, height: size.height) } } //MARK: - Protocol from PhotoItem //remember to write ".delegate = self" in Datasource extension PhotoArrayViewController: PhotoItemDelegate { func dismissVC() { dismissPhotoArray() } func showMapView(_ cell: PhotoItem, time: String) { let vc = MapPhotoViewController(timeOfPhoto: time) vc.modalTransitionStyle = .coverVertical vc.modalPresentationStyle = .fullScreen vc.currentEmail = userEmail present(vc, animated: true, completion: nil) } func shareImage(imgShare: UIImage) { let shareText = "Share Image" let vc = UIActivityViewController(activityItems: [shareText, imgShare], applicationActivities: nil) present(vc, animated: true, completion: nil) } func deleteImage(index: Int) { deleteAlert(rowIndex: index) } }
true
9164e2ed1b1ff31da1d585c3c2a013f046a2b4f7
Swift
adealmeida/Restivus
/Tests/RawDecodableSpec.swift
UTF-8
1,421
2.6875
3
[ "Apache-2.0" ]
permissive
// // RawDecodableSpec.swift // Restivus // // Created by Ryan Baldwin on 2017-08-31. //Copyright © 2017 bunnyhug.me. All rights governed under the Apache 2 License Agreement // import Quick import Nimble @testable import Restivus struct RawDelete: Deletable { typealias ResponseType = Raw var path: String = "/204" } struct GetGoogle: Gettable { typealias ResponseType = Raw var baseURL = "http://www.google.ca" var path = "/" } class RawDecodableSpec: QuickSpec { override func spec() { describe("A Restable using Raw for Decodable") { it("can handle empty response body") { var data: Data? _ = try? RawDelete().submit { if case let .success(responseData) = $0 { data = responseData } } expect(data).toEventuallyNot(beNil(), timeout: 3) } it("can handle non-empty response body") { var data: Data? _ = try? GetGoogle().submit { if case let .success(responseData) = $0 { data = responseData } } expect(data).toEventuallyNot(beNil(), timeout: 3) expect(data!.count) > 0 } } } }
true
653724d217ae076dc543f6e0f5e602e98d4d6ede
Swift
clemente806/Jump-The-Junk-
/JumpTheJunkTV/Classes/ActionNode/ActionNode.swift
UTF-8
2,997
2.71875
3
[]
no_license
// // ActionNode.swift // JumpTheJunkTV // // Created by Clemente Piscitelli on 01/07/2019. // Copyright © 2019 Clemente Piscitelli. All rights reserved. // import UIKit import SpriteKit class ActionNode: SKSpriteNode { var actionImage:SKAction! var unfocusedImage: SKTexture! var player = SKAction() var fitJumpAnimation = [SKTexture]() var levelsCompleted = 1 var levelsCompleted2 = 2 var label : String! private var fitRun = FitRun() private var fitRunAnimation = [SKTexture](); private var animateFitRunAction = SKAction(); override var canBecomeFocused: Bool { return true } func setFocusedImage(named name: String) { unfocusedImage = self.texture isUserInteractionEnabled = true } // livelli sbloccati func initializeButtonFitRun(){ fitRunAnimation.removeAll() name = "FitRun"; for i in 1...12 { let name = "fitR\(i)"; fitRunAnimation.append(SKTexture(imageNamed: name)); } animateFitRunAction = SKAction.animate(with: fitRunAnimation, timePerFrame: 0.07, resize: false, restore: false); self.run(SKAction.repeatForever(animateFitRunAction)); } // Livelli bloccati func initializeButtonFitRunBlock(){ fitRunAnimation.removeAll() name = "FitRun"; for i in 1...12 { let name = "fitRB\(i)"; fitRunAnimation.append(SKTexture(imageNamed: name)); } animateFitRunAction = SKAction.animate(with: fitRunAnimation, timePerFrame: 0.07, resize: false, restore: true); self.run(SKAction.repeatForever(animateFitRunAction)); } // Restart livello func initializeButtonRestart(){ fitRunAnimation.removeAll() name = "FitRun"; for i in 1...12 { let name = "fitRB\(i)"; fitRunAnimation.append(SKTexture(imageNamed: name)); } animateFitRunAction = SKAction.animate(with: fitRunAnimation, timePerFrame: 0.07, resize: false, restore: true); self.run(SKAction.repeatForever(animateFitRunAction)); } /* Se il levelsCompleted o levelsCompleted2 sono uguali a int(self.label) allora puoi mettere l'animazione del bambino che corre senza divieto */ func didGainFocus() { if levelsCompleted == Int(self.label) || levelsCompleted2 == Int(self.label){ initializeButtonFitRun() } else { initializeButtonFitRunBlock() } } func didLoseFocus() { removeAllActions() texture = unfocusedImage } func didGainFocusRestartButton(){ self.texture = SKTexture(imageNamed: "restartFocus") } func didGainFocusBacktoMenuButton(){ self.texture = SKTexture(imageNamed: "mainmenuFocus") } }
true
34751bc539d99fb24583bc0277f5522175e56cb1
Swift
shubham980/Overall-Diet-master
/OverAll Diet/NotesTableViewController.swift
UTF-8
5,225
3.15625
3
[]
no_license
// // NotesTableViewController.swift // OverAll Diet // // Created by Harshita Trehan on 14/04/19. // Copyright © 2019 Deakin. All rights reserved. // /* This class display the notes saved on the phone in the form of table and the notes can be expanded in the notes view controller class, also this class provides an option to add new notes and updates accordingly to changes made in the existing notes*/ import UIKit class NotesTableViewController: UITableViewController , NoteViewDelegate { @IBOutlet var table: UITableView! var homeBarButton = UIBarButtonItem() override func viewWillAppear(_ animated: Bool) { // Defining the left navigation bar item homeBarButton = UIBarButtonItem(title: "Home", style: .done, target: self, action: #selector(backTap1)) self.navigationItem.leftBarButtonItem = homeBarButton } //array to store the notes //keys = "title" ,"body" var arrNotes = [[String: String]]() //for locating the index value of the note selected var selectedNoteindex = -1 override func viewDidLoad() { super.viewDidLoad() //downcasting if let newNotes = UserDefaults.standard.array(forKey: "notes") as? [[String:String]] { //set the instsance value to the the new note arrNotes = newNotes } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return the number of elements in the table, in this case we have taken the from the array return arrNotes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //get the default cell let cell = tableView.dequeueReusableCell(withIdentifier: "CELL") as! UITableViewCell //set the text cell.textLabel!.text = arrNotes[indexPath.row]["title"] //return the updated/modified cell return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //set the index of the selected row before transition self.selectedNoteindex = indexPath.row //transition using seque performSegue(withIdentifier: "showNotesegue", sender: nil) } @IBAction func newNote(){ //new note let newAdd = ["title" : "" , "body" : ""] //adding the note to the array at the top arrNotes.insert(newAdd, at: 0) //set the index value to the recently updated note self.selectedNoteindex = 0 //reload the table with the new note self.tableView.reloadData() //push to the the notes view by seque performSegue(withIdentifier: "showNotesegue", sender: nil) //save notes to device saveNoteArrayonDevice() } //allows to modify the target view controller before it appears on the screen override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. let editorViewcontroller = segue.destination as! NotesViewController // Pass the selected object to the new view controller. //select the title bar and change the title to currently selected note editorViewcontroller.navigationItem.title = arrNotes[self.selectedNoteindex]["title"] //set the body of the notes view controller to the selected notes index value editorViewcontroller.notesBodytext = arrNotes[self.selectedNoteindex]["body"] //set the delegate value to self editorViewcontroller.delegate = self } //protocol func didModifyNoteWithTitle(newTitle: String, andNoteBody newBody: String) { //update the selected values self.arrNotes[self.selectedNoteindex]["title"] = newTitle self.arrNotes[self.selectedNoteindex]["body"] = newBody //refresh the view self.tableView.reloadData() //save notes to device saveNoteArrayonDevice() } //to save the notes on the phone func saveNoteArrayonDevice() { //save the updated/modified note UserDefaults.standard.set(arrNotes, forKey:"notes") UserDefaults.standard.synchronize() } //deleting the notes override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) table.setEditing(editing, animated: animated) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { arrNotes.remove(at: indexPath.row) table.deleteRows(at: [indexPath], with: .middle) saveNoteArrayonDevice() } // MARK: - Target Button Tap // Tap on home button action @objc func backTap1(){ print("clicked1") self.navigationController?.dismiss(animated: true, completion: { self.view.removeFromSuperview() }) } }
true
5183d4f25ec476e4907260f53294afa4b4023418
Swift
equalriver/PearlVideo
/PearlVideo/Helper/Tools/YPJImageTools.swift
UTF-8
9,159
2.828125
3
[]
no_license
// // YPJImageTools.swift // PearlVideo // // Created by equalriver on 2019/5/17. // Copyright © 2019 equalriver. All rights reserved. // public struct YPJImageTools<T>: YPJToolable { public let ypj: T public init(target: T) { self.ypj = target } } extension UIImage: YPJToolable { public var ypj: YPJImageTools<UIImage> { return YPJImageTools.init(target: self) } } extension YPJImageTools where YPJToolType == UIImage { //MARK: - 图片转成Base64 ///图片转成Base64字符串 public var base64String: String { let data = ypj.jpegData(compressionQuality: 1.0) let str = data?.base64EncodedString() ?? "" // let str = data?.base64EncodedString(options: .lineLength64Characters) return "data:image/jpeg;base64," + str } //MARK: - 异步绘制圆角 ///异步绘制圆角 public func asyncDrawCornerRadius(roundedRect: CGRect, cornerRadius: CGFloat, fillColor: UIColor, callback: @escaping (_ img: UIImage?) -> Void) { DispatchQueue.global().async { // 1.利用绘图,建立上下文 - 内存中开辟一个地址,跟屏幕无关! /** 参数: 1> size: 绘图的尺寸 2> 不透明:false / true 3> scale:屏幕分辨率,生成的图片默认使用 1.0 的分辨率,图像质量不好;可以指定 0 ,会选择当前设备的屏幕分辨率 */ UIGraphicsBeginImageContextWithOptions(roundedRect.size, true, 0) // 2.设置被裁切的部分的填充颜色 fillColor.setFill() UIRectFill(roundedRect) // 3.利用 贝塞尔路径 实现 裁切 效果 // 1>实例化一个圆形的路径 let path = UIBezierPath.init(roundedRect: roundedRect, cornerRadius: cornerRadius) // 2>进行路径裁切 - 后续的绘图,都会出现在圆形路径内部,外部的全部干掉 path.addClip() // 4.绘图 drawInRect 就是在指定区域内拉伸屏幕 self.ypj.draw(in: roundedRect) /* // 5.绘制内切的圆形 let ovalPath = UIBezierPath.init(ovalIn: rect) ovalPath.lineWidth = 2 lineColor.setStroke() ovalPath.stroke() // UIColor.darkGray.setStroke() // path.lineWidth = 2 // path.stroke() */ // 6.取得结果 let result = UIGraphicsGetImageFromCurrentImageContext() // 7.关闭上下文 UIGraphicsEndImageContext() DispatchQueue.main.async { callback(result) } } } //MARK: - 绘制图片圆角 ///绘制图片圆角 func drawCorner(rect: CGRect, cornerRadius: CGFloat) -> UIImage { let bezierPath = UIBezierPath.init(roundedRect: rect, cornerRadius: cornerRadius) UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale) if let context = UIGraphicsGetCurrentContext() { context.addPath(bezierPath.cgPath) context.clip() self.ypj.draw(in: rect) context.drawPath(using: CGPathDrawingMode.fillStroke) if let img = UIGraphicsGetImageFromCurrentImageContext(){ UIGraphicsEndImageContext() return img } } return UIImage() } //MARK: - 裁剪图片 ///裁剪图片 func clipImage(newRect: CGRect) -> UIImage? { //将UIImage转换成CGImage let sourceImg = self.ypj.cgImage //按照给定的矩形区域进行剪裁 //cropping以图片px为单位 guard let newCgImg = sourceImg?.cropping(to: newRect) else { return nil } //将CGImageRef转换成UIImage let newImg = UIImage.init(cgImage: newCgImg) return newImg } //MARK: - 自适应裁剪 ///自适应裁剪 func clipImageToRect(newSize: CGSize) -> UIImage? { //被切图片宽比例比高比例小 或者相等,以图片宽进行放大 if self.ypj.size.width * newSize.height <= self.ypj.size.height * newSize.width { //以被剪裁图片的宽度为基准,得到剪切范围的大小 let w = self.ypj.size.width let h = self.ypj.size.width * newSize.height / newSize.width // 调用剪切方法 // 这里是以中心位置剪切,也可以通过改变rect的x、y值调整剪切位置 return self.clipImage(newRect: CGRect.init(x: 0, y: (self.ypj.size.height - h) / 2, width: w, height: h)) } else {//被切图片宽比例比高比例大,以图片高进行剪裁 // 以被剪切图片的高度为基准,得到剪切范围的大小 let w = self.ypj.size.height * newSize.width / newSize.height let h = self.ypj.size.height // 调用剪切方法 // 这里是以中心位置剪切,也可以通过改变rect的x、y值调整剪切位置 return self.clipImage(newRect: CGRect.init(x: (self.ypj.size.width - w) / 2, y: 0, width: w, height: h)) } } //MARK: - 压缩图片 ///压缩图片 /** * 压缩上传图片到指定字节 * * image 压缩的图片 * maxLength 压缩后最大字节大小 * * return 压缩后图片的二进制 */ func compressImage(maxLength: Int) -> Data? { var compress: CGFloat = 1.0 var data = self.ypj.jpegData(compressionQuality: compress) guard data != nil else { return nil } while (data?.count)! > maxLength && compress > 0.01 { compress -= 0.02 data = self.ypj.jpegData(compressionQuality: compress) } return data } //MARK: - 等比例的图片 /** * 通过指定图片最长边,获得等比例的图片size * * image 原始图片 * imageLength 图片允许的最长宽度(高度) * * return 获得等比例的size */ func scaleImage(imageLength: CGFloat) -> CGSize { var newWidth:CGFloat = 0.0 var newHeight:CGFloat = 0.0 let width = self.ypj.size.width let height = self.ypj.size.height if (width > imageLength || height > imageLength){ if (width > height) { newWidth = imageLength; newHeight = newWidth * height / width; }else if(height > width){ newHeight = imageLength; newWidth = newHeight * width / height; }else{ newWidth = imageLength; newHeight = imageLength; } } return CGSize(width: newWidth, height: newHeight) } //MARK: - 指定size的图片 /** * 获得指定size的图片 * * image 原始图片 * newSize 指定的size * * return 调整后的图片 */ func resizeImage(newSize: CGSize) -> UIImage? { UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.main.scale) self.ypj.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } //MARK: - 保存图片到本地 ///保存图片到本地 func saveImageToLocalFolder(directory: FileManager.SearchPathDirectory, compressionQuality: CGFloat) -> String? { guard let data = ypj.jpegData(compressionQuality: compressionQuality) else { print("图片转data失败") return nil } let p = NSSearchPathForDirectoriesInDomains(directory, .userDomainMask, true) guard let path = p.first else { return nil } let imgCacheFolderPath = path + "/imageCache/" let imgAbsolutePath = imgCacheFolderPath + ypj.description.ypj.MD5 + ".jpg" if FileManager.default.fileExists(atPath: imgAbsolutePath) == false { DispatchQueue.ypj_once(token: "createDirectory") { do { try FileManager.default.createDirectory(atPath: imgCacheFolderPath, withIntermediateDirectories: true, attributes: nil) }catch { print(error) } } do { try data.write(to: URL.init(fileURLWithPath: imgAbsolutePath)) return imgAbsolutePath } catch { print(error) return nil } } else { return imgAbsolutePath } } }
true
f106c1b3dc4bc44d8da5d26ab8460490c02b5cf6
Swift
pitt500/CrackingTheCodeInterview-Swift
/Cap 3 - Stacks and Queues/Three in One.swift
UTF-8
1,780
4.125
4
[]
no_license
//Three in One - Stack class ThreeInOneStack { var stack: [Int?] = [nil, nil] private var middleTopIndex = 1 private var middleBottomIndex = 1 enum StackError: Error { case invalidStack } func push(value: Int, atStack stackNumber: Int) throws -> Void { if stackNumber > 3 && stackNumber < 0 { throw StackError.invalidStack } switch stackNumber { case 1: stack.insert(value, at: 0) middleTopIndex += 1 middleBottomIndex += 1 case 2: stack.insert(value, at: middleTopIndex) middleBottomIndex += 1 case 3: stack.append(value) default: break } } func pop(fromStack stackNumber: Int) throws -> Int? { if stackNumber > 3 && stackNumber < 0 { throw StackError.invalidStack } switch stackNumber { case 1: if stack.first! == nil { return nil } middleTopIndex -= 1 middleBottomIndex -= 1 return stack.remove(at: 0)! case 2: if stack[middleTopIndex] == nil { return nil } let value = stack.remove(at: middleTopIndex)! middleBottomIndex -= 1 return value case 3: if stack.last! == nil { return nil } return stack.popLast()! default: return nil } } } //Output let stack = ThreeInOneStack() try stack.push(value: 1, atStack: 1) try stack.push(value: 2, atStack: 1) try stack.push(value: 5, atStack: 2) try stack.push(value: 3, atStack: 2) try stack.push(value: 4, atStack: 3) try stack.push(value: 7, atStack: 3) print(stack.stack) for i in 1...3 { for _ in 1...3 { if let value = try? stack.pop(fromStack: i) { print("Pop: \(value) at stack #\(i)") } else { print("Stack #\(i) is empty") } print(stack.stack) } }
true
f6f4ad8cc1a8c0ab0920938adb777d6721195b2e
Swift
pavaris/SBU_Campus_Tab_Final
/SBU_Campus_Tab/CatagoryTableVC.swift
UTF-8
3,237
2.9375
3
[]
no_license
// // CatagoryTableVC.swift // SBU_Campus_Tab // // Created by Rashedul Khan & Pavaris Ketavanan on 3/30/16. // Copyright © 2016 Stony Brook University. All rights reserved. // import UIKit class CatagoryTableVC: UITableViewController { var catagories = [String]() var selectedPath: Set<String> = [] override func viewDidLoad() { print ("\nView DID LOAD") super.viewDidLoad() for cat in catagories{print(cat)} } // MARK: - Navigation @IBAction func cancelButton(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func selectAllButton(sender: UIBarButtonItem) { for var i=0; i<catagories.count;i++ { let indexPath = NSIndexPath(forRow: i, inSection: 0) let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.accessoryType = UITableViewCellAccessoryType.Checkmark selectedPath.insert((cell?.textLabel?.text)!) } // done adding check marks } @IBAction func selectNoneButton(sender: UIBarButtonItem) { for var i=0; i<catagories.count;i++ { let indexPath = NSIndexPath(forRow: i, inSection: 0) let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.accessoryType = UITableViewCellAccessoryType.None } // done removing check marks selectedPath.removeAll() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { print ("Done") } // MARK: - TableView override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) // Flip accessory type if cell?.accessoryType == UITableViewCellAccessoryType.Checkmark { // UnSelected cell?.accessoryType = UITableViewCellAccessoryType.None selectedPath.remove((cell?.textLabel?.text)!) } else { // Selected cell?.accessoryType = UITableViewCellAccessoryType.Checkmark selectedPath.insert((cell?.textLabel?.text)!) } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return catagories.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { print ("\nGenerating NEW cell") let cellIdentifier = "CatagoeryCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) //selectedPath.insert(catagories[indexPath.row]) // Display Cell cell.textLabel?.text = catagories[indexPath.row] if (selectedPath.contains(catagories[indexPath.row])) { cell.accessoryType = UITableViewCellAccessoryType.Checkmark } else { cell.accessoryType = UITableViewCellAccessoryType.None } cell.layoutIfNeeded() // make sure the cell is properly rendered return cell } }
true
e69338ce9e65cd47822d3686d3960372f9b452ee
Swift
malhal/Kraftstoff
/Classes/NSDecimalNumber+Kraftstoff.swift
UTF-8
1,464
3.125
3
[ "Zlib" ]
permissive
// // NSDecimalNumber+Kraftstoff.swift // kraftstoff // // Created by Ingmar Stein on 30.04.15. // // import Foundation // MARK: - Comparable extension NSDecimalNumber: Comparable {} public func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool { return lhs.compare(rhs) == .OrderedSame } public func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool { return lhs.compare(rhs) == .OrderedAscending } // MARK: - Arithmetic Operators public prefix func -(value: NSDecimalNumber) -> NSDecimalNumber { return NSDecimalNumber.zero().decimalNumberBySubtracting(value) } public func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.decimalNumberByAdding(rhs) } public func -(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.decimalNumberBySubtracting(rhs) } public func *(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.decimalNumberByMultiplyingBy(rhs) } public func /(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.decimalNumberByDividingBy(rhs) } public func ^(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber { return lhs.decimalNumberByRaisingToPower(rhs) } public func <<(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber { return lhs.decimalNumberByMultiplyingByPowerOf10(Int16(rhs)) } public func >>(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber { return lhs.decimalNumberByMultiplyingByPowerOf10(Int16(-rhs)) }
true
c8ce627498f9aa29fb8e67e1fe879c4bacaedd72
Swift
ksandeepvvn/OpenApiDataFetching
/SimpleWeather/Details.swift
UTF-8
902
2.734375
3
[]
no_license
// // Details.swift // OpenDataApi // // Created by Sandeep on 18/12/16. // Copyright © 2016 Sandeep. All rights reserved. // import Foundation struct Details{ let title_Type: String var title_Location: String let description: String let latitude: Double let longitude: Double let content: String let external_Source_Link: String init(detailsData: [String: AnyObject]) { let detailDict = detailsData["data"]![0] as! [String: AnyObject] longitude = detailDict["lng"] as! Double latitude = detailDict["lat"] as! Double title_Type = detailDict["title_type"] as! String title_Location = detailDict["title_location"] as! String description = detailDict["description"] as! String content = detailDict["content"] as! String external_Source_Link = detailDict["external_source_link"] as! String } }
true
eb6a30392ca02593b04e437f70443173ade85275
Swift
ekuipers1/Black-Gold
/Black Gold/Data/WarmData.swift
UTF-8
4,132
3.09375
3
[ "MIT" ]
permissive
// // WarmData.swift // Black Gold // // Created by Erik Kuipers on 4/1/20. // Copyright © 2020 Erik Kuipers. All rights reserved. // import SwiftUI let DataWarmDrinks: [WarmDrinks] = [ WarmDrinks( title: "Espresso", headline: "A smooth Espresso Roast with rich flavor and caramelly sweetness is at the very heart of everything", image: "Coffee-1", rating: 5, calories: 5, caffeine: 150, gramsofprotein: 0, instructions: [ "The weight of the liquid espresso should be somewhere between one and three times the weight of the dry coffee.", "The most common brew ratio to start with is two times the dry coffee dose.", "This means that if you started with 18 grams of dry coffee, you would end with 36 grams of liquid espresso in your cup." ], ingredients: [ "Ground coffee beans", "Nearly boiling water", "A small Espresso cup too serve" ] ), WarmDrinks( title: "Cappuccino", headline: "Dark, rich espresso lies in wait under a smoothed and stretched layer of thick milk foam. An alchemy of barista artistry and craft.", image: "Coffee-2", rating: 5, calories: 120, caffeine: 150, gramsofprotein: 5, instructions: [ "Pull a double shot of espresso into a cappuccino cup.", "Foam the milk to double its original volume.", "Top the espresso with foamed milk right after foaming. When initially poured, cappuccinos are only espresso and foam, but the liquid milk quickly settles out of the foam to create the (roughly) equal parts foam, steamed milk, and espresso for which cappuccino is known." ], ingredients: [ "Milk foam", "Steamed Milk", "Espresso Coffee" ] ), WarmDrinks( title: "Caffe Americano", headline: "An Americano is two ingredients: espresso and hot water. ", image: "Coffee-3", rating: 4, calories: 15, caffeine: 225, gramsofprotein: 25, instructions: [ "Pull a double shot of espresso into a cappuccino cup.", "Pour about 3oz or so of hot water into the mug you plan to drink from.", "Pour the espresso shot into the mug." ], ingredients: [ "Espresso Coffee", "About 3oz of nearly boiling water" ] ), WarmDrinks( title: "Latte Macchiato", headline: "A dark, rich espresso balanced with steamed milk and a light layer of foam. A perfect milk-forward warm-up.", image: "Coffee-4", rating: 5, calories: 190, caffeine: 150, gramsofprotein: 13, instructions: [ "Prepare the espresso in a small cup or pour pitcher.", "Foam the milk in a steaming pitcher, and pour it into a decorative glass.", "Add the espresso to the glass" ], ingredients: [ "3 large avocados,", "1/3 cup plus 2 tsp whole milk (90 ml)" ] ), WarmDrinks( title: "Caffe Mocha", headline: "Chocolate and espresso meet for the ultimate indulgence. Rich espresso and house-made chocolate sauce rendezvous with creamy steamed milk under a blanket of fresh whipped cream.", image: "Coffee-6", rating: 4, calories: 360, caffeine: 175, gramsofprotein: 13, instructions: [ "Brew an espresso into a mug, cup or glass.", "Add two teaspoons of hot chocolate mix or cocoa powder and mix with the espresso.", "Foam and texture the required quantity of milk, ensuring we have a good quality foam.", "Add the milk to the cup containing the chocolate espresso and top with whipped cream.", "Dust with more cocoa powder before serving." ], ingredients: [ "Espresso", "Chocolate", "Steamed Mild", "Milk Foam", "Whipped Cream" ] ) ]
true
ff38306aa9a0954880a0f4cf13e36070bc82aa69
Swift
rohinideo1812/Swift-Algorithm-Function
/GenericInsertion/GenericInsertionSort/main.swift
UTF-8
450
2.71875
3
[]
no_license
/****************************************************************************** * Purpose:Program for Generic Insertion Sort * * @author Rohini * @version 4.0 * @since 15-03-2018 * ******************************************************************************/ import Foundation var utility:Utility=Utility() print("Enter your choice \n1-Integer \n2-String") var choice = utility.acceptinputint() utility.acceptelements(choice: choice)
true
b38e2c7c2430aace4aa9cd1818e211958457b48a
Swift
CyuanChen/DevChat
/DevChat/Controller/LoginViewController.swift
UTF-8
2,503
2.625
3
[]
no_license
// // LoginViewController.swift // // // Created by PeterChen on 2017/10/16. // import UIKit class LoginViewController: UIViewController { @IBOutlet weak var emailTextField: InsetTextField! @IBOutlet weak var passwordTextField: InsetTextField! override func viewDidLoad() { super.viewDidLoad() emailTextField.delegate = self passwordTextField.delegate = self // Do any additional setup after loading the view. } @IBAction func signInBtnWasPressed(_ sender: Any) { if emailTextField.text != nil && passwordTextField.text != nil { AuthService.instance.loginUser(withEmail: emailTextField.text!, andPassword: passwordTextField.text!, loginComplete: { (success, loginError) in if success { self.dismiss(animated: true, completion: nil) } else { if (self.passwordTextField.text?.count)! < 6 { let pwdWarning = UIAlertController(title: "Error", message: String(describing:(loginError?.localizedDescription)!), preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil) pwdWarning.addAction(okAction) self.present(pwdWarning, animated: true, completion: nil) self.passwordTextField.text?.removeAll() } print(String(describing: loginError?.localizedDescription)) } AuthService.instance.registerUser(withEmail: self.emailTextField.text!, andPassword: self.passwordTextField.text!, userCreationComplete: { (success, registrationError) in if success { AuthService.instance.loginUser(withEmail: self.emailTextField.text!, andPassword: self.passwordTextField.text!, loginComplete: { (success, nil) in self.dismiss(animated: true, completion: nil) print("Successfully registered user") }) } else { print(String(describing: registrationError?.localizedDescription)) } }) }) } } @IBAction func CloseBtnWasPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } } extension LoginViewController: UITextFieldDelegate {}
true
388d6a37ff7ec5d5f3940c52135fb956e5882feb
Swift
dabing1022/HappySwiftUI
/HappySwiftUI/Tutorials/ProgressViewPage.swift
UTF-8
1,346
3
3
[]
no_license
// // ProgressViewPage.swift // HappySwiftUI // // Created by ChildhoodAndy on 2020/10/3. // Copyright © 2020 HappyCoding. All rights reserved. // import SwiftUI struct ProgressViewPage: View { @State private var progress = 0.2 var body: some View { VStack { ProgressView("Happy Loading...") .padding(.bottom, 20) .border(Color.green.opacity(0.2), width: 1.0) VStack { ProgressView(value: progress, total: 2.0) .padding(.all, 20) HStack { Text("0.00") Spacer() Text(String(format: "%.2f", progress)) Spacer() Text("2.00") } .padding(.horizontal, 20) Button("Load More", action: { progress += 0.05 if progress >= 2.0 { progress = 2.0 } }) .padding() } .border(Color.green.opacity(0.2), width: 1.0) } .navigationBarTitle(Text(verbatim: "ProgressView"), displayMode: .inline) } } struct ProgressViewPage_Previews: PreviewProvider { static var previews: some View { ProgressViewPage() } }
true
454f693aab328aa7498f564153b9e537b769a9bd
Swift
omarsamir/MindvalleyChallenge
/MindvalleyChallenge/MindvalleyChallenge/View/ResourceViewController.swift
UTF-8
3,004
2.71875
3
[]
no_license
// // ResourceViewController.swift // MindvalleyChallenge // // Created by Omar Samir on 9/15/18. // Copyright © 2018 Omar Samir. All rights reserved. // import UIKit class ResourceViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,ResourceControllerDelegate { @IBOutlet weak var resourcesTableView: UITableView! var resources : [Resource]! var resourceController : ResourceController! var refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() resourceController = ResourceController() resourceController.delegate = self resourcesTableView.delegate = self resourcesTableView.dataSource = self resourcesTableView.register(UINib(nibName: String(describing: ResourceTableViewCell.self), bundle: nil), forCellReuseIdentifier: "ResourceTableViewCellId") resources = [Resource]() refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged) resourcesTableView.addSubview(refreshControl) // not required when using UITableViewController // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { resourceController.getResources() } @objc func refresh() { resourceController.getResources() } // #MARK: Resource table view delegate methods implementation func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : ResourceTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ResourceTableViewCellId", for: indexPath) as! ResourceTableViewCell let resource = resources[indexPath.row] cell.set(resource: resource) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.resources.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 620.0 } // #MARK: Resource controller delegate methods implementation func display(resources: [Resource]) { self.resources = resources refreshControl.endRefreshing() resourcesTableView.reloadData() } func display(error: Error) { let alert = UIAlertController(title: "Error Alert", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: false, completion: nil) })) self.present(alert, animated: true, completion: nil) } }
true
f3cc1c82f08926b2a6869376d3e3b563552ed527
Swift
dunguyenn/nosedive-app-release
/PlayGroundTests/Circle-Animation.playground/Contents.swift
UTF-8
6,094
3.390625
3
[]
no_license
//: A UIKit based Playground for presenting user interface import UIKit import PlaygroundSupport class CircleView: UIView { var path = UIBezierPath() override func draw(_ rect: CGRect) { // x^2 + y^2 = r^2 //cos(theta) = x / r ==> x = r * cos(theta) //sin(theta) = y / r ==> y = r * sin(theta) let radius = 100.0 let center = CGPoint(x: rect.width / 2, y: rect.height / 2) path.move(to: CGPoint(x: Double(center.x) + radius, y: Double(center.y) )) for i in stride(from: 0, to: 380.0, by: 1){ let theta = i * Double.pi / 180 let x = Double(center.x) + radius * cos(theta) let y = Double(center.y) + radius * sin(theta) path.addLine(to: CGPoint(x: x, y: y)) } //path.addLine(to: CGPoint(x: 100, y: 100)) //Color UIColor.green.setFill() path.fill() //Stroke Color UIColor.red.setStroke() path.lineWidth = 5 path.stroke() print("BIG CIRCLEEEEE \n \n", path.cgPath) path.close() } func changeStrokeColor() { UIColor.blue.setStroke() path.stroke() } } class MyViewController : UIViewController { override func loadView() { let view = UIView() view.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1) self.view = view let circle = CircleView() let circleWithPath = self.createCircle(rect: CGRect(x: 200, y: 500, width: 100, height: 100)) //let circleWithPathEnd = self.createCircle(rect: CGRect(x: 100, y: 300, width: 300 , height: 300)) let circleWithPathEnd = UIBezierPath(arcCenter: view.center, radius: 200, startAngle: 0, endAngle: .pi*2, clockwise: true) //Create Layer let circleShapeLayer = CAShapeLayer() circleShapeLayer.path = circleWithPath.cgPath circleShapeLayer.fillColor = UIColor.clear.cgColor circleShapeLayer.strokeColor = UIColor.blue.cgColor view.layer.addSublayer(circleShapeLayer) let circleShapeLayer2 = CAShapeLayer() circleShapeLayer2.path = circleWithPathEnd.cgPath circleShapeLayer2.fillColor = UIColor.green.cgColor circleShapeLayer2.strokeColor = UIColor.red.cgColor circleShapeLayer2.backgroundColor = UIColor.clear.cgColor view.layer.addSublayer(circleShapeLayer2) let aniFrame = CABasicAnimation(keyPath: "path") aniFrame.duration = 1 aniFrame.fromValue = circleWithPath.cgPath aniFrame.toValue = circleWithPathEnd.cgPath aniFrame.repeatCount = MAXFLOAT circleShapeLayer2.add(aniFrame, forKey: aniFrame.keyPath) //let circlePath = UIBezierPath(arcCenter: view.center, radius: 20, startAngle: 0, endAngle: .pi*2, clockwise: true) let circlePath = UIBezierPath(arcCenter: view.center, radius: 20, startAngle: 0, endAngle: .pi*2, clockwise: true) let rect = CGRect(x: 100, y: 100, width: 100, height: 100) let curve = UIBezierPath(roundedRect: rect, cornerRadius: 10) //let poin1 = CGPoint(x: 0, y: 100) // let poin2 = CGPoint(x: 50, y: 300) // let poin3 = CGPoint(x: 100, y: 100) // curve.addCurve(to: poin1, controlPoint1: poin2, controlPoint2: poin3) // let layer = CAShapeLayer() layer.path = curve.cgPath layer.strokeColor = UIColor.blue.cgColor view.layer.addSublayer(layer) let animationFrame = CAKeyframeAnimation(keyPath: "position") animationFrame.duration = 1 animationFrame.repeatCount = MAXFLOAT //animationFrame.path = circlePath.cgPath //animationFrame.path = curve.cgPath animationFrame.path = circleWithPath.cgPath let squareView = UIView() //whatever the value of origin for squareView will not affect the animation squareView.frame = CGRect(x: 0, y: 0, width: 50, height: 50) squareView.backgroundColor = .lightGray view.addSubview(squareView) // You can also pass any unique string value for key squareView.layer.add(animationFrame, forKey: nil) // circleLayer is only used to locate the circle animation path let circleLayer = CAShapeLayer() circleLayer.path = circlePath.cgPath //print("ANOTHERRRR \n", circlePath.cgPath) circleLayer.strokeColor = UIColor.black.cgColor circleLayer.fillColor = UIColor.clear.cgColor view.layer.addSublayer(circleLayer) } func createCircle(rect: CGRect) -> UIBezierPath { let path = UIBezierPath() // x^2 + y^2 = r^2 //cos(theta) = x / r ==> x = r * cos(theta) //sin(theta) = y / r ==> y = r * sin(theta) let radius = 100.0 let center = CGPoint(x: rect.origin.x, y: rect.origin.y ) path.move(to: CGPoint(x: Double(center.x) + radius, y: Double(center.y) )) for i in stride(from: 0, to: 380.0, by: 1){ let theta = i * Double.pi / 180 let x = Double(center.x) + radius * cos(theta) let y = Double(center.y) + radius * sin(theta) path.addLine(to: CGPoint(x: x, y: y)) } //path.addLine(to: CGPoint(x: 100, y: 100)) //Color UIColor.green.setFill() path.fill() //Stroke Color UIColor.red.setStroke() path.lineWidth = 5 path.stroke() // path.close() return path } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = MyViewController()
true
3bc979c714258f2f591c37bd90d546b31f7597fb
Swift
avito-tech/Emcee
/Sources/CommonTestModels/TestRunResult.swift
UTF-8
1,477
2.609375
3
[ "MIT" ]
permissive
import EmceeTypes import Foundation /// A result of a single test run. public struct TestRunResult: Codable, CustomStringConvertible, Hashable { public let succeeded: Bool public let exceptions: [TestException] public let logs: [TestLogEntry] public let duration: TimeInterval public let startTime: DateSince1970ReferenceDate public let hostName: String public let udid: UDID public var finishTime: DateSince1970ReferenceDate { return startTime.addingTimeInterval(duration) } public init( succeeded: Bool, exceptions: [TestException], logs: [TestLogEntry], duration: TimeInterval, startTime: DateSince1970ReferenceDate, hostName: String, udid: UDID ) { self.succeeded = succeeded self.exceptions = exceptions self.logs = logs self.duration = duration self.startTime = startTime self.hostName = hostName self.udid = udid } public var description: String { var result: [String] = ["\(type(of: self)) \(succeeded ? "succeeded" : "failed")"] result += ["duration \(String(format: "%.3f", duration)) sec"] result += ["\(udid)"] if !exceptions.isEmpty { result += ["\(exceptions.count) exceptions"] } if !logs.isEmpty { result += ["\(logs.count) log entries"] } return "<\(result.joined(separator: ", "))>" } }
true
1918bab8e45ebadf2f1eab15ed4406139e05ce8b
Swift
Wlfade/NewPracticeForSwift
/1.基础知识/2.循环和条件判断/MyPlayground.playground/Contents.swift
UTF-8
3,251
4.75
5
[ "Apache-2.0" ]
permissive
import UIKit var str = "Hello, playground" /* for循环 */ for index in 0..<3 { print("index is \(index)") } //for-in 语句中, ..< 符号表示数值返回在 0~3之间,但是不包含数字3 for index1 in 0...3 { print("index is \(index1)") } //数组遍历 let students = ["Jerry","Thomas","John"] for student in students { print("student name:\(student)") } //字典类型数组的遍历 // 通过for-in 循环语句可以遍历一个字典的键值对(key-value pairs).在遍历字典时,字典的每一项元素会以(key,value)元组的形式返回 let scores = ["Jerry":78,"Thomas":88,"John":92] for (student,score) in scores { print(student+"'score is \(score)") // print(student+"是名字"+"分数是\(score)") } //因为字典的内容在内部是无序的,所以遍历元素时不能保证与其插入的顺序一致,字典元素的遍历顺序和插入顺序可能不同 /* while循环 */ var index = 0 while index < 3 { index += 1 print("try connect server again") } /* repeat-while循环 相当于 do-while */ var index1 = 0 repeat { index1 += 1 print("try connect server again") } while index1 < 3 //由于repeat-while 语句是先执行代码块再进行条件的判断,因此代码段总是会被执行至少一次。 var index2 = 0 repeat { index2 += 1 print("try connect server again 2") } while index2 < 0 let IDCard = "330382133210142248" let count = IDCard.lengthOfBytes(using: String.Encoding.utf8) //if(count != 18 && count != 15) if count != 18 && count != 15 { print("错误的身份证号码") } //在 Objective-C 环境中使用if 语句时,如果代码段只有一行,可以不使用大括号“{}”但是在 swift 中,为了提高代码的规范性,大括号是强制使用的 let IDCard2 = "330382133210142248" let count2 = IDCard.lengthOfBytes(using: String.Encoding.utf8) //if(count != 18 && count != 15) if count2 == 18 { print("正确的身份证号码") } else if count2 == 15 { print("正确的身份证号码") } else { print("错误的身份证号码") } /* switch 条件判断语句 */ let time = 12 switch time { case 7: print("It's time to get up") case 8,12,18: print("It's time to eating") case let x where x>18 && x <= 24: print("Happy Time") case 1...6: print("It's time for rest") default: print("keep busy") } /* continue 语句和fallthrough 语句 */ //continuej语句用来告诉用户一个循环体停止本次循环,并立即进入下次循环 let studentGender = ["男","女","男","女","男","男","女"] var boysAmount = 0 var studentAmount = 0 for gender in studentGender { studentAmount += 1 if (gender == "女") { continue }else{ boysAmount += 1 } } print("学生数量\(studentAmount)") print("男生数量 \(boysAmount)") let time1 = 6 var message = "It's now" switch time1 { case 2,3,6,7,9,10,16: message += "\(time1)o'clock" fallthrough case 4,5,8: message += "hehe\(time1)o'clock" fallthrough default: message += "." } print("message :\(message)") //由于使用了 fallthrough 语句,因此当执行完第一个case 分支后,会跳转到 第二个分支 再跳到 default,从而message变量添加句号
true
e28b6e5223dd0c28d06bfd09afd498c29d29f819
Swift
MykolaDenysyuk/SectionsMVPC
/SectionsMVPC/Screens/Home/Presenter/HomePresenter+Helpers.swift
UTF-8
697
2.609375
3
[]
no_license
// // HomePresenter+Helpers.swift // SectionsMVPC // // Created by Mykola Denysyuk on 3/28/18. // Copyright © 2018 Mykola Denysyuk. All rights reserved. // import UIKit extension HomePresenter { /// Simple items container struct Section { let items: [Home.Item] } /// Creates display items for Presenter class ContentFactory { func create() -> [Section] { return [Section(items: [Home.Item(icon: UIImage(named: "bread"), title: "Lorem"), Home.Item(icon: UIImage(named: "donut"), title: "Ipsum"), Home.Item(icon: UIImage(named: "loaf"), title: "Dolor")])] } } }
true
1d7461e8cb67ee68d56aaf7c285b0207f9db211f
Swift
vvi2/cornell_connect_iOS
/HackChallenge_/Attraction.swift
UTF-8
510
2.578125
3
[]
no_license
// // Attraction.swift // HackChallenge_ // // Created by Varsha Iyer on 5/10/21. // import Foundation struct Attraction: Codable{ var id: Int var name: String var address: String var category: String var image: String var posts: [Post] } struct Post: Codable{ var id: Int var name: String var picture: String var description: String // var comments: [Comment] } struct Comment: Codable{ var id: Int var name: String var description: String }
true
a564a4c33197608abc75230788e0e9a6f81238fd
Swift
margaritachernyaeva/CurrencyExchangeApp
/CurrencyForFutureMVVM/Model/Currency.swift
UTF-8
493
2.75
3
[]
no_license
// // nationalCurrency.swift // CurrencyForFutureMVC // // Created by Маргарита Черняева on 11/5/20. // import Foundation struct Currency : Codable { let date : String? let cur_Abbreviation : String? let cur_OfficialRate : Double? let cur_Symbol: String? enum CodingKeys: String, CodingKey { case cur_OfficialRate = "Cur_OfficialRate" case date = "Date" case cur_Abbreviation = "Cur_Abbreviation" case cur_Symbol = "Cur_Symbol" } }
true
bc7dee701abb098f1d0c51c9cc17f13813849f7c
Swift
Dixonlamond/FizzBuzz-2.playground
/Contents.swift
UTF-8
741
4.3125
4
[]
no_license
//: Playground - noun: a place where people can play // FizzBuzz import UIKit // This is giving the program numbers between 1 - 100 for number in 1...100 { if (number % 3 == 0) && (number % 5 == 0){ // This is checking if the number is equal to 0 in either 3 or 5 it will print "FizzBuzz" print("FizzBuzz") }else if (number % 3 == 0){ // This will print to the console "Fizz if either number is equal to 0 when divided by 3 print("Fizz") }else if (number % 5 == 0){ // Will print "Buzz" when numbers between 1 - 100 equal 0 when divided by 5 print("Buzz") }else { print(number) // if any of the numbers can't be divded by 3 or 5 it will just print this numbers to the console. } }
true
16b3db20407dba58115df95a3d6d081004ad25d9
Swift
Anonym0uz/Currency-Converter
/CurrencyConverter/Main/Model/Currency.swift
UTF-8
1,056
2.6875
3
[]
no_license
// // Currency.swift // CurrencyConverter // // Created by sot on 16.02.2021. // import Foundation struct CurrencyModel: Codable { var id: String? var numCode: String? var charCode: String? var nominal: Int? var name: String? var value: Double? var previous: Double? enum CodingKeys: String, CodingKey { case id = "ID" case numCode = "NumCode" case charCode = "CharCode" case nominal = "Nominal" case name = "Name" case value = "Value" case previous = "Previous" } } //{ // "Date\": \"2021-02-17T11:30:00+03:00\", // \"PreviousDate\": \"2021-02-16T11:30:00+03:00\", // \"PreviousURL\": \"\\/\\/www.cbr-xml-daily.ru\\/archive\\/2021\\/02\\/16\\/daily_json.js\", // \"Timestamp\": \"2021-02-16T18:00:00+03:00\", // \"Valute\": // "AUD" : { // \"ID\": \"R01010\", // \"NumCode\": \"036\", // \"CharCode\": \"AUD\", // \"Nominal\": 1, // \"Name\": \"Австралийский доллар\", // \"Value\": 57.0559, // \"Previous\": 57.0639 // } //}
true
adb436ca2a56e9c3596027aedb755edba2ec5767
Swift
dachangjin/Data-Structure-and-Algorithm
/Algorithm/getOffers/28_isSymmetric/28_isSymmetric/main.swift
UTF-8
826
3.328125
3
[]
no_license
// // main.swift // 28_isSymmetric // // Created by tommywwang on 2021/6/8. // import Foundation public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } class Solution { func isSymmetric(_ root: TreeNode?) -> Bool { if root == nil { return true } return same(n1: root!.left, n2: root!.right) } func same(n1: TreeNode?, n2: TreeNode?) -> Bool { if n1 == nil && n2 == nil { return true } if n1 == nil || n2 == nil || n1!.val != n2!.val { return false } return same(n1: n1!.left, n2: n2!.right) && same(n1: n1!.right, n2: n2!.left) } }
true
a06b8b6e4a74f38c48943d4c8340f2751f43ce04
Swift
mike-normal13/Drum-Machine
/DecayContainerView.swift
UTF-8
811
2.625
3
[]
no_license
// // DecayContainerView.swift // FInalProject // // Created by Budge on 5/1/15. // Copyright (c) 2015 Budge. All rights reserved. // import UIKit // holds the controls that decide how a sound terminates // instance of this class is owned by the SlotConfigView class DecayContainerView: UIView { private var _decayView: DecayView! = nil; // accessors var decayView: DecayView { get { return _decayView } set {_decayView = newValue } } override func layoutSubviews() { var rect = bounds; layer.borderWidth = 1; layer.borderColor = UIColor.whiteColor().CGColor; layer.cornerRadius = 5; clipsToBounds = true; _decayView = DecayView(frame: bounds) addSubview(_decayView); } }
true
552443931e63cac8c0334e352b8ed6a8e94a7621
Swift
wdesimini/SanDiegoZooSample
/SanDiegoZooSample/Controllers/HomeViewController.swift
UTF-8
2,113
2.65625
3
[]
no_license
// // HomeViewController.swift // SanDiegoZooSample // // Created by Wilson Desimini on 3/12/19. // Copyright © 2019 Wilson Desimini. All rights reserved. // import UIKit class HomeViewController: UIViewController { @IBOutlet weak var experiencesView: UIView! @IBOutlet weak var connectView: UIView! @IBOutlet weak var ticketsView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let views = [experiencesView, connectView, ticketsView] views.forEach { $0?.layer.cornerRadius = 12 $0?.clipsToBounds = true } } override func viewWillAppear(_ animated: Bool) { navigationItem.title = "San Diego Zoo" } @IBAction func ticketsButtonTapped(_ sender: Any) { openInBrowser("https://zoo.sandiegozoo.org/tickets") } @IBAction func facebookTapped(_ sender: Any) { openApp("facebook://profile/28896772146", "https://www.facebook.com/SanDiegoZoo") } @IBAction func instagramTapped(_ sender: Any) { openApp("instagram://profile/1259368", "https://www.instagram.com/sandiegozoo/") } @IBAction func twitterTapped(_ sender: Any) { openApp("twitter://profile/15526913", "https://twitter.com/sandiegozoo/") } @IBAction func youtubeTapped(_ sender: Any) { openApp("youtube://www.youtube.com/user/SDZoo", "https://www.youtube.com/user/SDZoo") } func openApp(_ AppUrl: String,_ WebUrl: String) { UIApplication.tryURL([AppUrl, WebUrl]) } } // Open applications/safari for social media links extension UIApplication { class func tryURL(_ urlStrings: [String]) { let application = UIApplication.shared let urls = urlStrings.map { URL(string: $0) } urls.forEach { if application.canOpenURL($0!) { application.open($0!, options: [:], completionHandler: nil) return } } } }
true
c10db36a99117a1f5aa51baa25b6b7c946b74c63
Swift
ALlauradoM/iOS_ExampleApp
/LSRentals/LSRentals/DetailsController.swift
UTF-8
2,547
2.703125
3
[]
no_license
// // DetailsController.swift // LSRentals // import UIKit import MapKit class DetailsController: UIViewController { var apartment:Dictionary<String, Any>? = nil @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var capacityLabel: UILabel! @IBOutlet weak var infoText: UITextView! @IBOutlet weak var img: UIImageView! @IBOutlet weak var map: MKMapView! let regionRadius: CLLocationDistance = 1000 func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius) map.setRegion(coordinateRegion, animated: true) } override func viewDidLoad() { self.navigationController?.isNavigationBarHidden = false nameLabel.text = apartment?["name"] as? String let l = apartment?["location"] as? Dictionary<String, Any> addressLabel.text = l?["address"] as? String let c = apartment?["maximum_capacity"] as! Int capacityLabel.text = "\(c)" infoText.text = apartment?["information"] as? String let images = apartment?["images"] as! Dictionary<String, Any> //print("\n---------------------\n", images["main"]) let imageUrlString = images["main"] as! String let imageUrl:URL = URL(string: imageUrlString)! let imageData:NSData = NSData(contentsOf: imageUrl)! img.image = UIImage(data: imageData as Data) let loc = CLLocation(latitude: l!["latitud"] as! CLLocationDegrees, longitude: l!["longitud"] as! CLLocationDegrees) centerMapOnLocation(location: loc) let annotation = MKPointAnnotation() annotation.coordinate = CLLocationCoordinate2D(latitude: l!["latitud"] as! CLLocationDegrees, longitude: l!["longitud"] as! CLLocationDegrees) map.addAnnotation(annotation) self.map.isZoomEnabled = false; self.map.isScrollEnabled = false; self.map.isUserInteractionEnabled = false; } @IBAction func bookBtnAction(_ sender: Any) { self.performSegue(withIdentifier: "segueBook", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueBook" { let controller = segue.destination as! BookController controller.apartment = apartment } } }
true
e89b6478c68a8dbfba5ae0036b98498dcb46798c
Swift
anisjonischkeit/Friends
/Friends/Controllers/MasterViewController.swift
UTF-8
5,929
2.78125
3
[]
no_license
// // DetailViewController.swift // Friends // // Created by Anis on 24/05/2016. // Copyright © 2016 Anis. All rights reserved. // import UIKit // location of the persistance plist file let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString let fileName = documentsDirectory.stringByAppendingPathComponent("friends.plist") class MasterViewController: UITableViewController { var friendList = FriendList() var friend : Friend! var firstLoad : Bool = true override func viewWillAppear(animated: Bool) { for (i, element) in friendList.entries.enumerate() { //loops through all contacts with i as the index and element as the array item if(element.fullName().stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) == "") && (element.photoData == nil || element.photoUrl == "") {// checks if first or last name have been entered or if a photo has been added friendList.entries.removeAtIndex(i) //if not, the item is removed (used to remove invalid contacts) } } //makes sure it only gets triggered when the app is loading not when coming back to the master view from the detail view if firstLoad == true { firstLoad = false //checks if there is a photo.plist file in the app's document directory and if so it loads in the NSDictionary from the files into the PhotoList array using the PhotoExtension if (NSFileManager.defaultManager().fileExistsAtPath(fileName)) { let fileContent = NSArray(contentsOfFile: fileName) as! Array<NSDictionary> friendList.entries = fileContent.map { Friend(propertyList: $0) } } //Loads images for Photos added from the .PLIST for currentFriend in friendList.entries { currentFriend.photoData = loadImage(currentFriend.photoUrl) } } self.tableView.reloadData() saveToFile() } override func viewDidLoad() { super.viewDidLoad() //adds add and edit button let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton self.navigationItem.leftBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // inserts a new blank Friend into the friendlist array and segues to the detail view func insertNewObject(sender: AnyObject) { friend = Friend(firstName: "", lastName: "", address: "", flikr: "", website: "", photoUrl: "") friendList.entries.append(friend) performSegueWithIdentifier("showDetail", sender: self) } // loads images before the app runs func loadImage(urlName : String) -> NSData? { var imgData: NSData? = nil if let url = NSURL(string: urlName) { if let data = NSData(contentsOfURL: url), let _ = UIImage(data: data) { imgData = data } } return imgData } // saves friendlist array to a plist file func saveToFile() { let propertyList: NSArray = friendList.entries.map{ $0.propertyListRepresentation() } propertyList.writeToFile(fileName, atomically: true) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return the number of rows return friendList.entries.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) // Configure the cell let object:Friend = friendList.entries[indexPath.row] cell.textLabel!.text = "\(object.fullName())" if object.photoData != nil, let image = UIImage(data: object.photoData!){ cell.imageView?.image = image } else { cell.imageView?.image = nil } return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source friendList.entries.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) saveToFile() } } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Pass the selected object to the new view controller. if segue.identifier == "showDetail" { if let dvc = segue.destinationViewController as? DetailViewController { if let indexPath = self.tableView.indexPathForSelectedRow { friend = friendList.entries[indexPath.row]// as ContactListEntry //selects the selected contact } dvc.friend = friend } } } }
true
f9884371a50db2f0cefae683915ef717ee13eaae
Swift
RusChr/extensions-kit
/Sources/ExtendedUIKit/UICollectionView/UICollectionView+ScrollingUtils.swift
UTF-8
1,656
3.125
3
[ "MIT" ]
permissive
// // UICollectionView+ScrollingUtils.swift // extensions-kit // // Created by Astemir Eleev on 03/10/2018. // Copyright © 2018 Astemir Eleev. All rights reserved. // import UIKit extension UICollectionView { /// Scrolls to the bottom of the UICollectionView /// /// - Parameters: /// - animated: is a boolean parameter indicating whether the scrolling should be performed with animation public func scrollToBottom(animated: Bool = true) { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height) setContentOffset(bottomOffset, animated: animated) } /// Scrolls to the top of the UICollectionView /// /// - Parameters: /// - animated: is a boolean parameter indicating wherher the scrolling should be performed with animation public func scrollToTop(animated: Bool = true) { setContentOffset(.zero, animated: animated) } /// Wrapper that safely scrolls to the speficied index path /// /// - Parameters: /// - indexPath: is an IndexPath type that specifies the target scrolling position /// - scrollPosition: is the target scroll position of the specified index path /// - animated: is a boolean value indicating whether the scrolling should be animated or not public func safeScrollingToCell(at indexPath: IndexPath, at scrollPosition: UICollectionView.ScrollPosition, animated: Bool = true) { guard indexPath.section < numberOfSections, indexPath.row < numberOfItems(inSection: indexPath.section) else { return } scrollToItem(at: indexPath, at: scrollPosition, animated: animated) } }
true
4ec3b467f666050a7cea4f8c530fdd6640a23943
Swift
magic-IOS/leetcode-swift
/1818. Minimum Absolute Sum Difference.swift
UTF-8
3,278
3.09375
3
[ "Apache-2.0" ]
permissive
class Solution { // 1818. Minimum Absolute Sum Difference // You are given two positive integer arrays nums1 and nums2, both of length n. // The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). // You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. // Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 10^9 + 7. // |x| is defined as: // x if x >= 0, or // -x if x < 0. // Example 1: // Input: nums1 = [1,7,5], nums2 = [2,3,5] // Output: 3 // Explanation: There are two possible optimal solutions: // - Replace the second element with the first: [1,7,5] => [1,1,5], or // - Replace the second element with the third: [1,7,5] => [1,5,5]. // Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3. // Example 2: // Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10] // Output: 0 // Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an // absolute sum difference of 0. // Example 3: // Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4] // Output: 20 // Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7]. // This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20 // Constraints: // n == nums1.length // n == nums2.length // 1 <= n <= 10^5 // 1 <= nums1[i], nums2[i] <= 10^5 private let mod = 1_000_000_007 func minAbsoluteSumDiff(_ nums1: [Int], _ nums2: [Int]) -> Int { let n = nums1.count var noChange = 0 for i in 0..<n { noChange += abs(nums1[i] - nums2[i]) } var ans = noChange let sortedNums1 = nums1.sorted() func searchPosition(for val: Int) -> Int { guard val > sortedNums1[0] else { return -1 } guard val < sortedNums1[n - 1] else { return n } var left = 0 var right = n - 1 while left < right { let mid = left + (right - left) >> 1 if sortedNums1[mid] == val { return mid } else if sortedNums1[mid] < val { guard sortedNums1[mid + 1] <= val else { return mid } left = mid + 1 } else { guard sortedNums1[mid - 1] > val else { return mid - 1 } right = mid - 1 } } return sortedNums1[left] <= val ? left : (left - 1) } for idx in 0..<n { var temp = noChange temp -= abs(nums2[idx] - nums1[idx]) let idx1 = searchPosition(for: nums2[idx]) if idx1 == -1 { temp += abs(sortedNums1[0] - nums2[idx]) } else if idx1 == n { temp += abs(sortedNums1[n - 1] - nums2[idx]) } else { temp += min(abs(sortedNums1[idx1] - nums2[idx]), abs(sortedNums1[idx1 + 1] - nums2[idx])) } ans = min(ans, temp) } return ans % mod } }
true
4869ffa050866d3b7400e2133057dd2a7a16722a
Swift
ReactComponentKit/EmojiCollection
/EmojiCollectionApp/EmojiCollectionApp/Model/EmojiSectionHeaderModel.swift
UTF-8
691
2.765625
3
[ "MIT" ]
permissive
// // EmojiSectionHeaderModel.swift // EmojiCollectionApp // // Created by burt on 2018. 8. 26.. // Copyright © 2018년 Burt.K. All rights reserved. // import ReactComponentKit struct EmojiSectionHeaderModel: ItemModel, Hashable { var id: Int { return self.hashValue } func hash(into hasher: inout Hasher) { hasher.combine(title) } var componentClass: UIViewComponent.Type { return EmojiSectionHeaderComponent.self } var contentSize: CGSize { return CGSize(width: UIScreen.main.bounds.width, height: 36) } let title: String init(title: String) { self.title = title } }
true
1b0109de267650875f2ecdfe6f6e6d19618a499d
Swift
grigorye/RSSReader
/RSSReader/RSSReader/Swift/ItemInListView.swift
UTF-8
890
2.859375
3
[]
no_license
// // ItemInListView.swift // RSSReader // // Created by Grigory Entin on 27/09/2016. // Copyright © 2016 Grigory Entin. All rights reserved. // import RSSReaderData import Foundation extension Item { class func keyPathsForValuesAffectingItemListSectionName() -> Set<String> { return [#keyPath(date)] } func itemsListSectionName() -> String { let timeInterval = date.timeIntervalSince(date) if timeInterval < 24 * 3600 { return "" } else if timeInterval < 7 * 24 * 3600 { return "Last Week" } else if timeInterval < 30 * 7 * 24 * 3600 { return "Last Month" } else if timeInterval < 365 * 7 * 24 * 3600 { return "Last Year" } else { return "More than Year Ago" } } func itemListFormattedDate(forNowDate nowDate: Date) -> String { let timeInterval = nowDate.timeIntervalSince(self.date) return dateComponentsFormatter.string(from: timeInterval)! } }
true
b2128e8586a851c62a253d2e94d8483a2aa8a3ae
Swift
bc125/SwiftNetworking
/GetAddressDataFromBing.playground/section-1.swift
UTF-8
1,965
3.375
3
[]
no_license
// Playground - noun: a place where people can play import Foundation var running = false // had this been a class these will be instance vars instead of globals var config = NSURLSessionConfiguration.defaultSessionConfiguration() var session = NSURLSession(configuration: config) let bingkey="GET_A_MAP_KEY_FROM_BING_and_PUT_IT_HERE" var address="540%20Evelyn%20Place%20Beverly%20Hills,%20CA%2090210" var urlstring = "http://dev.virtualearth.net/REST/v1/Locations?q=" + address + "&key=" + bingkey var url = NSURL(string:urlstring) typealias ClosureSignatureForPrintingResult = (AnyObject?) -> () func parseJson(data: NSData, printResult:ClosureSignatureForPrintingResult) { var error: NSError? let json: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &error) if error != nil { println("Error parsing json: \(error)") printResult(nil) } else { printResult(json) } } func downloadJson(printResult:ClosureSignatureForPrintingResult) { func myDataTaskCH(let data:NSData!, let response:NSURLResponse!, let error:NSError!)->Void { if let httpResponse = response as? NSHTTPURLResponse { switch(httpResponse.statusCode) { case 200: println("got a 200") parseJson(data,printResult) default: println("Got an HTTP \(httpResponse.statusCode)") } } else { println("I don't know how to handle non-http responses") } running = false; } let task = session.dataTaskWithURL(url, myDataTaskCH) task.resume(); } func getSetGo() { println("starting the get") running = true; func printResult(jsonResponse:AnyObject?) ->Void { println(jsonResponse) } downloadJson(printResult) } getSetGo() while running { println("waiting...") sleep(1) }
true
bc678b606f68c7b64424e6b0c0a6ea4582ae35e1
Swift
voxqhuy/iOS-SmallApps
/Web/Web/PetitionAPI.swift
UTF-8
2,220
3.140625
3
[]
no_license
// // PetitionAPI.swift // Web // // Created by Vo Huy on 6/17/18. // Copyright © 2018 Vo Huy. All rights reserved. // import Foundation enum PetitionError: Error { case parsingError case statusError case urlContentError case invalidURLError } enum PetitionResult { case success([[String:String]]) case failure(Error) } class PetitionAPI { static let recentURLString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" static let topRatedURLString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100" static func fetchPetitions(forURL urlString: String, completion: @escaping (PetitionResult) -> Void) { // DispatchQueue.global(qos: .userInitiated).async { // [unowned self] in if let url = URL(string: urlString) { if let data = try? String(contentsOf: url) { let json = JSON(parseJSON: data) if json["metadata"]["responseInfo"]["status"].intValue == 200 { if let petitions = parse(json: json) { completion(.success(petitions)) } else { completion(.failure(PetitionError.parsingError)) } } else { completion(.failure(PetitionError.statusError)) } } else { completion(.failure(PetitionError.urlContentError)) } } else { completion(.failure(PetitionError.invalidURLError)) } // } return } } extension PetitionAPI { static func parse(json: JSON) -> [[String: String]]? { var petitions = [[String: String]]() for result in json["results"].arrayValue { let title = result["title"].stringValue let body = result["body"].stringValue let signatureCount = result["signatureCount"].stringValue petitions.append(["title": title, "body": body, "signatureCount": signatureCount]) } return petitions } }
true
8ab7e83d5b72dced548c2ce064f8217bcfb6996e
Swift
pabloroca/WeatherLondon
/WeatherLondon/Controllers/Cells/ForeCastSectionHeaderViewModel.swift
UTF-8
529
2.609375
3
[]
no_license
// // ForeCastSectionHeaderViewModel.swift // WeatherLondon // // Created by Pablo Roca Rozas on 11/10/18. // Copyright © 2018 PR2Studio. All rights reserved. // import Foundation struct ForeCastSectionHeaderViewModel { let title: String let tempMin: Double let tempMax: Double var suggestion: String init(title: String, tempMin: Double, tempMax: Double, suggestion: String) { self.title = title self.tempMin = tempMin self.tempMax = tempMax self.suggestion = suggestion } }
true
8adb2de44555df675209e64e7958f94ebc6773e9
Swift
benspratling4/SwiftFoundationCompression
/Sources/SwiftFoundationCompression/Data+Compression.swift
UTF-8
12,387
2.75
3
[]
no_license
// // Data+Compression.swift // FoundationZip // // Created by Ben Spratling on 10/9/16. // // import Foundation import zlib let memoryPageSize:Int = 4096 /// There are many ways to compress data, use this to pick which one. public enum CompressionTechnique { ///The default technique used in .zip files, aka "inflate" for decompression case deflate case gzip //If you would like additional techniques, like lz4, lzfsfzse or lzma, please request them. } extension Data { /// One shot data compression wrapping .zlib functionality /// TODO: add ability to get crc/adler values from the compression public func compressed(using technique:CompressionTechnique = .deflate, progress:CompressionProgressHandler? = nil)throws->Data { switch technique { case .deflate: return try deflate(progress:progress).data case .gzip: return try gzip(progress: progress) } } /// To decompress data, with the given technique. May throw a CompressionError public func decompressed(using technique:CompressionTechnique, progress:CompressionProgressHandler? = nil)throws->Data { switch technique { case .deflate: return try inflate(progress:progress) case .gzip : return try gunzip(progress:progress) } } /* //TODO: write me /// for stream-like writing to file public func decompress(using technique:CompressionTechnique, appendingTo handle:FileHandle)throws { ///TODO: write me } */ /// compresses the receiver into a "deflate" stream, does not provide file headers /// returns the data & crc of the uncompressed data func deflate(progress:CompressionProgressHandler? = nil)throws->(data:Data, crc:UInt32) { let chunkSize:Int = memoryPageSize let strategy:Int32 = 0 //default let compressionLevel:Int32 = -1 //default let memoryLevel:Int32 = 8 //how much internal memory is used //do the dual-buffer thing var inBuffer:[UInt8] = [UInt8](repeating:0, count:chunkSize) let inBufferPointer = UnsafeMutableBufferPointer(start: &inBuffer, count: chunkSize) var outBuffer:[UInt8] = [UInt8](repeating:0, count:chunkSize) let outBufferPointer = UnsafeMutableBufferPointer(start: &outBuffer, count: chunkSize) //pre-fill the inBuffer let countInBuffer:Int = Swift.min(chunkSize, self.count) let copiedByteCount:Int = self.copyBytes(to: inBufferPointer, from: 0..<countInBuffer) //init the stream var stream = z_stream(next_in: inBufferPointer.baseAddress, avail_in: UInt32(copiedByteCount), total_in: 0, next_out: nil, avail_out: 0, total_out: 0, msg: nil, state: nil, zalloc: nil, zfree: nil, opaque: nil, data_type: 0, adler: 0, reserved: 0) let windowBits:Int32 = -MAX_WBITS//(method == "gzip") ? MAX_WBITS + 16 : MAX_WBITS let result = deflateInit2_(&stream, compressionLevel, Z_DEFLATED, windowBits, memoryLevel, strategy, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) //check for init errors if result != Z_OK { throw CompressionError.fail(result) } //defer clean up defer { deflateEnd(&stream) } //TODO: support crc32 var crc:UInt = zlib.crc32(0, nil, 0) //loop over buffers var outData:Data = Data() var streamStatus:Int32 = Z_OK while streamStatus == Z_OK { //always provide at least a whole buffer of data let readBytes = Int(stream.total_in) let countInBuffer:Int = Swift.min(chunkSize, self.count - readBytes) let copiedByteCount:Int = self.copyBytes(to: inBufferPointer, from: readBytes..<(readBytes+countInBuffer)) stream.next_in = inBufferPointer.baseAddress stream.avail_in = UInt32(copiedByteCount) stream.next_out = outBufferPointer.baseAddress stream.avail_out = UInt32(chunkSize) //actual deflation let previousTotalOut:Int = Int(stream.total_out) streamStatus = zlib.deflate(&stream, copiedByteCount > 0 ? Z_NO_FLUSH : Z_FINISH) //check for errors if streamStatus != Z_OK && streamStatus != Z_STREAM_END && streamStatus != Z_BUF_ERROR { throw CompressionError.fail(streamStatus) } let readByteCount:Int = copiedByteCount - Int(stream.avail_in) crc = crc32(crc, inBufferPointer.baseAddress, UInt32(readByteCount)) //always copy out all written bytes let newOutByteCount:Int = Int(stream.total_out) - previousTotalOut outData.append(&outBuffer, count: newOutByteCount) } inBuffer = [] outBuffer = [] return (outData, UInt32(crc)) } // decompresses the receiver, assuming it is a "deflate" stream, not the contents of a .zip file, i.e. no local file header func inflate(progress:CompressionProgressHandler? = nil)throws->Data { //create the first buffer before initializing the stream... because backwards API's are wonderful :( let chunkSize:Int = memoryPageSize var copyBuffer:[UInt8] = [UInt8](repeating:0, count:chunkSize) let inputBuffer = UnsafeMutableBufferPointer(start: &copyBuffer, count: chunkSize) let availableByteCount:Int = Swift.min(self.count, chunkSize) let copiedByteCount:Int = self.copyBytes(to: inputBuffer, from: 0..<availableByteCount) var aStream:z_stream = z_stream(next_in: inputBuffer.baseAddress, avail_in: UInt32(availableByteCount), total_in: 0, next_out: nil, avail_out: 0, total_out: 0, msg: nil, state: nil, zalloc: nil, zfree: nil, opaque: nil, data_type: 0, adler: 0, reserved: 0) let windowBits:Int32 = -15 //some kind of magic value let initResult:Int32 = inflateInit2_(&aStream, windowBits, zlibVersion(), Int32(MemoryLayout<z_stream>.size)) //Check for init errors if initResult != Z_OK { throw CompressionError.fail(initResult) } //defer clean up defer { inflateEnd(&aStream) } //prepare an output buffer var decompressBuffer:[UInt8] = [UInt8](repeating:0, count:chunkSize) let outputBuffer = UnsafeMutableBufferPointer(start: &decompressBuffer, count: chunkSize) var outputData:Data = Data() let floatCount:Float32 = Float32(self.count) var streamStatus:Int32 = Z_OK while streamStatus == Z_OK { //copy next buffer-full of data let remainingByteCount:Int = self.count - Int(aStream.total_in) let countOfBytesToCopy:Int = Swift.min(remainingByteCount, chunkSize) let copiedByteCount:Int = self.copyBytes(to: inputBuffer, from: Int(aStream.total_in)..<(Int(aStream.total_in)+countOfBytesToCopy)) let oldTotalOut:UInt = aStream.total_out //update stream values aStream.next_in = inputBuffer.baseAddress aStream.avail_in = UInt32(copiedByteCount) aStream.next_out = outputBuffer.baseAddress aStream.avail_out = UInt32(chunkSize) //decompress streamStatus = zlib.inflate(&aStream, Z_SYNC_FLUSH) //check for decompression errors if streamStatus != Z_STREAM_END && streamStatus != Z_OK { throw CompressionError.fail(streamStatus) } //collect new data let newOutputByteCount:UInt = aStream.total_out - oldTotalOut if copiedByteCount > 0 { outputData.append(outputBuffer.baseAddress!, count: Int(newOutputByteCount)) } //update progress var shouldCancel:Bool = false progress?(Float32(aStream.total_in)/floatCount, &shouldCancel) if shouldCancel { throw CompressionError.canceled } } return outputData } func gunzip(progress:CompressionProgressHandler? = nil)throws->Data { //create the first buffer before initializing the stream... because backwards API's are wonderful :( let chunkSize:Int = memoryPageSize var copyBuffer:[UInt8] = [UInt8](repeating:0, count:chunkSize) let inputBuffer = UnsafeMutableBufferPointer(start: &copyBuffer, count: chunkSize) let availableByteCount:Int = Swift.min(self.count, chunkSize) let copiedByteCount:Int = self.copyBytes(to: inputBuffer, from: 0..<availableByteCount) var aStream:z_stream = z_stream(next_in: inputBuffer.baseAddress, avail_in: UInt32(availableByteCount), total_in: 0, next_out: nil, avail_out: 0, total_out: 0, msg: nil, state: nil, zalloc: nil, zfree: nil, opaque: nil, data_type: 0, adler: 0, reserved: 0) let windowBits:Int32 = 15 | 16 //some kind of magic value let initResult:Int32 = inflateInit2_(&aStream, windowBits, zlibVersion(), Int32(MemoryLayout<z_stream>.size)) //Check for init errors if initResult != Z_OK { throw CompressionError.fail(initResult) } //defer clean up defer { inflateEnd(&aStream) } //prepare an output buffer var decompressBuffer:[UInt8] = [UInt8](repeating:0, count:chunkSize) let outputBuffer = UnsafeMutableBufferPointer(start: &decompressBuffer, count: chunkSize) var outputData:Data = Data() let floatCount:Float32 = Float32(self.count) var streamStatus:Int32 = Z_OK while streamStatus == Z_OK { //copy next buffer-full of data let remainingByteCount:Int = self.count - Int(aStream.total_in) let countOfBytesToCopy:Int = Swift.min(remainingByteCount, chunkSize) let copiedByteCount:Int = self.copyBytes(to: inputBuffer, from: Int(aStream.total_in)..<(Int(aStream.total_in)+countOfBytesToCopy)) let oldTotalOut:UInt = aStream.total_out //update stream values aStream.next_in = inputBuffer.baseAddress aStream.avail_in = UInt32(copiedByteCount) aStream.next_out = outputBuffer.baseAddress aStream.avail_out = UInt32(chunkSize) //decompress streamStatus = zlib.inflate(&aStream, Z_SYNC_FLUSH) //check for decompression errors if streamStatus != Z_STREAM_END && streamStatus != Z_OK { throw CompressionError.fail(streamStatus) } //collect new data let newOutputByteCount:UInt = aStream.total_out - oldTotalOut if copiedByteCount > 0 { outputData.append(outputBuffer.baseAddress!, count: Int(newOutputByteCount)) } //update progress var shouldCancel:Bool = false progress?(Float32(aStream.total_in)/floatCount, &shouldCancel) if shouldCancel { throw CompressionError.canceled } } return outputData } func gzip(progress:CompressionProgressHandler? = nil)throws->Data { let chunkSize:Int = memoryPageSize let strategy:Int32 = 0 //default let compressionLevel:Int32 = -1 //default let memoryLevel:Int32 = 8 //how much internal memory is used //do the dual-buffer thing var inBuffer:[UInt8] = [UInt8](repeating:0, count:chunkSize) let inBufferPointer = UnsafeMutableBufferPointer(start: &inBuffer, count: chunkSize) var outBuffer:[UInt8] = [UInt8](repeating:0, count:chunkSize) let outBufferPointer = UnsafeMutableBufferPointer(start: &outBuffer, count: chunkSize) //pre-fill the inBuffer let countInBuffer:Int = Swift.min(chunkSize, self.count) let copiedByteCount:Int = self.copyBytes(to: inBufferPointer, from: 0..<countInBuffer) //init the stream var stream = z_stream(next_in: inBufferPointer.baseAddress, avail_in: UInt32(copiedByteCount), total_in: 0, next_out: nil, avail_out: 0, total_out: 0, msg: nil, state: nil, zalloc: nil, zfree: nil, opaque: nil, data_type: 0, adler: 0, reserved: 0) let windowBits:Int32 = MAX_WBITS | 16//(method == "gzip") ? MAX_WBITS + 16 : MAX_WBITS let result = deflateInit2_(&stream, compressionLevel, Z_DEFLATED, windowBits, memoryLevel, strategy, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) //check for init errors if result != Z_OK { throw CompressionError.fail(result) } //defer clean up defer { deflateEnd(&stream) } //loop over buffers var outData:Data = Data() var streamStatus:Int32 = Z_OK while streamStatus == Z_OK { //always provide at least a whole buffer of data let readBytes = Int(stream.total_in) let countInBuffer:Int = Swift.min(chunkSize, self.count - readBytes) let copiedByteCount:Int = self.copyBytes(to: inBufferPointer, from: readBytes..<(readBytes+countInBuffer)) stream.next_in = inBufferPointer.baseAddress stream.avail_in = UInt32(copiedByteCount) stream.next_out = outBufferPointer.baseAddress stream.avail_out = UInt32(chunkSize) //actual deflation let previousTotalOut:Int = Int(stream.total_out) streamStatus = zlib.deflate(&stream, copiedByteCount > 0 ? Z_NO_FLUSH : Z_FINISH) //check for errors if streamStatus != Z_OK && streamStatus != Z_STREAM_END && streamStatus != Z_BUF_ERROR { throw CompressionError.fail(streamStatus) } //always copy out all written bytes let newOutByteCount:Int = Int(stream.total_out) - previousTotalOut outData.append(&outBuffer, count: newOutByteCount) } return outData } }
true
c40adf0b484d48f20a18e959d034208abcb861a1
Swift
awesome-academy/NTC-Weather-Forecast-COVID-19
/NTC-Weather-Forecast-COVID-19/NTC-Weather-Forecast-COVID-19/Screen/WeatherForecast/SettingTemp/SettingTempViewController.swift
UTF-8
2,454
2.84375
3
[]
no_license
// // SettingTempViewController.swift // NTC-Weather-Forecast-COVID-19 // // Created by trần nam on 9/1/21. // import UIKit protocol SettingTempDelegate: AnyObject { func sendIndexTemp(indexTemp: Int) } final class SettingTempViewController: UIViewController { @IBOutlet private weak var settingTempTableView: UITableView! private var currentIndexTempFormat = 0 private let keyTempFormat = UserDefaultsKeys.keyTempFomat.rawValue weak var delegate: SettingTempDelegate? override func viewDidLoad() { super.viewDidLoad() settingTempTableView.delegate = self settingTempTableView.dataSource = self settingTempTableView.register(SettingTempTableViewCell.nib, forCellReuseIdentifier: SettingTempTableViewCell.reuseIdentifier) currentIndexTempFormat = (UserDefaults.standard.value(forKey: keyTempFormat) as? Int) ?? 0 } private func updateTempFormatInUserDefaults(newValue: Int) { UserDefaults.standard.set(newValue, forKey: keyTempFormat) } } extension SettingTempViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return TempFormat.allCases.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell( withIdentifier: SettingTempTableViewCell.reuseIdentifier) as? SettingTempTableViewCell { let temp = TempFormat.allCases[indexPath.row].rawValue.components(separatedBy: " ") cell.configView(temp: temp) if indexPath.row == currentIndexTempFormat { cell.accessoryType = .checkmark } return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark if indexPath.row != currentIndexTempFormat { dismiss(animated: true) { [weak self] in guard let self = self else { return } self.updateTempFormatInUserDefaults(newValue: indexPath.row) self.delegate?.sendIndexTemp(indexTemp: indexPath.row) } } tableView.deselectRow(at: indexPath, animated: true) } }
true
3ca27ad9dc5afa4769c2fb5a33b54e7dc06158a5
Swift
venkatp4/testrepro
/Sources/CNXPackageManger/Cards/HorizontalCard/HorizontalCard.swift
UTF-8
4,697
3.046875
3
[]
no_license
// // HorizontalCard.swift // CNXUIKit // // Created by VeeraSubhash on 23/08/21. // import SwiftUI extension View { func getWidth() -> CGFloat { return UIScreen.main.bounds.width } } //extension VerticalAlignment { // struct CustomAlignment: AlignmentID { // static func defaultValue(in context: ViewDimensions) -> CGFloat { // return context[VerticalAlignment.center] // } // } // // static let custom = VerticalAlignment(CustomAlignment.self) //} public struct HorizontalCard: View { public typealias CheckBoxButtonCallBack = () -> Void public var checkBoxButtonAction: CheckBoxButtonCallBack public typealias ArrowButtonCallBack = () -> Void public var arrowButtonAction: ArrowButtonCallBack public typealias ToggleButtonCallBack = () -> Void public var toggleButtonAction: ToggleButtonCallBack @State private var isOn = true var cardData: HorizontalCardData public init(cardData: HorizontalCardData, checkBoxButtonAction: @escaping CheckBoxButtonCallBack, arrowButtonAction: @escaping ArrowButtonCallBack, toggleButtonAction: @escaping ToggleButtonCallBack) { self.cardData = cardData self.checkBoxButtonAction = checkBoxButtonAction self.arrowButtonAction = arrowButtonAction self.toggleButtonAction = toggleButtonAction } public var body: some View { HStack(alignment: .center) { cardData.leftIcon? .resizable() // .scaledToFit() // .aspectRatio(contentMode: .fit) .frame(width: 39, height: 39, alignment: .leading) .cornerRadius(CNXTheme.buttonCornerRadius) Text(cardData.title) .font(CNXTheme.font.imageButton) .foregroundColor(CNXTheme.color.titleColor) .frame(alignment: .leading) .padding(.leading, 10) Spacer() switch cardData.clickableCardType { case .arrow: Button(action: { print("Arrow Button Clicked") }) { Image.createImageFromCNXUIKit(with: "right-arrow") .resizable() .renderingMode(.original) .aspectRatio(contentMode: .fit) .frame(width: 14, height: 14, alignment: .trailing) .onTapGesture { arrowButtonAction() } } case .toggle: Toggle(isOn: $isOn) { Text("") } .frame(width: 40, height: 20) .toggleStyle(CustomToggleStyle(trailingButtonAction: { toggleButtonAction() })) case .checkbox: Button(action: { print("Checkbox Button Clicked") }) { // TO DO: - Add condition // Image.createImageFromCNXUIKit(with: "checkbox-unchecked") // .resizable() // .frame(width: 15, height: 15, alignment: .trailing) Toggle(isOn: $isOn) { Text("") } .frame(width: 20, height: 20) .toggleStyle(CheckBoxToggleStyle(trailingButtonAction: { checkBoxButtonAction() })) } case nil: Spacer().frame(width: 0) case .some(.none): Spacer() } } .padding(.leading, 10) .padding(.trailing, 20) .padding([.top, .bottom], 10) .frame(height: 54) } } struct HorizontalCard_Previews: PreviewProvider { static var previews: some View { let data = HorizontalCardData(leftIcon: Image("bigImage"), title: "SwiftUI", clickableButtonType: .arrow) HorizontalCard(cardData: data, checkBoxButtonAction: { print("Horizontal Card CheckBoxTrailing Button Action_Previews") }, arrowButtonAction: { print("Horizontal Card Arrow Trailing Button Action_Previews") }, toggleButtonAction: { print("Horizontal Card Toggle Trailing Button Action_Previews") }) } }
true
3a189be076428c68195c9c1844a65eed461855a8
Swift
dushyant-dahiya/AllAboutDelhi
/AllAboutDelhi/Shopping.swift
UTF-8
1,189
2.71875
3
[]
no_license
// // Shopping.swift // AllAboutDelhi // // Created by Dushyant Dahiya on 9/3/16. // Copyright © 2016 DUSHYANT DAHIYA. All rights reserved. // import Foundation class Shopping { fileprivate var _address: String! fileprivate var _name: String! fileprivate var _longitude: Double! fileprivate var _latitude: Double! fileprivate var _fb: String! fileprivate var _url: String! fileprivate var _category: String! var address: String { return _address } var name: String { return _name } var longitude: Double { return _longitude } var latitude: Double { return _latitude } var fb: String { return _fb } var url: String { return _url } var category: String { return _category } init(address: String, name: String, longitude: Double, latitude: Double, fb: String, url: String, category: String){ self._address = address self._name = name self._longitude = longitude self._latitude = latitude self._category = category self._fb = fb self._url = url } }
true
299bd3de401c98a4f863f2fbcc1953c98465e5ff
Swift
yuanjilee/keyboard
/iOS_KeyboardTest/SecoondViewController.swift
UTF-8
1,076
2.546875
3
[]
no_license
// // SecoondViewController.swift // iOS_KeyboardTest // // Created by yuanjilee on 2017/4/7. // Copyright © 2017年 Worktile. All rights reserved. // import UIKit class SecoondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = .white navigationItem.title = "Second" NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil) setupAppearance() } func keyboardWillShow() { debugPrint("Will Show") } func keyboardWillHidden() { debugPrint("Will Hidden") } func setupAppearance() { let field = UITextField() field.frame = CGRect(x: 100, y: 100, width: 200, height: 30) field.borderStyle = .roundedRect view.addSubview(field) } }
true
abe5313e86b9d7ceff2a465e3dd784518f344ca2
Swift
bobosanta/Products-App-ios
/Products/Products-Root/Networking/APIClient.swift
UTF-8
2,297
3.0625
3
[]
no_license
// // APIClient.swift // Products // // Created by bogdan razvan on 01/03/2020. // Copyright © 2020 Archlime. All rights reserved. // import Alamofire /** * General protocol used for API request/response management * Implemented by Repositories that make API calls */ protocol APIClient { func performRequest<T: Decodable>(route: APIRouter, completion: @escaping (APIResponse<T>) -> Void) } // MARK: - Default Implementation extension APIClient { /// Method performing a network request having a callback of concrete type 'Decodable'. /// - Parameter route: the route. /// - Parameter completion: completion handler. func performRequest<T: Decodable>(route: APIRouter, completion: @escaping (APIResponse<T>) -> Void) { print(route.path) AF.request(route) .responseJSON(completionHandler: { response in print(response) }) .responseDecodable (decoder: JSONDecoder()) {(response: AFDataResponse<T>) in self.parseResponse(route: route, response: response, completion: completion) } } // MARK: - Private functions /// Method used for parsing a response of generic type. /// - Parameter route: the route of the request. /// - Parameter response: the response to be parsed. /// - Parameter completion: the completion handler containing the result of the parsint: success or failure. private func parseResponse<T: Decodable>(route: APIRouter, response: AFDataResponse<T>, completion: @escaping (APIResponse<T>) -> Void) { if let error = self.checkError(response: response) { completion(APIResponse.failure(error)) } else { switch response.result { case .success(let data): completion(APIResponse<T>.success(data)) case .failure(let error): completion(APIResponse.failure(APIError(error))) } } } private func checkError<T>(response: AFDataResponse<T>) -> APIError? { if let statusCode = response.response?.statusCode, statusCode >= 300, let data = response.data, let error = try? JSONDecoder().decode(APIError.self, from: data) { return error } return nil } }
true
b46a3561a82f8189e33d3e19060609c5a270d55f
Swift
FilipGonera/Weather-App
/CurrentWeatherViewController.swift
UTF-8
2,791
2.796875
3
[]
no_license
// // ViewController.swift // Weather app // // Created by Filip Gonera on 31/08/2018. // Copyright © 2018 Filip Gonera. All rights reserved. // import Foundation import UIKit import CoreLocation import Alamofire class CurrentWeatherViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var dayLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var weatherDescriptionLabel: UILabel! @IBOutlet weak var tempretureLabel: UILabel! var lat = 64.128288 var lon = -21.827774 let locationManager = CLLocationManager() var currentWeather: CurrentWeather! var currentLocation: CLLocation! override func viewDidLoad() { super.viewDidLoad() callDelegates() setupLocation() locationAuthCheck() // Do any additional setup after loading the view, typically from a nib. } func callDelegates(){ locationManager.delegate = self } func setupLocation(){ locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startMonitoringSignificantLocationChanges() } func locationAuthCheck(){ if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{ currentLocation = locationManager.location lat = currentLocation.coordinate.latitude lon = currentLocation.coordinate.longitude Location.sharedInstance.latitude = lat Location.sharedInstance.longitude = lon print(lat) print(lon) currentWeather = CurrentWeather() currentWeather.downloadCurrentWeather { self.updateUI() // Here I update the UI after completion of downloading data } } else { locationManager.requestWhenInUseAuthorization() locationAuthCheck() } } func updateUI() { print("updateUI called") // For debuging purpose I check if updateUI was successfuly called print(currentWeather.location) self.locationLabel.text = currentWeather.location print(currentWeather.location) self.iconImageView.image = UIImage(named: currentWeather.iconName) print(currentWeather.iconName) self.weatherDescriptionLabel.text = currentWeather.weatherDescription self.tempretureLabel.text = currentWeather.currentTemp self.dayLabel.text = currentWeather.day } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
77663d0a1ffb6a25edbdb61d4f84564ceeebf255
Swift
makingdevs/JugoTerapia-iOS
/JugoTerapia/JuicyCategory.swift
UTF-8
302
2.671875
3
[]
no_license
// // JuicyCategory.swift // JugoTerapia // // Created by José Juan Reyes Zuniga on 29/11/15. // Copyright © 2015 MakingDevs. All rights reserved. // struct JuicyCategory { let id:Int let categoryName:String init(id: Int, categoryName:String){ self.id = id self.categoryName = categoryName } }
true
7716ac22df29f48084f6cc4dbc5177938ed9dc4a
Swift
navi380/IOSMVVM
/MvvmProjectCleanStructure/Network/GenericApiImplementation/NetworkClient.swift
UTF-8
905
2.90625
3
[]
no_license
// // NetworkClient.swift // MvvmProjectCleanStructure // // Created by Naveed Tahir on 10/08/2021. // import Foundation import Foundation protocol NetworkLoader { func loadData(using request: URLRequest, with completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) } extension URLSession: NetworkLoader { func loadData(using request: URLRequest, with completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) { self.dataTask(with: request) { (data, response, error) in if error != nil || data == nil { print("Client error!") return } guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else { print("Server error!") return } completion(data, response, error) }.resume() } }
true
570eebaec99d9301c1b0fcdbc8c832ebc99a9d3c
Swift
LoiKos/kituraAPI
/Tests/ApiTests/PrintLogger.swift
UTF-8
1,962
3.046875
3
[]
no_license
// // File.swift // kituraMbao // // Created by Loic LE PENN on 31/08/2017. // // import Foundation import LoggerAPI /// The set of colors used when logging with colorized lines public enum TerminalColor: String { /// Log text in white. case white = "\u{001B}[0;37m" // white /// Log text in red, used for error messages. case red = "\u{001B}[0;31m" // red /// Log text in yellow, used for warning messages. case yellow = "\u{001B}[0;33m" // yellow /// Log text in the terminal's default foreground color. case foreground = "\u{001B}[0;39m" // default foreground color /// Log text in the terminal's default background color. case background = "\u{001B}[0;49m" // default background color } public class PrintLogger: Logger { let colored: Bool init(colored: Bool) { self.colored = colored } public func log(_ type: LoggerMessageType, msg: String, functionName: String, lineNum: Int, fileName: String ) { let message = "[\(type)] [\(getFile(fileName)):\(lineNum) \(functionName)] \(msg)" guard colored else { print(message) return } let color: TerminalColor switch type { case .warning: color = .yellow case .error: color = .red default: color = .foreground } print(color.rawValue + message + TerminalColor.foreground.rawValue) } public func isLogging(_ level: LoggerAPI.LoggerMessageType) -> Bool { return true } public static func use(colored: Bool) { Log.logger = PrintLogger(colored: colored) setbuf(stdout, nil) } private func getFile(_ path: String) -> String { guard let range = path.range(of: "/", options: .backwards) else { return path } return path.substring(from: range.upperBound) } }
true
b42eeb30b57a6f3895551874f03850ed042e57fb
Swift
diana311-web/DoggohApp
/Doggoh-Starter/Network/DogAPIClient2.swift
UTF-8
3,437
2.8125
3
[]
no_license
// // DogAPIClient2.swift // Doggoh-Starter // // Created by Elena Gaman on 20/08/2019. // Copyright © 2019 Endava Internship 2019. All rights reserved. // import Foundation import Alamofire enum DogAPI2{ case tags case postTags } extension DogAPI2{ var url: String { switch self { case .tags: return "tags" case .postTags: return "tags" } } var method: HTTPMethod { switch self { case .tags: return .get case .postTags: return .post } } } class DogAPI2Client { static let sharedInstance = DogAPI2Client(baseURL:"https://api.imagga.com/v2/") let baseURL: String let headers: HTTPHeaders = ["Authorization": AuthParameter.basicAuth ] private init(baseURL: String) { self.baseURL = baseURL } private struct AuthParameter { static let basicAuth = "Basic YWNjXzZlOGM4ZjJjNGMzN2VjNjo3ZDUxODhjNTA0ZTYzYTVlMmIyNjFlMjgzNmI1MjRlOA==" } private struct Parameter { static let imageUrl = "image_url" static let image = "image" } func getTags(for imageURL: String) { let parameters = [Parameter.imageUrl : imageURL] request(endpoint: DogAPI2.tags, parameters: parameters).responseJSON { response in switch response.result { case .failure(let error): print(error) case .success(let value): if let data = response.data { do { print(value) let responseObject = try JSONDecoder().decode(TagsResponse.self, from: data) print(responseObject) } catch let error { print(error) } } } } } func postTags(with image: UIImage,_ completion: @escaping (Result<[String], Error>) -> Void){ let url = "\(baseURL)\(DogAPI2.postTags.url)" AF.upload(multipartFormData: { (multipartFromData) in multipartFromData.append(image.pngData()!, withName: Parameter.image, fileName: "dog.jpg", mimeType: "image/jpg") }, to: url, headers: headers).responseJSON { response in switch response.result { case .failure(let error): completion(.failure(error)) case .success(let value): if let data = response.data { do { // print(value) var dogs : [String] = [] let responseObject = try JSONDecoder().decode(TagsResponse.self, from: data) // print(responseObject) for item in responseObject.result.tags{ dogs.append(item.tag.en) } completion(.success(dogs)) } catch let error { print(error) completion(.failure(error)) } } } } } private func request(endpoint: DogAPI2, parameters: Parameters? = nil ) -> DataRequest { let url = "\(baseURL)\(endpoint.url)" return AF.request(url, method: endpoint.method, parameters: parameters, headers: headers) } }
true
be87d0a13164b8369b378ef2d39fab78a2a81f42
Swift
derekli66/Algorithm-In-Swift
/Others/DEQUE/Tests/DEQUETests/STACKTests.swift
UTF-8
1,150
2.75
3
[]
no_license
import XCTest @testable import STACK final class STACKTests: XCTestCase { func testInsert() { var stack = Stack<Int>() stack.insert(999) XCTAssert(stack.top! == 999) XCTAssert(stack.pop()! == 999) XCTAssert(stack.top == nil) } func testInsertAndPop() { var stack = Stack<Int>() for idx in 100..<1001 { stack.insert(idx) XCTAssert(stack.top! == idx) } for idx in (100..<1001).reversed() { XCTAssert(stack.pop()! == idx) } } func testCopyOnWrite() { var stack1 = Stack<Int>() stack1.insert(100) stack1.insert(200) stack1.insert(300) var stack2 = stack1 XCTAssert(stack2.pop()! == 300) XCTAssert(stack2.top! == 200) XCTAssert(stack1.top! == 300) stack1.insert(400) stack2.insert(999) XCTAssert(stack1.top! == 400) XCTAssert(stack2.top! == 999) } static var allTests = [ ("testInsert", testInsert), ("testInsertAndPop", testInsertAndPop), ("testCopyOnWrite", testCopyOnWrite) ] }
true
1903d5e90596d5d291f241ea41f29d834abcbca9
Swift
juliofihdeldev/learnSwiftUI
/HaitiCine/InstagramItemView.swift
UTF-8
3,814
3.03125
3
[]
no_license
import SwiftUI struct InstagramItemView: View { var body: some View { VStack{ frame( idealHeight: 200, maxHeight: 300, alignment: .leading) HStack{ VStack{ Image("espn") .resizable() .aspectRatio(contentMode: .fit) .frame(idealWidth: 40, idealHeight: 40) .clipShape(Circle()) }.frame(width: 90, height:90) VStack(alignment: .leading){ Text("ESPN") .frame(maxWidth: .infinity, alignment: .leading) .font(.headline) Text("ESPN Wide World of Sports") .frame(maxWidth: .infinity, alignment: .leading) .font(.body) } Spacer() VStack(alignment: .leading){ Button(action: { print("Button was tapped") }) { Image(systemName: "livephoto.play") .font(Font.system(size: 40, weight: .ultraLight)) .accentColor(Color.black) } } } .padding(4.0) .background(Color.white) .clipped()// apply only on stack .shadow(color: Color.gray, radius: 1, x: 0, y: 0) HStack { Image("lakers") .resizable() .aspectRatio(contentMode: .fit).cornerRadius(0) .clipShape(Rectangle()) .padding(.all, 0.0) } VStack{ HStack(spacing: 16){ Button(action: { print("Button was heart") }) { Image(systemName: "heart") .font(Font.system(size: 40, weight: .ultraLight)) .accentColor(Color.black) } Button(action: { print("Button was message") }) { Image(systemName: "message") .font(Font.system(size: 40, weight: .ultraLight)) .accentColor(Color.black) } Button(action: { print("Button was icloud") }) { Image(systemName: "icloud") .font(Font.system(size: 40, weight: .ultraLight)) .accentColor(Color.black) } Spacer() Button(action: { print("Button was pencil") }) { Image(systemName: "pencil.tip") .font(Font.system(size: 50, weight: .ultraLight)) .accentColor(Color.black) } } } .padding(16.0) Spacer() } } } struct InstagramItemView_Previews: PreviewProvider { static var previews: some View { InstagramItemView() } }
true
19d381f868f2764f46bbcfcf176b7435e8c11dfb
Swift
avito-tech/Mixbox
/Frameworks/Gray/Sources/Utils/MenuItem/GrayMenuItem.swift
UTF-8
4,043
2.53125
3
[ "MIT" ]
permissive
import MixboxUiTestsFoundation import MixboxTestsFoundation import MixboxFoundation import MixboxIpcCommon final class GrayMenuItem: MenuItem, CustomStringConvertible { private let possibleTitles: [String] private let elementFinder: ElementFinder private let elementMatcherBuilder: ElementMatcherBuilder private let elementSimpleGesturesProvider: ElementSimpleGesturesProvider private let runLoopSpinnerFactory: RunLoopSpinnerFactory init( possibleTitles: [String], elementFinder: ElementFinder, elementMatcherBuilder: ElementMatcherBuilder, elementSimpleGesturesProvider: ElementSimpleGesturesProvider, runLoopSpinnerFactory: RunLoopSpinnerFactory) { self.possibleTitles = possibleTitles self.elementFinder = elementFinder self.elementMatcherBuilder = elementMatcherBuilder self.elementSimpleGesturesProvider = elementSimpleGesturesProvider self.runLoopSpinnerFactory = runLoopSpinnerFactory } // MARK: - MenuItem func tap() throws { let elementSnapshot = try resolveSnapshot() let elementSimpleGestures = try elementSimpleGesturesProvider.elementSimpleGestures( elementSnapshot: elementSnapshot, pointOnScreen: elementSnapshot.frameRelativeToScreen.mb_center ) try elementSimpleGestures.tap() } func waitForExistence(timeout: TimeInterval) throws { var errorToThrow: Error? let spinUntilResult = runLoopSpinnerFactory.runLoopSpinner(timeout: timeout).spinUntil { [weak self] in guard let strongSelf = self else { errorToThrow = ErrorString("self is nil in GrayMenuItem") return true // stop } do { _ = try strongSelf.resolveSnapshot() return true // stop } catch { errorToThrow = error return false // continue } } if let error = errorToThrow { throw error } else if spinUntilResult == .timedOut { // This should never happen: // - either true is returned from `stopConditionBlock` of `spinUntil` so `spinUntilResult` will be `stopConditionMet` // - or `errorToThrow` is set inside `stopConditionBlock` // // TODO: Insert not-fatal assertion failure that would only work in Tests on Mixbox. _ = try resolveSnapshot() } } private func resolveSnapshot() throws -> ElementSnapshot { let element = elementMatcherBuilder let query = elementFinder.query( elementMatcher: element.type == .button && possibleTitles.reduce(AlwaysFalseMatcher()) { result, title in result || element.accessibilityLabel == title }, elementFunctionDeclarationLocation: FunctionDeclarationLocation( fileLine: .current(), function: #function ) ) let resolvedQuery = query.resolveElement(interactionMode: .useUniqueElement) let matchingSnapshots = resolvedQuery.matchingSnapshots guard let first = matchingSnapshots.first else { throw ErrorString("Couldn't find \(description)") } guard matchingSnapshots.count == 1 else { throw ErrorString("Found multiple matches of \(description)") } return first } // MARK: - CustomStringConvertible var description: String { let titlesDescription = possibleMenuTitlesDescription() return "button with one of the possible titles: \(titlesDescription)" } private func possibleMenuTitlesDescription() -> String { return possibleTitles .map { "\"\($0)\"" } .joined(separator: " or ") } }
true
c96102d571cfbe909c68963dfad2209bd0303be8
Swift
MRuslanMS/GBSWIFT
/4kurs/lesson3/VKProject1/VKProject1/Services/SearchGroup.swift
UTF-8
2,206
3
3
[]
no_license
// // SearchGroup.swift // VKProject1 // // Created by xc553a8 on 11.10.2021. // import Foundation class SearchGroup { //данные для авторизации в ВК func loadData(searchText:String, complition: @escaping ([Group]) -> Void ) { // Конфигурация по умолчанию let configuration = URLSessionConfiguration.default // собственная сессия let session = URLSession(configuration: configuration) // конструктор для URL var urlConstructor = URLComponents() urlConstructor.scheme = "https" urlConstructor.host = "api.vk.com" urlConstructor.path = "/method/groups.search" urlConstructor.queryItems = [ URLQueryItem(name: "q", value: searchText), URLQueryItem(name: "type", value: "group"), URLQueryItem(name: "access_token", value: Session.instance.token), URLQueryItem(name: "v", value: "5.122") ] // задача для запуска let task = session.dataTask(with: urlConstructor.url!) { (data, response, error) in //print("Запрос к API: \(urlConstructor.url!)") // в замыкании данные, полученные от сервера, мы преобразуем в json guard let data = data else { return } do { let arrayGroups = try JSONDecoder().decode(GroupsResponse.self, from: data) var searchGroup: [Group] = [] for i in 0...arrayGroups.response.items.count-1 { let name = ((arrayGroups.response.items[i].name)) let logo = arrayGroups.response.items[i].logo let id = arrayGroups.response.items[i].id searchGroup.append(Group.init(groupName: name, groupLogo: logo, id: id)) } complition(searchGroup) } catch let error { print(error) complition([]) } } task.resume() } }
true
cb6025d04039644d92ab1b0da79d63c3bf11bb67
Swift
abhi7054/Work-Courses-LMS
/Work Courses LMS/Support.swift
UTF-8
4,777
2.65625
3
[]
no_license
// // Support.swift // Work Courses LMS // // Created by Arpit on 10/2/20. // Copyright © 2020 Dev Abhi. All rights reserved. // import UIKit extension String { enum ValidityType { case name case studentName case groupName case phoneNumber case password case numberOfBuses } enum Regex: String { case name = "[A-Za-z0-9 ]{4,}" case studentName = "(?i)ST[A-Za-z0-9]{2,}" case groupName = "(?i)GR[A-Za-z0-9]{2,}" case phoneNumber = "[0-9]{10,10}" case numberOfBuses = "[0-9]{0,}" } func isValid(_ validityType: ValidityType) -> Bool { let format = "SELF MATCHES %@" var regex = "" switch validityType { case .name: regex = Regex.name.rawValue case .studentName : regex = Regex.studentName.rawValue case .groupName : regex = Regex.groupName.rawValue case .phoneNumber : regex = Regex.phoneNumber.rawValue case .numberOfBuses : regex = Regex.numberOfBuses.rawValue case .password : return (self.count >= 6) } return NSPredicate(format: format, regex).evaluate(with: self) } } extension UIViewController { func viewController(viewController:String!, fromStoryBoard storyBoard : String!) -> UIViewController? { let storyboard = UIStoryboard(name: storyBoard, bundle: Bundle.main) return storyboard.instantiateViewController(withIdentifier:viewController) } static func viewController(viewController:String, fromStoryBoard storyBoard : String) -> UIViewController? { let storyboard = UIStoryboard(name: storyBoard, bundle: Bundle.main) return storyboard.instantiateViewController(withIdentifier:viewController) } func showToast(title:String?, message:String?, duration:Double = 3) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) self.present(alert, animated: true) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) { alert.dismiss(animated: true) } } func showAlert(title:String?, message:String?, actions:[String]) { let ac = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) self.present(ac, animated: true, completion: nil) } func show(_ title: String? = nil, _ message: String? = nil, _ cancelAction: String, _ confirmAction: String, onSelectConfirm: @escaping (Bool) -> Void) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: cancelAction, style: .cancel, handler: { (_) in onSelectConfirm(false) })) alert.addAction(UIAlertAction(title: confirmAction, style: .default, handler: { (_) in onSelectConfirm(true) })) self.present(alert, animated: true, completion: nil) } func show(_ title: String? = nil, _ message: String? = nil, _ actionName: String? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: actionName == nil ? "Ok" : actionName, style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } func show(_ title: String? = nil, _ message: String? = nil, _ confirmAction: String, onSelectConfirm: @escaping (Bool) -> Void) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: confirmAction, style: .default, handler: { (_) in onSelectConfirm(true) })) self.present(alert, animated: true, completion: nil) } } extension UITableView { func register(nib name:String, identifier:String) { self.register(UINib(nibName: name, bundle: nil), forCellReuseIdentifier: identifier) } } extension String { var capitalizeFirstLetter : String { get { let first = String(self.prefix(1)).capitalized let other = String(self.dropFirst()) return first + other } } func heightWithConstraint(width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil) return boundingBox.height } } extension UITextField { var isEmpty: Bool { return text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" } }
true
f1ae2d87c836b6490d99bdf82b6a9973015a6e32
Swift
hannyA/kwikcy2
/PopIn/HAButtonDisableOverlay.swift
UTF-8
1,304
2.640625
3
[]
no_license
// // HAButtonDisableOverlay.swift // PopIn // // Created by Hanny Aly on 6/17/16. // Copyright © 2016 Aly LLC. All rights reserved. // import AsyncDisplayKit class HAButtonDisableOverlay: ASButtonNode { var overlay: ASDisplayNode override init() { overlay = ASDisplayNode() super.init() overlay.backgroundColor = UIColor(white: 0.5, alpha: 0.5) overlay.hidden = true } func disable(disabled:Bool) { overlay.hidden = disabled } override func layoutSpecThatFits(constrainedSize: ASSizeRange) -> ASLayoutSpec { let height = constrainedSize.max.height let width = constrainedSize.max.width overlay.preferredFrameSize = CGSizeMake(width, height) let overlayFG = ASStaticLayoutSpec(children: [overlay]) let overlayView = ASCenterLayoutSpec(centeringOptions: .XY, sizingOptions: .Default, child: overlayFG) let overlayOverButton = ASOverlayLayoutSpec(child: self, overlay: overlayView) return overlayOverButton } }
true
7b91797a6d9b1a124c7f4e9701c176c523bb37b8
Swift
rahulbelekar/ParkingLotAssignment
/ParkingLot/Models/ParkingSpace.swift
UTF-8
1,078
3.125
3
[ "MIT" ]
permissive
// // ParkingSpace.swift // ParkingLot // // Created by Rahul Belekar on 04/07/20. // Copyright © 2020 Company. All rights reserved. // import Foundation //class ParkingSpace { // private var vehicle: Vehicle? // private var spotSize: VehicleType? // private var row: Int? // private var spotNumber: Int? // private var level: Int? // // func parkingSpace(lvl: Int, row: Int, number: Int, size: VehicleType) { // // } // // func isAvailable() -> Bool { // return vehicle == nil // } // // func canFitVehicle(vehicle: Vehicle) -> Bool { // return true //Check if the spot is big enough and is available // } // // func canPark(vehicle: Vehicle) -> Bool { // return true //Park vehicle in this spot. // } // // func getRow() -> Int? { // return row // } // // func getSpaceNumber() -> Int? { // return spotNumber // } // // func removeVehicel() { // //Remove vehicle from spot, and notify // //level that a new spot is available // } //}
true
51a97d0af5ca7c4646b55ab67c3082a31623fabf
Swift
Softwareengineering-S/Custom-Podcast-Icon
/Custom Podcast Icon/Custom Podcast Icon/ContentView.swift
UTF-8
1,386
2.8125
3
[]
no_license
// // ContentView.swift // Custom Podcast Icon // // Created by Monique Shaqiri on 15.05.21. // Copyright © 2021 Monique Shaqiri. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { ZStack { Circle() .frame(width: 120, height: 120) .foregroundColor(.red) .overlay( Circle() .stroke(Color.gray, lineWidth: 2) .frame(width: 128, height: 128)) Rectangle() .frame(width: 16, height: 2) .foregroundColor(.white) offset(y: 32) Rectangle() .frame(width: 2, height: 16) .foregroundColor(.white) offset(y: 24) Capsule() .trim(from: 1/2, to: 1) .stroke(Color.white, lineWidth: 2) .frame(width: 32, height: 42) .rotationEffect(.degrees(180)) .offset(y: -6) Capsule() .stroke(Color.white, lineWidth: 2) .frame(width: 24, height: 48) .offset(y: -14) }.scaleEffect(2, anchor: .center) } } #if DEBUG struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } #endif
true
f62cb2a8fa7e1e48b316e8d72b6437b7869a8859
Swift
mumuWorld/FuckQQ
/fuckqq/fuckqq/RandomColor.swift
UTF-8
489
2.609375
3
[]
no_license
// // RandomColor.swift // fuckqq // // Created by YangJie on 2017/7/17. // Copyright © 2017年 YangJie. All rights reserved. // import UIKit extension UIColor { open class var randomColor:UIColor{ get{ let r = arc4random_uniform(256); let g = arc4random_uniform(256); let b = arc4random_uniform(256); return UIColor.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0) } } }
true
0a9d779829a5dfb292a8f4aa2b615f020ef1c435
Swift
Jaymondr/FamilyNightProject
/FamilyNight/FamilyNight/Helper and Extension/Ideas.swift
UTF-8
2,318
2.96875
3
[]
no_license
// // EventIdeas.swift // FamilyNight // // Created by Jaymond Richardson on 6/8/21. // import Foundation class Idea { var title: String init(title: String) { self.title = title } } var ideas: [Idea] = [ Idea(title: "Go on a walk"), Idea(title: "Wash the car"), Idea(title: "Go to the zoo"), Idea(title: "Throw a slumber party"), Idea(title: "Camp in the backyard"), Idea(title: "Go through baby photos"), Idea(title: "Try a new cookie recipe"), Idea(title: "Visit the library"), Idea(title: "Play kick-ball"), Idea(title: "Plant a garden"), Idea(title: "Visit a museum"), Idea(title: "Record acting out a play"), Idea(title: "Fly a kite"), Idea(title: "Play hide and seek in the dark"), Idea(title: "Go on a hike"), Idea(title: "Have a race"), Idea(title: "Tell scary stories in the dark"), Idea(title: "Make a rope swing and hang it in a tree"), Idea(title: "Draw funny faces of each other"), Idea(title: "Go ice blocking"), Idea(title: "Go to a lake"), Idea(title: "Play sardines in a forest"), Idea(title: "Play tag on a park gymnasium"), Idea(title: "Drive through town and read historical signs"), Idea(title: "Play tag football"), Idea(title: "Doorbell-Ditch: Nice letters to your neighbors, or friends"), Idea(title: "Visit a local book store"), Idea(title: "Say why your grateful for each other"), Idea(title: "Make a lemonade stand"), Idea(title: "Babysit friendsdi or neighbors kids for free so parents can go out"), Idea(title: "Have a formal dinner"), Idea(title: "Have a garage sale"), Idea(title: "Go through a drive through and pay for the car behind you"), Idea(title: "Have ice cream for breakfast, and talk about why you dont care"), Idea(title: "Go fishing"), Idea(title: "Visit a waterfall"), Idea(title: "Go bird watching"), Idea(title: "Video call a loved one"), Idea(title: "Go to a local bakery"), Idea(title: "Make cookies for your neighbor"), Idea(title: "Play charades with chalk outside"), Idea(title: "Go to the zoo") ] func randomIdea() -> String { let randomIdea = Int(arc4random_uniform(UInt32(ideas.count))) let placeHolderIdea = ideas.remove(at: randomIdea) return placeHolderIdea.title }
true
7e42b6f04c408798c651708537f9392036ca4427
Swift
muzicaed/sl-smart
/Res Smart WatchKit App/Services/ScorePostHelper.swift
UTF-8
6,131
2.515625
3
[]
no_license
// // ScorePostHelper.swift // SL Smart // // Created by Mikael Hellman on 2015-11-29. // Copyright © 2015 Mikael Hellman. All rights reserved. // import Foundation import CoreLocation class ScorePostHelper { static let NewRoutineTripScore = Float(5) static let TapCountScore = Float(2) static let NotBestTripScore = Float(-1) static let RequiredDistance = Double(400) /** * Creates the score posts to represent a newly * created routine trip. */ static func giveScoreForNewRoutineTrip(routineTrip: RoutineTrip) { var scorePosts = DataStore.sharedInstance.retrieveScorePosts() if routineTrip.routine != nil { scoreForRoutineTrip(routineTrip, scorePosts: &scorePosts, scoreMod: NewRoutineTripScore, location: nil) } DataStore.sharedInstance.writeScorePosts(scorePosts) } /** * Handles changes to rotine for modified routine trip */ static func giveScoreForUpdatedRoutineTrip( updatedRoutineTrip: RoutineTrip, oldRoutineTrip: RoutineTrip) { var scorePosts = DataStore.sharedInstance.retrieveScorePosts() if oldRoutineTrip.routine != nil { scoreForRoutineTrip(oldRoutineTrip, scorePosts: &scorePosts, scoreMod: (NewRoutineTripScore * -1), location: nil) } if updatedRoutineTrip.routine != nil { scoreForRoutineTrip(updatedRoutineTrip, scorePosts: &scorePosts, scoreMod: NewRoutineTripScore, location: nil) } DataStore.sharedInstance.writeScorePosts(scorePosts) } /** * Change (or create) score for matching score post. */ static func changeScore( dayInWeek: Int, hourOfDay: Int, siteId: Int, isOrigin: Bool, scoreMod: Float, location: CLLocation?, inout scorePosts: [ScorePost]) { if !modifyScorePost( dayInWeek, hourOfDay: hourOfDay, siteId: siteId, isOrigin: isOrigin, location: location, allPosts: &scorePosts, scoreMod: scoreMod) { let newScorePost = ScorePost( dayInWeek: dayInWeek, hourOfDay: hourOfDay, siteId: siteId, score: scoreMod, isOrigin: isOrigin, location: location) print("Created new score post (Score: \(scoreMod)).") print(" - DW: \(dayInWeek), HD: \(hourOfDay), ID: \(siteId), isOri: \(isOrigin)") scorePosts.append(newScorePost) } } /** * Adds score for selected routine trip. */ static func addScoreForSelectedRoutineTrip(originId: Int, destinationId: Int) { var scorePosts = DataStore.sharedInstance.retrieveScorePosts() let currentLocation = MyLocationHelper.sharedInstance.currentLocation let dayOfWeek = DateUtils.getDayOfWeek() let hourOfDay = DateUtils.getHourOfDay() let originId = originId let destinationId = destinationId ScorePostHelper.changeScore(dayOfWeek, hourOfDay: hourOfDay, siteId: originId, isOrigin: true, scoreMod: 1, location: currentLocation, scorePosts: &scorePosts) ScorePostHelper.changeScore(dayOfWeek, hourOfDay: hourOfDay, siteId: destinationId, isOrigin: false, scoreMod: 2, location: currentLocation, scorePosts: &scorePosts) DataStore.sharedInstance.writeScorePosts(scorePosts) } //MARK: Private /** * Handles score for new routine trip. */ static private func scoreForRoutineTrip( routineTrip: RoutineTrip, inout scorePosts: [ScorePost], scoreMod: Float, location: CLLocation?) { for dayInWeek in createWeekRange(routineTrip.routine!.week) { for hourOfDay in createHourRange(routineTrip.routine!.time) { changeScore( dayInWeek, hourOfDay: hourOfDay, siteId: routineTrip.origin!.siteId, isOrigin: true, scoreMod: scoreMod, location: location, scorePosts: &scorePosts) changeScore( dayInWeek, hourOfDay: hourOfDay, siteId: routineTrip.destination!.siteId, isOrigin: false, scoreMod: scoreMod, location: location, scorePosts: &scorePosts) } // Add after midnight hours.. if routineTrip.routine!.time == .Night { for hourOfDay in 0...4 { changeScore( dayInWeek, hourOfDay: hourOfDay, siteId: routineTrip.origin!.siteId, isOrigin: true, scoreMod: scoreMod, location: location, scorePosts: &scorePosts) changeScore( dayInWeek, hourOfDay: hourOfDay, siteId: routineTrip.destination!.siteId, isOrigin: false, scoreMod: scoreMod, location: location, scorePosts: &scorePosts) } } } } /** * Creates a day-in-week integer range based on RoutineWeek. */ private static func createWeekRange(routineWeek: RoutineWeek) -> Range<Int> { if routineWeek == .WeekDays { return 1...5 } return 6...7 } /** * Creates a hour-of-day integer range based on RoutineWeek. */ private static func createHourRange(routineTime: RoutineTime) -> Range<Int> { switch routineTime { case .Morning: return 5...10 case .Day: return 11...17 case .Evening: return 18...21 case .Night: return 22...23 } } /** * Finds existing score post */ private static func modifyScorePost( dayInWeek: Int, hourOfDay: Int, siteId: Int, isOrigin: Bool, location: CLLocation?, inout allPosts: [ScorePost], scoreMod: Float) -> Bool { for post in allPosts { if post.dayInWeek == dayInWeek && post.hourOfDay == hourOfDay && post.siteId == siteId && post.isOrigin == isOrigin { print("Found post on id & time") if let location = location, postLocation = post.location { if location.distanceFromLocation(postLocation) < RequiredDistance { print("Found post within distance") post.score += scoreMod print("Modified score post (Score: \(post.score)).") return true } } } } return false } }
true
f4a3705b32515b53381d8ebaf9cba3a04ede4a8a
Swift
anfema/Tarpit
/src/tarfile.swift
UTF-8
6,830
2.9375
3
[ "BSD-3-Clause" ]
permissive
// // tarfile.swift // tarpit // // Created by Johannes Schriewer on 26/11/15. // Copyright © 2015 anfema. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the conditions of the 3-clause // BSD license (see LICENSE.txt for full license text) import Foundation open class TarFile { public enum Errors: Error { /// Invalid header encountered case headerParseError /// End of file marker found case endOfFile /// Programming error (called extractFile on streaming mode or consumeData on file mode) case programmingError } fileprivate struct TarFileHeader { var isFile: Bool var filepath: String var filesize: size_t var mtime: Date } fileprivate let streamingMode: Bool // MARK: - File based unpack fileprivate var data: Data! = nil fileprivate var offset: size_t = 0 /// Initialize for unpacking with data /// /// - parameter data: tar file data public init(data: Data) { self.streamingMode = false self.data = data } /// Initialize for unpacking with file name /// /// - parameter fileName: file name to open /// /// - throws: NSData contentsOfURL errors public convenience init(fileName: String) throws { self.init(data: try Data(contentsOf: URL(fileURLWithPath: fileName), options: .mappedIfSafe)) } /// Extract file from disk /// /// - throws: TarFile.Errors /// /// - returns: tuple with filename and data open func extractFile() throws -> (filename: String, mtime: Date, data: Data)? { if streamingMode { throw Errors.programmingError } var fileData : Data? var fileHeader : TarFileHeader? try self.data.withUnsafeBytes { rawBufferPointer -> Void in let dataPtr = rawBufferPointer.bindMemory(to: CChar.self).baseAddress! while true { guard self.offset + 512 < self.data.count else { throw Errors.endOfFile } // parse header info let header = try self.parse(header: dataPtr.advanced(by: self.offset)) var data: Data? = nil if header.filesize > 0 { // copy over data data = Data(bytes: dataPtr.advanced(by: self.offset + 512), count: header.filesize) } // advance offset (512 byte blocks) var size = 0 if header.filesize > 0 { if header.filesize % 512 == 0 { size = header.filesize } else { size = (header.filesize + (512 - header.filesize % 512)) } } self.offset += 512 + size if let data = data, header.isFile { // return file data fileData = data fileHeader = header break } } } guard let _fileData = fileData, let _fileHeader = fileHeader else { return nil } return (filename: _fileHeader.filepath, mtime: _fileHeader.mtime, data: _fileData) } // MARK: - Stream based unpack fileprivate var buffer = [CChar]() /// Initialize for unpacking from streaming data /// /// - parameter streamingData: initial data or nil public init(streamingData: [CChar]?) { self.streamingMode = true if let data = streamingData { self.buffer.append(contentsOf: data) } } /// Consume bytes from stream, return unpacked file /// /// - parameter data: data to consume /// /// - throws: TarFile.Errors /// /// - returns: tuple with filename and data on completion of a single file open func consume(data: [CChar]) throws -> (filename: String, data: Data)? { if !self.streamingMode { throw Errors.programmingError } self.buffer.append(contentsOf: data) let dataPtr = UnsafePointer<CChar>(self.buffer) if self.buffer.count > 512 { let header = try self.parse(header: dataPtr) let endOffset = 512 + (header.filesize + (512 - header.filesize % 512)) if self.buffer.count > endOffset { let data = Data(bytes: dataPtr.advanced(by: 512), count: header.filesize) self.buffer.removeFirst(endOffset) if header.isFile { return (filename: header.filepath, data:data) } } } return nil } // MARK: - Private fileprivate func parse(header: UnsafePointer<CChar>) throws -> TarFileHeader { var result = TarFileHeader(isFile: false, filepath: "", filesize: 0, mtime: Date(timeIntervalSince1970: 0)) let buffer = UnsafeBufferPointer<CChar>(start:header, count:512) // verify magic 257-262 guard buffer[257] == 117 && // u header[258] == 115 && // s header[259] == 116 && // t header[260] == 97 && // a header[261] == 114 && // r header[262] == 0 else { if header[0] == 0 { throw Errors.endOfFile } throw Errors.headerParseError } // verify checksum var checksum:UInt32 = 0 for index in 0..<512 { if index >= 148 && index < 148+8 { checksum += 32 } else { checksum += UInt32(header[index]) } } let headerChecksum:UInt32 = UInt32(strtol(header.advanced(by: 148), nil, 8)) if headerChecksum != checksum { throw Errors.headerParseError } // verify we're handling a file if header[156] == 0 || header[156] == 48 { result.isFile = true } // extract filename -> 0-99 guard let filename = String(cString: header, encoding: String.Encoding.utf8) else { return result } result.filepath = filename // extract file size let fileSize = strtol(header.advanced(by: 124), nil, 8) result.filesize = fileSize // extract modification time let mTime = strtol(header.advanced(by: 136), nil, 8) result.mtime = Date(timeIntervalSince1970: TimeInterval(mTime)) return result } }
true
4158718187afcd2cfbfabd1efe84414d64943ea1
Swift
adityadaniel/Basic-Swift-ADA
/Functions.playground/Contents.swift
UTF-8
462
3.59375
4
[]
no_license
import Foundation var numbers = [8,9,9,4,1,3,1,3,5,6] func printArrayOfNumber(array: [Int]) { for number in array { print(number) } } //printArrayOfNumber(array: numbers) for i in 0..<3 { print(i) } var myNumbers = 3 func exponentNumber(baseNumber: Int, power: Int) -> Int { var result = baseNumber for _ in 1..<power { result = result * baseNumber } return result } exponentNumber(baseNumber: 3, power: 3)
true
ec8e07f84ab2d53e35675d57d24aebcf6463603a
Swift
Abhishek9634/HorizontalPaginationDemo
/HorizontalPagination/ViewController.swift
UTF-8
3,140
3.03125
3
[ "MIT" ]
permissive
// // HorizontalPaginationViewController.swift // HorizontalPagination // // Created by Abhishek Thapliyal on 15/07/20. // Copyright © 2020 Abhishek Thapliyal. All rights reserved. // import UIKit public func delay(_ delay: Double, closure: @escaping () -> Void) { let deadline = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter( deadline: deadline, execute: closure ) } class HorizontalPaginationViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! var items = [1,2,3,4,5] private lazy var paginationManager: HorizontalPaginationManager = { let manager = HorizontalPaginationManager(scrollView: self.collectionView) manager.delegate = self return manager }() private var isDragging: Bool { return self.collectionView.isDragging } override func viewDidLoad() { super.viewDidLoad() self.setupCollectionView() self.setupPagination() self.fetchItems() } } extension HorizontalPaginationViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private func setupCollectionView() { self.collectionView.delegate = self self.collectionView.dataSource = self self.collectionView.alwaysBounceHorizontal = true } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "HorizontalCollectionCell", for: indexPath ) as! HorizontalCollectionCell cell.update(index: indexPath.row) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height) } } extension HorizontalPaginationViewController: HorizontalPaginationManagerDelegate { private func setupPagination() { self.paginationManager.refreshViewColor = .clear self.paginationManager.loaderColor = .white } private func fetchItems() { self.paginationManager.initialLoad() } func refreshAll(completion: @escaping (Bool) -> Void) { delay(2.0) { self.items = [1, 2, 3, 4, 5] self.collectionView.reloadData() completion(true) } } func loadMore(completion: @escaping (Bool) -> Void) { delay(2.0) { self.items.append(contentsOf: [6, 7, 8, 9, 10]) self.collectionView.reloadData() completion(true) } } }
true
36a8cd2cf85fad16df1c3faf2d46010cdf0fff57
Swift
CheckThisCodeCarefully/TransEasy
/Source/TransEasyAnimationController.swift
UTF-8
11,705
2.625
3
[ "MIT" ]
permissive
// // UIViewController+TransEasy.swift // TransEasy // // Created by Mohammad Porooshani on 7/21/16. // Copyright © 2016 Porooshani. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2016 Mohammad Poroushani // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit /// Handles animations reqired for the TransEasy Present. public class EasyPresentAnimationController: NSObject, UIViewControllerAnimatedTransitioning { /// The view animation would use as starting point. public var originalView: UIView? /// The view that originalView will land to. public var destinationView: UIView? /// The duration of animation. public var duration: NSTimeInterval = 0.4 /// The background's blur style. If nil, won't add blur effect. public var blurEffectStyle: UIBlurEffectStyle? public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // Check the integrity of context guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey), toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey), containerView = transitionContext.containerView(), originView = originalView, destView = destinationView else { print("Transition has not been setup!") return } print("Easy Present") // Prepares the presented view before moving on. toVC.view.frame = transitionContext.finalFrameForViewController(toVC) toVC.view.setNeedsDisplay() toVC.view.layoutIfNeeded() // Prepares required snapshots. let finalFrame = destView.frame let originalFrame = originView.frame let fromSnapshot = originView.snapshot() let toSnapshot = destView.snapshot() // Setup snapshot states before starting animations. fromSnapshot.alpha = 1.0 toSnapshot.alpha = 0.0 toVC.view.alpha = 0.0 fromSnapshot.frame = originalFrame toSnapshot.frame = originalFrame destView.hidden = true originView.hidden = true // Add blur style, in case a blur style has been set. if let blurStyle = blurEffectStyle { let fromWholeSnapshot = fromVC.view.snapshot() let effectView = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle)) effectView.frame = transitionContext.finalFrameForViewController(toVC) effectView.addSubview(fromWholeSnapshot) toVC.view.insertSubview(fromWholeSnapshot, atIndex: 0) toVC.view.insertSubview(effectView, aboveSubview: fromWholeSnapshot) } // Adds views to container view to start animations. containerView.addSubview(toVC.view) containerView.addSubview(fromSnapshot) containerView.addSubview(toSnapshot) let duration = transitionDuration(transitionContext) // Animations will be handled with keyframe animations. UIView.animateKeyframesWithDuration(duration, delay: 0, options: [.CalculationModeCubicPaced], animations: { // The move animation. UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: { fromSnapshot.frame = finalFrame toSnapshot.frame = finalFrame toVC.view.alpha = 1.0 }) // Fades source view to destination. UIView.addKeyframeWithRelativeStartTime(1/2, relativeDuration: 1/2, animations: { fromSnapshot.alpha = 0.0 toSnapshot.alpha = 1.0 }) }) { _ in // Wrap up final state of the transition. destView.layoutIfNeeded() destView.hidden = false originView.hidden = false fromSnapshot.removeFromSuperview() toSnapshot.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } } /// Handles animations reqired for the TransEasy Dismiss. public class EasyDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning { // The source view dimiss transition starts from. public var originalView: UIView? // The view that dimiss will land to. public var destinationView: UIView? // Transitions duration. public var duration: NSTimeInterval = 0.4 public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // Check the integrity of context guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey), toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey), containerView = transitionContext.containerView(), originView = originalView, destView = destinationView else { print("Transition has not been setup!") return } print("Easy Dismiss") // Prepare required info fro transitions. let finalFrame = destView.frame let originalFrame = originView.frame let fromSnapshot = originView.snapshotViewAfterScreenUpdates(false) let toSnapshot = destView.snapshot() // Setup initial state of the snapshots and other views. fromSnapshot.alpha = 1.0 toSnapshot.alpha = 0.0 fromVC.view.alpha = 1.0 toVC.view.alpha = 1.0 fromSnapshot.frame = originalFrame toSnapshot.frame = originalFrame originView.hidden = true destView.hidden = true let fromWholeSnapshot = fromVC.view.snapshot() // Add views to transition's container view. containerView.addSubview(toVC.view) containerView.addSubview(fromWholeSnapshot) containerView.addSubview(fromSnapshot) containerView.addSubview(toSnapshot) let duration = transitionDuration(transitionContext) // Transition's animation will be handled using keyframe. UIView.animateKeyframesWithDuration(duration, delay: 0, options: [.CalculationModeCubicPaced], animations: { // The move transition. UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: { fromSnapshot.frame = finalFrame toSnapshot.frame = finalFrame fromWholeSnapshot.alpha = 0.0 }) // Fade animation from source to destination view. UIView.addKeyframeWithRelativeStartTime(1/2, relativeDuration: 1/2, animations: { fromSnapshot.alpha = 0.0 toSnapshot.alpha = 1.0 }) }) { _ in // Wrap up final state of the transitions. destView.layoutIfNeeded() destView.hidden = false originView.hidden = false fromSnapshot.removeFromSuperview() toSnapshot.removeFromSuperview() fromWholeSnapshot.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } } public class EasyPopAnimationController: NSObject, UIViewControllerAnimatedTransitioning { // The source view dimiss transition starts from. public var originalView: UIView? // The view that dimiss will land to. public var destinationView: UIView? // Transitions duration. public var duration: NSTimeInterval = 0.4 public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // Check the integrity of context guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey), toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey), containerView = transitionContext.containerView(), originView = originalView, destView = destinationView else { print("Transition has not been setup!") return } print("Easy Pop") // Prepare required info fro transitions. let finalFrame = destView.frame let originalFrame = originView.frame let fromSnapshot = originView.snapshotViewAfterScreenUpdates(false) let toSnapshot = destView.snapshot() // Setup initial state of the snapshots and other views. fromSnapshot.alpha = 1.0 toSnapshot.alpha = 0.0 fromVC.view.alpha = 1.0 toVC.view.alpha = 1.0 fromSnapshot.frame = originalFrame toSnapshot.frame = originalFrame originView.hidden = true destView.hidden = true let fromWholeSnapshot = fromVC.view.snapshot() // Add views to transition's container view. toVC.view.frame = toVC.view.frame.offsetBy(dx: -(toVC.view.frame.width / 3.0), dy: 0) containerView.addSubview(toVC.view) containerView.addSubview(fromWholeSnapshot) containerView.addSubview(fromSnapshot) containerView.addSubview(toSnapshot) let duration = transitionDuration(transitionContext) // Transition's animation will be handled using keyframe. UIView.animateKeyframesWithDuration(duration, delay: 0, options: [.CalculationModeCubicPaced], animations: { // The move transition. UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: { fromSnapshot.frame = finalFrame toSnapshot.frame = finalFrame // fromWholeSnapshot.alpha = 0.0 fromWholeSnapshot.frame = fromWholeSnapshot.frame.offsetBy(dx: fromWholeSnapshot.frame.width, dy: 0) toVC.view.frame.origin.x = 0 }) // Fade animation from source to destination view. UIView.addKeyframeWithRelativeStartTime(1/2, relativeDuration: 1/2, animations: { fromSnapshot.alpha = 0.0 toSnapshot.alpha = 1.0 }) }) { _ in // Wrap up final state of the transitions. destView.layoutIfNeeded() destView.hidden = false originView.hidden = false fromSnapshot.removeFromSuperview() toSnapshot.removeFromSuperview() fromWholeSnapshot.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } } // A handy extension to allow snapshotting views. Because UIView's snapshot method messes up auto-layout. internal extension UIView { func snapshot() -> UIImageView { UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) layer.renderInContext(UIGraphicsGetCurrentContext()!) let img = UIGraphicsGetImageFromCurrentImageContext() return UIImageView(image: img) } }
true
43c8f8f92c681995df3813188b768d9eb599ff62
Swift
denisbohm/firefly-production-tools
/FireflyFirmwareCrypto/FireflyFirmwareCryptoFrameworkTests/FireflyFirmwareCryptoFrameworkTests.swift
UTF-8
3,988
2.65625
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
// // FireflyFirmwareCryptoFrameworkTests.swift // FireflyFirmwareCryptoFrameworkTests // // Created by Denis Bohm on 4/14/17. // Copyright © 2017 Firefly Design. All rights reserved. // import XCTest @testable import FireflyFirmwareCryptoFramework class FirmwareCryptoCommandTest: FirmwareCryptoCommand { var function: String? var firmwarePath: String? var encryptedFirmwarePath: String? var key: Data? var version: FirmwareCrypto.Version? var comment: String? open override func encrypt(firmwarePath: String, encryptedFirmwarePath: String, key: Data, version: FirmwareCrypto.Version, comment: String) throws { self.function = "encrypt" self.firmwarePath = firmwarePath self.encryptedFirmwarePath = encryptedFirmwarePath self.key = key self.version = version self.comment = comment } open override func decrypt(firmwarePath: String, encryptedFirmwarePath: String, key: Data) throws { self.function = "decrypt" self.firmwarePath = firmwarePath self.encryptedFirmwarePath = encryptedFirmwarePath self.key = key } } class FireflyFirmwareCryptoFrameworkTests: XCTestCase { func testCommandParseEncrypt() { let command = FirmwareCryptoCommandTest() let exitCode = command.main(arguments: ["FireflyFirmwareCrypto", "-firmware", "debug.hex", "-encrypted-firmware", "encrypted.bin", "-key", "000102030405060708090a0b0c0d0e0f", "-version", "1", "2", "3", "000102030405060708090a0b0c0d0e0f10111213", "-comment", "comment"]) XCTAssert(exitCode == 0) XCTAssert(command.function == "encrypt") XCTAssert(command.firmwarePath == "debug.hex") XCTAssert(command.encryptedFirmwarePath == "encrypted.bin") XCTAssert(command.key == Data(bytes: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f])) XCTAssert(command.version == FirmwareCrypto.Version(major: 1, minor: 2, revision: 3, commit: Data(bytes: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13]))) XCTAssert(command.comment == "comment") } func testCommandParseDecrypt() { let command = FirmwareCryptoCommandTest() let exitCode = command.main(arguments: ["FireflyFirmwareCrypto", "-firmware", "debug.hex", "-encrypted-firmware", "encrypted.bin", "-key", "000102030405060708090a0b0c0d0e0f", "-decrypt"]) XCTAssert(exitCode == 0) XCTAssert(command.function == "decrypt") XCTAssert(command.firmwarePath == "debug.hex") XCTAssert(command.encryptedFirmwarePath == "encrypted.bin") XCTAssert(command.key == Data(bytes: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f])) XCTAssert(command.version == nil) XCTAssert(command.comment == nil) } func testCryptDecrypt() throws { let address: UInt32 = 0x1 let data = Data(bytes: Array<UInt8>(repeating: 0x5a, count: 1)) let intelHex = IntelHex(data: data, address: address) let firmware = try IntelHexFormatter.format(intelHex: intelHex) let key = Data(bytes: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]) let version = FirmwareCrypto.Version(major: 1, minor: 2, revision: 3, commit: Data(bytes: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13])) let comment = "comment" let encryptedFirmware = try FirmwareCrypto.encrypt(firmware: firmware, key: key, version: version, comment: comment) let (firmware: decryptedData, metadata: metadata) = try FirmwareCrypto.decrypt(encryptedFirmware: encryptedFirmware, key: key) XCTAssert(metadata.version == version) XCTAssert(metadata.address == address) XCTAssert(metadata.comment == comment) XCTAssert(decryptedData == data) } }
true
6fc9a49fbac81dae52d87ff9f7b157592c38e64b
Swift
johndpope/sheets
/Sheets/AutocompleteUITextField.swift
UTF-8
4,010
2.78125
3
[]
no_license
// // AutocompleteUITextField.swift // AutocompleteUITextField // // Created by Keiwan Donyagard on 31.08.16. // Copyright © 2016 Keiwan Donyagard. All rights reserved. // import Foundation import UIKit protocol AutocompleteUITextFieldDelegate { func tableViewSelectedRow(_ entry: String) } class AutocompleteUITextField : UITextField, UITableViewDelegate, UITableViewDataSource { /** The TableView containing the autocomplete suggestions. */ @IBOutlet weak var suggestionsTableView : UITableView? /** The height of each TableView cell */ var tableViewRowHeight : CGFloat = 50 var autoCompDelegate: AutocompleteUITextFieldDelegate? /** The strings from which the suggestions are filtered. */ var autocompleteStrings : [String]? { didSet{ suggestionsTableView?.reloadData() } } var suggestions : [String]? { didSet{ suggestionsTableView?.reloadData() } } var testStrings = ["adfh","bfdj","fhdjg","gjsfk","gjsfk","gjsfk","gjsfk","gjsfk","gjsfk","gjsfk","gjsfk"] override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //initialize() } override func awakeFromNib() { super.awakeFromNib() initialize() } func initialize() { suggestions = [String]() setupTableView() self.addTarget(self, action: #selector(textDidChange(_:)), for: .editingChanged) } func setupTableView() { if let tableView = suggestionsTableView { setupTableView(tableView) } else { fatalError("The autocomplete UITableView is not set.") } } func setupTableView(_ tableView: UITableView){ tableView.rowHeight = tableViewRowHeight tableView.delegate = self tableView.dataSource = self suggestionsTableView?.isHidden = true } func findSuggestions(_ text: String) { // trim the string let text = text.trim() suggestions = [String]() let textLower = text.lowercased() if let allStrings = autocompleteStrings { for string in allStrings{ if string.lowercased().contains(textLower) { suggestions?.append(string) } } } } @objc func textDidChange(_ textField: UITextField){ suggestionsTableView?.delegate = self suggestionsTableView?.dataSource = self findSuggestions(textField.text!) suggestionsTableView?.reloadData() if textField.text == "" { suggestionsTableView?.isHidden = true } else { suggestionsTableView?.isHidden = false } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return number of table view cells if let count = suggestions?.count { return count } else { return 0 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Selected a cell let cell = suggestionsTableView?.cellForRow(at: indexPath) self.text = cell?.textLabel?.text suggestionsTableView?.isHidden = true suggestionsTableView?.reloadData() autoCompDelegate?.tableViewSelectedRow(text!) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() if let strings = suggestions { cell.textLabel?.text = strings[(indexPath as NSIndexPath).row] } else { cell.textLabel?.text = "" } return cell } }
true
c13e5003ad98d917d44301b1f0daf97e49472046
Swift
jpaaquino/SuperbWeather
/SuperbWeather/City/CityViewModel.swift
UTF-8
1,406
2.828125
3
[]
no_license
// // CityViewModel.swift // SuperbWeather // // Created by Joao Paulo Aquino on 16/07/20. // Copyright © 2020 Joao Paulo Aquino. All rights reserved. // import Foundation class CityViewModel { internal init(list: List, cityForecast: CityForecast? = nil) { self.list = list self.cityForecast = cityForecast } var cityForecast: CityForecast? var list: List func fetchDailyForecast(completion: @escaping (Bool) -> Void) { NetworkManager.fetchDailyForecast(lat: list.coord.lat, lon: list.coord.lon) { [weak self] (forecast) in guard let self = self, let forecast = forecast else {return} self.cityForecast = forecast completion(true) } } var dayViewModels: [DayViewModel] { guard let daily = cityForecast?.daily else {return []} return daily.map {DayViewModel(daily: $0)} } var temperature: String { let temp = Int(list.main.temp) return "\(temp)°" } var weatherDescription: String { return list.weather.first?.weatherDescription ?? "" } var name: String { return list.name } var cityId: Int { return list.id } var iconURL: URL? { guard let iconId = list.weather.first?.icon else {return nil} return URL(string: "http://openweathermap.org/img/w/\(iconId).png") } }
true
c151e1823a822cb7f60906f2ea530a85445702e8
Swift
FredrikSjoberg/Topology
/Topology/Protocols/Corner.swift
UTF-8
578
2.59375
3
[]
no_license
// // Corner.swift // Topology // // Created by Fredrik Sjöberg on 30/11/16. // Copyright © 2016 KnightsFee. All rights reserved. // import Foundation public protocol CornerType: Hashable { associatedtype Adjacent: Hashable associatedtype Downslope associatedtype Center: Hashable associatedtype Lake var elevation: Float { get } var downslope: Downslope { get } var adjacent: Set<Adjacent> { get } var touches: Set<Center> { get } var lake: Lake? { get } var isOcean: Bool { get } var isBorder: Bool { get } }
true
bcfffa0cc0dfef5c88c06dc0e60da00fb7441220
Swift
Albinzr/CoreApp
/DemoApp-iOS/StoryDetailContainerController.swift
UTF-8
3,582
2.5625
3
[]
no_license
// // StoryDetailsContainerController.swift // DemoApp-iOS // // Created by Albin CR on 1/19/17. // Copyright © 2017 Albin CR. All rights reserved. // import UIKit //import Quintype class StoryDetailContainerController:BaseController{ var slugCollection:[String]? var currentPage:Int? // var storyDataStorage:[Int:Story] = [:] convenience init(slugArray: [String], currentSlugPosition: Int) { self.init() self.slugCollection = slugArray self.currentPage = currentSlugPosition } var pageViewController:UIPageViewController = { let pageViewController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal, options: nil) return pageViewController }() override func viewDidLoad() { super.viewDidLoad() pageViewController.isDoubleSided = true pageViewController.dataSource = self pageViewController.delegate = self let startingViewController = self.loadViewControllerAtIndex(index: currentPage!) as! StoryDetailPager let viewControllers = [startingViewController] pageViewController.setViewControllers(viewControllers, direction:UIPageViewControllerNavigationDirection.forward, animated:false, completion:nil) pageViewController.view.frame = self.view.frame self.addChildViewController(pageViewController) self.view.addSubview(pageViewController.view) pageViewController.didMove(toParentViewController: self) self.edgesForExtendedLayout = [] self.navigationController?.hidesBarsOnSwipe = false } } extension StoryDetailContainerController:UIPageViewControllerDataSource,UIPageViewControllerDelegate{ func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let vc = viewController as? StoryDetailPager var index = vc?.pageIndex if (index == NSNotFound ){ return nil } index = index! + 1 if (index == self.slugCollection?.count){ return nil } return loadViewControllerAtIndex(index: index!) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let vc = viewController as? StoryDetailPager var index = vc?.pageIndex if (index == 0 || index == NSNotFound){ return nil } index = index! - 1 return loadViewControllerAtIndex(index: index!) } func loadViewControllerAtIndex(index: Int) -> UIViewController{ let newController = StoryDetailPager(slug: (slugCollection?[index])!, Index: index) return newController } // func loadAndStoreStories(index:Int){ // // //// Quintype.api.getStoryFromSlug(slug: currentSlug!, cache: cacheOption.none, Success: { (story) in //// //// //// print(story!) //// //// }) { (error) in //// //// print(error!) //// //// } // // // } }
true
e498c2896e388d5b97b1ed4ef3bbf84878a2e875
Swift
janFrancoo/Swift-Tutorials-Projects
/CoordinatorPattern/Coordinators/TopRatedDetailCoordinator.swift
UTF-8
839
2.90625
3
[]
no_license
// // TopRatedDetailCoordinator.swift // CoordinatorPatternExample // // Created by JanFranco on 9.12.2020. // import UIKit protocol TopRatedDetailFlow { func dismissDetail() } class TopRatedDetailCoordinator: Coordinator, TopRatedDetailFlow { let navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController } func start() { let topRatedDetailViewController = TopRatedDetailViewController() topRatedDetailViewController.coordinator = self navigationController.present(topRatedDetailViewController, animated: true, completion: nil) } // MARK: - Flow Methods func dismissDetail() { navigationController.dismiss(animated: true, completion: nil) } }
true
29b54abba9e435da57343bbd65f216085d463e95
Swift
RobinAnja/LottoAppIOS
/iOSLottoApp/TicketDurationView.swift
UTF-8
4,726
2.5625
3
[]
no_license
// // TicketDurationView.swift // iOSLottoApp // // Created by Robin Fischer on 02.08.19. // Copyright © 2019 Robin Fischer. All rights reserved. // import SwiftUI struct TicketDurationView: View { @EnvironmentObject var lottoTicket: LottoTicket var body: some View { VStack { Text("WOCHENLAUFZEIT").fontWeight(.bold).foregroundColor(Color("text")).padding(.top, 10).frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) HStack(spacing: 8) { Button(action: { self.lottoTicket.duration = 1 }, label: { Text("1") .padding(.horizontal, 23) .padding(.vertical, 8)}) .foregroundColor(self.lottoTicket.duration == 1 ? Color.white : Color("red")) .background(self.lottoTicket.duration == 1 ? Color("red") : Color.white) .cornerRadius(10) .border(Color("red"), width: 1, cornerRadius: 10) Button(action: { self.lottoTicket.duration = 2 }, label: { Text("2") .padding(.horizontal, 23) .padding(.vertical, 8)}) .foregroundColor(self.lottoTicket.duration == 2 ? Color.white : Color("red")) .background(self.lottoTicket.duration == 2 ? Color("red"): Color.white) .cornerRadius(10) .border(Color("red"), width: 1, cornerRadius: 10) Button(action: { self.lottoTicket.duration = 3 }, label: { Text("3") .padding(.horizontal, 23) .padding(.vertical, 8)}) .foregroundColor(self.lottoTicket.duration == 3 ? Color.white : Color("red")) .background(self.lottoTicket.duration == 3 ? Color("red") : Color.white) .cornerRadius(10) .border(Color("red"), width: 1, cornerRadius: 10) Button(action: { self.lottoTicket.duration = 4 }, label: { Text("4") .padding(.horizontal, 23) .padding(.vertical, 8)}) .foregroundColor(self.lottoTicket.duration == 4 ? Color.white : Color("red")) .background(self.lottoTicket.duration == 4 ? Color("red") : Color.white) .cornerRadius(10) .border(Color("red"), width: 1, cornerRadius: 10) Button(action: { self.lottoTicket.duration = 5 }, label: { Text("5") .padding(.horizontal, 23) .padding(.vertical, 8)}) .foregroundColor(self.lottoTicket.duration == 5 ? Color.white : Color("red")) .background(self.lottoTicket.duration == 5 ? Color("red") : Color.white) .cornerRadius(10) .border(Color("red"), width: 1, cornerRadius: 10) Button(action: { self.lottoTicket.duration = 8 }, label: { Text("8") .padding(.horizontal, 23) .padding(.vertical, 8)}) .foregroundColor(self.lottoTicket.duration == 8 ? Color.white : Color("red")) .background(self.lottoTicket.duration == 8 ? Color("red") : Color.white) .cornerRadius(10) .border(Color("red"), width: 1, cornerRadius: 10) } } } } #if DEBUG var ticketDurationViewLottoTicket = LottoTicket() struct TicketDurationView_Previews: PreviewProvider { static var previews: some View { TicketDurationView().environmentObject(ticketDurationViewLottoTicket) } } #endif
true
a86d03d170530604c4761e71d8cba8b4358448b2
Swift
mf3129/DailyTask
/DailyTask/Controllers/CategoryViewController.swift
UTF-8
3,954
2.796875
3
[]
no_license
// // CategoryViewController.swift // DailyTask // // Created by Makan Fofana on 10/23/18. // Copyright © 2018 Makan Fofana. All rights reserved. // import UIKit // import CoreData import RealmSwift import ChameleonFramework class CategoryViewController: SwipeTableViewController { let realm = try! Realm() var itemArrays: Results<Category>? override func viewDidLoad() { super.viewDidLoad() loadCategory() tableView.separatorStyle = .none } //MARK: TableView Datasource Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemArrays?.count ?? 1 // NIL COALESCING OPERATOR } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) if let category = itemArrays?[indexPath.row] { cell.textLabel?.text = category.name cell.backgroundColor = UIColor(hexString: category.Color ) } return cell } //ADDING NEW ITEMS TO THE LIST @IBAction func addBarButtonItem(_ sender: UIBarButtonItem) { var textField = UITextField() let alertMessage = UIAlertController(title: "Add Categories", message: "", preferredStyle: .alert) let action = UIAlertAction(title: "Add Categories", style: .default) { (action) in let newItem = Category() newItem.name = textField.text! newItem.Color = UIColor.randomFlat.hexValue() self.save(category: newItem) } alertMessage.addTextField { (alertTextField) in textField = alertTextField alertTextField.placeholder = "Add Category To List" } alertMessage.addAction(action) present(alertMessage, animated: true, completion: nil) } //MARK: TableView Delegate Methods override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "goToItems", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destinationVC = segue.destination as! DailyTaskController if let indexPath = tableView.indexPathForSelectedRow { destinationVC.selectedCategory = itemArrays?[indexPath.row] } } //MARK: Data Manipulation Methods func save(category: Category) { do { try realm.write { realm.add(category) } } catch { print("Error saving category \(error)") } self.tableView.reloadData() } func loadCategory() { itemArrays = realm.objects(Category.self) tableView.reloadData() // let request: NSFetchRequest<Categories> = Categories.fetchRequest() ORIGINAL FOR CORE DATA // do { // itemArrays = try context.fetch(request) // } catch { // print("Error catching data from context \(error)") // } } //MARK: Delete Data From Swipe override func updateModel(at indexPath: IndexPath) { //Update our data model if let categoryDeleted = self.itemArrays?[indexPath.row] { do { try! self.realm.write { self.realm.delete(categoryDeleted) // tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } } catch { print("Error deleting the category, \(error)") } } } }
true
8d621210deea35a4ffa2bef3d1cebc74d6161bbe
Swift
tonyguan/SwiftBook2
/ch7/7.3.1break语句1.playground/section-1.swift
UTF-8
473
3.1875
3
[]
no_license
// // Created by 关东升 on 2017-1-18. // 本书网站:http://www.51work6.com // 智捷课堂在线课堂:http://www.zhijieketang.com/ // 智捷课堂微信公共号:zhijieketang // 作者微博:@tony_关东升 // 作者微信:tony关东升 // QQ:569418560 邮箱:eorient@sina.com // QQ交流群:162030268 // let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in 0 ..< numbers.count { if i == 3 { break } print("Count is: \(i)") }
true
7d56b45d6e35ef80e64fb284e7dcef0f8a8e638c
Swift
LBkos/RPS
/RPS/ViewController.swift
UTF-8
2,381
3.046875
3
[]
no_license
// // ViewController.swift // RPS // // Created by Константин Лопаткин on 19/09/2019. // Copyright © 2019 Konstantin Lopatkin. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var robotButton: UILabel! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var rockButton: UIButton! @IBOutlet weak var paperButton: UIButton! @IBOutlet weak var scissersButton: UIButton! @IBOutlet weak var playAgainButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. playAgainButton.isHidden = true } func play (_ sign: Sign){ let computerSign = randomSign() robotButton.text = computerSign.emoji switch sign { case .rock: rockButton.isHidden = false scissersButton.isHidden = true paperButton.isHidden = true case .paper: rockButton.isHidden = true paperButton.isHidden = false scissersButton.isHidden = true case .scissors: scissersButton.isHidden = false paperButton.isHidden = true rockButton.isHidden = true } playAgainButton.isHidden = false let result = sign.getResult(for: computerSign) switch result { case .win: statusLabel.text = "You win!" self.view.backgroundColor = UIColor.green case .draw: statusLabel.text = "Draw!" self.view.backgroundColor = UIColor.gray case .lose: statusLabel.text = "You lose!" self.view.backgroundColor = UIColor.red case .start: reset() } } func reset() { statusLabel.text = "Rock, paper, scissors?" view.backgroundColor = UIColor.white rockButton.isHidden = false scissersButton.isHidden = false paperButton.isHidden = false playAgainButton.isHidden = true } @IBAction func rockPressed(_ sender: Any) { play(.rock) } @IBAction func paperPressed(_ sender: Any) { play(.paper) } @IBAction func scissorsPressed(_ sender: Any) { play(.scissors) } @IBAction func resetPressed(_ sender: Any) { reset() } }
true
68f8ec9fefdc45771af1ca3e12216787d1117ce3
Swift
Cerf88/BudgetChecker
/ContentView.swift
UTF-8
2,690
2.8125
3
[]
no_license
// // ContentView.swift // BudgetChecker // // Created by Anna Bunchuzhna on 15.02.2021. // import SwiftUI struct ContentView: View { init() { UITabBar.appearance().barTintColor = UIColor(named: "mainBlue") UINavigationBar.appearance().barTintColor = UIColor(named: "mainBlue") } @State private var selection = 0 var body: some View { TabView(selection: $selection) { PersonalTransactionsView() .tabItem { Image(systemName: selection == 0 ? "person.fill": "person").renderingMode(.template) Text("Personal") } .tag(0) FamilyTransactionsView() .tabItem { Image(systemName: selection == 1 ? "person.3.fill": "person.3") Text("Family") } .tag(1) } .accentColor(Color("mainDarkBlue")) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environmentObject(TransactionList.shared) } } struct TransactionCell: View { let transaction: Transaction func getDateString(date:Date) -> String{ let formatter = DateFormatter() formatter.dateStyle = .medium let dateString = formatter.string(from: date) return dateString } var body: some View { HStack (alignment: .top){ VStack(alignment: .leading) { Text(transaction.details) .foregroundColor(Color("mainBlack")) .padding(.leading, 10) .font(.headline) Text(transaction.category) .foregroundColor(Color("mainBlack")) .padding(.leading, 15) .font(.footnote) } Spacer() VStack(alignment: .trailing) { Text (String (format: "%.2f UAH", Double(transaction.amount)/100)) .fontWeight(.heavy) .foregroundColor(Color("mainBlack")) .multilineTextAlignment(.trailing) .padding(.trailing, 10) .font(.body) Text (getDateString(date: transaction.date)) .foregroundColor(Color("mainBlack")) .multilineTextAlignment(.trailing) .padding(.trailing, 10) .font(.subheadline) } } } }
true
28c0f9332962aef206af5c585c6fb46d683bf98e
Swift
renesugar/SwiftKotlin
/Assets/Tests/KotlinTokenizer/statics.swift
UTF-8
581
2.78125
3
[ "MIT" ]
permissive
class A { public static var myBool = true } class A { static private var myBool = true static public var myNum = 3 static var myString = "string" } class A { static func method() {} } class A { static func method() {} static func create() -> A? { return nil } static func withParams(param: Int) -> A? { return nil } } class A { var name = "string" static var myBool = true static func method() {} func test() {} } struct A { var name = "string" static var myBool = true static func method() {} func test() {} }
true
cd539d58007fa5c7b7e6bfe1b72abb32a7ccde5f
Swift
ivaanteo/Vibe
/Vibe/View/ShopCollectionViewCell.swift
UTF-8
5,079
2.515625
3
[]
no_license
// // ShopCollectionViewCell.swift // Vibe // // Created by Ivan Teo on 23/6/21. // import UIKit class ShopCollectionViewCell: UICollectionViewCell{ // View Components var purchaseButton: PurchaseButton! private var nameLabel: UILabel! private var waveImageView: UIImageView! // View Dimensions private let margin: CGFloat = 20 private lazy var buttonWidth: CGFloat = { return contentView.frame.width * 0.25 }() private var buttonHeight:CGFloat = 35 // Bool var vibrationOwned = false var vibrationIsSelected: Bool?{ didSet{ if vibrationIsSelected!{ DispatchQueue.main.async { // darken because is selected self.purchaseButton.isHidden = true self.backgroundColor = .init(white: 0.1, alpha: 0.4) } }else{ DispatchQueue.main.async { // reset to normal colour for reuse cell self.purchaseButton.isHidden = false self.backgroundColor = .init(white: 0.35, alpha: 0.5) } } } } // View Model var backgroundVibration: BackgroundVibrationViewModel?{ didSet{ vibrationOwned = BackgroundVibrationManager.shared.vibrationsOwned.contains(backgroundVibration!.id) if vibrationOwned{ purchaseButton.setTitle("Select", for: .normal) } else{ // }else if backgroundVibration?.id != BackgroundVibrationManager.shared.getBackgroundChoice(){ purchaseButton.setTitle("$\(backgroundVibration!.price)", for: .normal) } nameLabel.text = backgroundVibration?.title waveImageView.image = backgroundVibration?.img } } // Button Actions // Layout Views override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupViews(){ setupBackground() setupImageView() setupNameLabel() setupPurchaseButton() } func setupBackground(){ backgroundColor = .init(white: 0.35, alpha: 0.5) layer.cornerRadius = contentView.frame.height / 4 layer.shadowOffset = CGSize(width: 4, height: 8) layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale layer.shadowColor = UIColor.black.cgColor layer.shadowRadius = 3.5 layer.shadowOpacity = 0.5 layer.masksToBounds = false } func setupPurchaseButton(){ purchaseButton = PurchaseButton() purchaseButton.backgroundColor = .clear purchaseButton.layer.cornerRadius = buttonHeight/2 purchaseButton.titleLabel?.font = UIFont(name: "Futura", size: 16) contentView.addSubview(purchaseButton) setupPurchaseButtonConstraints() } func setupPurchaseButtonConstraints(){ purchaseButton.translatesAutoresizingMaskIntoConstraints = false purchaseButton.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true purchaseButton.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true purchaseButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true purchaseButton.leadingAnchor.constraint(equalTo: nameLabel.trailingAnchor, constant: margin).isActive = true purchaseButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -margin).isActive = true } func setupNameLabel(){ nameLabel = UILabel() nameLabel.numberOfLines = 2 nameLabel.textColor = . white nameLabel.font = UIFont(name: "Futura", size: 16) contentView.addSubview(nameLabel) setupNameLabelConstraints() } func setupNameLabelConstraints(){ nameLabel.translatesAutoresizingMaskIntoConstraints = false nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true nameLabel.leadingAnchor.constraint(equalTo: waveImageView.trailingAnchor, constant: margin).isActive = true } func setupImageView(){ waveImageView = UIImageView() waveImageView.tintColor = UIColor(named: "orange") contentView.addSubview(waveImageView) setupImageViewConstraints() } func setupImageViewConstraints(){ waveImageView.translatesAutoresizingMaskIntoConstraints = false waveImageView.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true waveImageView.widthAnchor.constraint(equalToConstant: buttonHeight).isActive = true waveImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true waveImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: margin).isActive = true } }
true
0d7d8d3223f940ec275a285d9a7cf4f0bb14fa89
Swift
ihusnainalii/my-swift-journey
/SwiftUI-SinglePass/SinglePass/Views/SharedTextField.swift
UTF-8
1,605
3
3
[ "MIT" ]
permissive
// // SharedTextField.swift // SinglePass // // Created by Juan Francisco Dorado Torres on 28/10/20. // import SwiftUI struct SharedTextField: View { @Binding var value: String var header = "Username" var placeholder = "Your username or email" var trailingIconName = "" var errorMessage = "" var showUnderline = true var onEditingChanged: ((Bool) -> Void) = { _ in } var onCommit: (() -> Void) = {} var body: some View { VStack(alignment: .leading, spacing: 0) { Text(header.uppercased()) .font(.footnote) .foregroundColor(Color.gray) HStack { TextField( placeholder, text: self.$value, onEditingChanged: { flag in self.onEditingChanged(flag) }, onCommit: { self.onCommit() } ) .padding(.vertical, 15) if !self.trailingIconName.isEmpty { Image(systemName: self.trailingIconName) .foregroundColor(Color.gray) } } .frame(height: 45) if showUnderline { Rectangle() .frame(height: 1) .foregroundColor(Color.gray) } if !errorMessage.isEmpty { Text(errorMessage) .lineLimit(nil) .font(.footnote) .foregroundColor(Color.red) .transition( AnyTransition .opacity .animation(.easeIn) ) } } .background(Color.background) } } struct SharedTextField_Previews: PreviewProvider { static var previews: some View { SharedTextField(value: .constant("")) } }
true
116248b696ccdc6bdeddc7db99713e33db0340f7
Swift
aoenth/disciplines
/Disciplines/AxisView.swift
UTF-8
1,617
2.765625
3
[]
no_license
// // AxisView.swift // Disciplines // // Created by Kevin Peng on 2020-04-23. // Copyright © 2020 Monorail Apps. All rights reserved. // import UIKit @IBDesignable class AxisView: UIView { override func layoutSubviews() { super.layoutSubviews() backgroundColor = .clear } private let lineColor = UIColor(hex: 0x979797) override func draw(_ rect: CGRect) { let marginX: CGFloat = 0 let marginY: CGFloat = 0 let originX: CGFloat = marginX let originY = rect.height - marginY let endX = rect.width let endY = originY lineColor.setStroke() let path = UIBezierPath() path.lineWidth = 1 drawLine(path: path, originX: originX, endX: endX, endY: endY, percentage: 0) drawLine(path: path, originX: originX, endX: endX, endY: endY, percentage: 1) path.stroke() let subdividers = UIBezierPath() subdividers.lineWidth = 0.5 drawLine(path: subdividers, originX: originX, endX: endX, endY: endY, percentage: 0.25) drawLine(path: subdividers, originX: originX, endX: endX, endY: endY, percentage: 0.50) drawLine(path: subdividers, originX: originX, endX: endX, endY: endY, percentage: 0.75) subdividers.stroke() } func drawLine(path: UIBezierPath, originX: CGFloat, endX: CGFloat, endY: CGFloat, percentage: CGFloat) { let lineHeight = endY * (1 - percentage) assert(lineHeight >= 0 && lineHeight <= endY, "percentage must be 0 <= percentage <= 1") let lineStart = CGPoint(x: originX, y: lineHeight) let lineEnd = CGPoint(x: endX, y: lineHeight) path.move(to: lineStart) path.addLine(to: lineEnd) } }
true
e2c40e7bfb6d82ca3c458ba17f6e8c8f024d6404
Swift
gaoxiangyu369/Photo_Application_Like_Instagram
/MyInstagram/Model/Post.swift
UTF-8
1,038
3.078125
3
[]
no_license
// // Post.swift // MyInstagram // // Created by Jocelyn Jiang on 01/10/2018. // Copyright © 2018 Jocelyn Jiang. All rights reserved. // import Foundation import FirebaseAuth class Post { var id: String? var photoUrl: String? var description: String? var userId: String? var likeCount: Int? var likes: Dictionary<String,Any>? var isLiked: Bool? } extension Post { static func formatPost(dict:[String:Any],key:String) -> Post { let post = Post() post.id = key post.description = dict["desc"] as? String post.photoUrl = dict["photoUrl"] as? String post.userId = dict["userId"] as? String post.likeCount = dict["likeCount"] as? Int post.likes = dict["likes"] as? Dictionary<String, Any> if let currentUserId = Auth.auth().currentUser?.uid { if post.likes != nil { post.isLiked = post.likes![currentUserId] != nil }else { post.isLiked = false } } return post } }
true
ac96210d3f136337b1853f777ebb9444abc1545d
Swift
KoshiroYokono/PrivateYoutube
/TinderApp/extension/String+extension.swift
UTF-8
572
3
3
[]
no_license
// // String+extension.swift // TinderApp // // Created by 横野公至郎 on 2019/11/16. // Copyright © 2019 横野公至郎. All rights reserved. // import Foundation extension String { func urlEncode() -> String { return addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! } func toDate() -> Date { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" formatter.locale = .current let date = formatter.date(from: self)! return date } }
true
a37a021e9c5d154f551855bf6a0908b7cfed14b7
Swift
ramirezi29/Journal-CloudKit-iOS22-Afternoon
/JournalCloudKitiOS22-AfternoonProject/Model/EntryModel.swift
UTF-8
2,174
3
3
[]
no_license
// // EntryModel.swift // JournalCloudKitiOS22-AfternoonProject // // Created by Ivan Ramirez on 11/5/18. // Copyright © 2018 ramcomw. All rights reserved. // import Foundation import CloudKit class Entry { var title: String var textBody: String? var timestamp: Date let ckRecordID: CKRecord.ID init(title: String, textBody: String, ckRecordID: CKRecord.ID = CKRecord.ID(recordName: UUID().uuidString)) { self.title = title self.timestamp = Date() self.textBody = textBody self.ckRecordID = ckRecordID } var timeStampAsString: String { return DateFormatter.localizedString(from: timestamp, dateStyle: .short, timeStyle: .none) } // NOTE: - Create a model object fromR a CKRecord -- 🔥Fetch convenience init?(ckRecord: CKRecord) { //🍕 Step 1. Unpack the values that i want from the CKREcord guard let title = ckRecord[Constants.titleKey] as? String, let textBody = ckRecord[Constants.textBodyKey] as? String else {return nil} //🍕 Step 2. Set tthose values as my initial values for my new instance self.init(title: title, textBody: textBody, ckRecordID: ckRecord.recordID) } } // NOTE: - Create a CKRecord using our model object -- 🔥Push extension CKRecord { convenience init(enty: Entry) { self.init(recordType: Constants.EntryTypeKey, recordID: enty.ckRecordID) self.setValue(enty.title, forKey: Constants.titleKey) self.setValue(enty.textBody, forKey: Constants.textBodyKey) self.setValue(enty.timestamp, forKey: Constants.timestampKey) } } struct Constants { static let EntryTypeKey = "Entry" static let titleKey = "title" static let textBodyKey = "textBody" static let timestampKey = "timestamp" } extension Entry: Equatable { static func == (lhs: Entry, rhs: Entry) -> Bool { if lhs.title != rhs.title {return false} if lhs.textBody != rhs.textBody {return false} if lhs.timestamp != rhs.timestamp {return false} if lhs.ckRecordID != rhs.ckRecordID {return false} return true } }
true
17fe3a64612a6eb3fa8951bc5facaf0e372e3c45
Swift
phillfarrugia/sf-study
/BinaryTreeInorderPostorderTraversal.playground/Contents.swift
UTF-8
2,139
3.84375
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } // inorder = [9,3,15,20,7] // postorder = [9,15,7,20,3] // [15,20,7] // [15,7,20] // [15] // [15] class Solution { func buildTree(_ inorder: [Int], _ postorder: [Int]) -> TreeNode? { let inStart = 0 let inEnd = inorder.count - 1 let postStart = 0 let postEnd = postorder.count - 1 return buildTree(inorder: inorder, postorder: postorder, inStart: inStart, inEnd: inEnd, postStart: postStart, postEnd: postEnd) } func buildTree(inorder: [Int], postorder: [Int], inStart: Int, inEnd: Int, postStart: Int, postEnd: Int) -> TreeNode? { if inStart > inEnd || postStart > postEnd { return nil } let rootValue = postorder[postEnd] let node = TreeNode(rootValue) var k = 0 for index in 0..<inorder.count { if (inorder[index] == rootValue) { k = index break } } node.left = buildTree(inorder: inorder, postorder: postorder, inStart: inStart, inEnd: k - 1, postStart: postStart, postEnd: postStart + k - (inStart + 1)) node.right = buildTree(inorder: inorder, postorder: postorder, inStart: k + 1, inEnd: inEnd, postStart: postStart + k - inStart, postEnd: postEnd - 1) return node } } //Solution().buildTree([9,3,15,20,7], [9,15,7,20,3]) Solution().buildTree([15, 2], [15, 2])
true
fa6ae5568c493bb8eee3bb19e4fccedb2c5b623d
Swift
jasonjsnell/XvGui
/Textures/Textures.swift
UTF-8
2,995
3.046875
3
[]
no_license
// // Textures.swift // XvGui // // Created by Jason Snell on 2/13/19. // Copyright © 2019 Jason Snell. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif import QuartzCore public class Textures{ //MARK: - CLASS FUNCS - //convenience, full screen, black lines public class func createScanLines( lineHeight:CGFloat, spaceHeight:CGFloat) -> UIView { return createScanLines(x: 0.0, y: 0.0, width: Screen.width, height: Screen.height, color: .black, lineHeight: lineHeight, spaceHeight: spaceHeight) } public class func createScanLines( x:CGFloat, y:CGFloat, width:CGFloat, height:CGFloat, color:UIColor, lineHeight:CGFloat, spaceHeight:CGFloat) -> UIView { //make frame let frame:CGRect = CGRect(x: x, y: y, width: width, height: height) //init view let scanLinesView:ScanLinesView = ScanLinesView(frame: frame) scanLinesView.backgroundColor = UIColor.clear //update vars scanLinesView.color = color scanLinesView.lineHeight = lineHeight scanLinesView.spaceHeight = spaceHeight //refresh display scanLinesView.setNeedsDisplay() //return view return scanLinesView } } //MARK: - VIEWS - class ScanLinesView:UIView { //required override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //set vars public var color:UIColor = .black public var lineHeight:CGFloat = 1.0 public var spaceHeight:CGFloat = 1.0 override func draw(_ rect: CGRect) { //get context if let context:CGContext = UIGraphicsGetCurrentContext() { //color of each rect context.setFillColor(color.cgColor) //build var that will update for each line var buildY:CGFloat = 0.0 //loop until whole frame is full while buildY <= frame.height { //make the rect let rect:CGRect = CGRect( x: 0.0, y: buildY, width: frame.width, height: lineHeight ) // add rect using a fill (rather than stroke) context.addRect(rect) context.drawPath(using: .fill) //y loc of next line buildY += lineHeight + spaceHeight } } else { print("XvGui: Textures: ScanLinesView: Error getting CGContext") } } }
true
251eea98f74d469fd567e3e8b2c91ded75db610e
Swift
aarsla/super.ba-ios
/super/Source.swift
UTF-8
624
2.53125
3
[]
no_license
// // Source.swift // super // // Created by Aid Arslanagic on 05/07/2017. // Copyright © 2017 Simpastudio. All rights reserved. // import Foundation import ObjectMapper class SourcesResponse: Mappable { var sources: [Source]? required init?(map: Map){ } func mapping(map: Map) { sources <- map["sources"] } } class Source: Mappable { var title: String? var url: String? var logo: String? required init?(map: Map){ } func mapping(map: Map) { title <- map["title"] url <- map["url"] logo <- map["logo"] } }
true
9170c9673f66b16ababa1349cfdc0f93ceeae838
Swift
jarukorn/Trax
/Senior Project I/ViewController.swift
UTF-8
1,951
2.6875
3
[]
no_license
// // ViewController.swift // Senior Project I // // Created by Jarukorn Thuengjitvilas on 18/3/2561 BE. // Copyright © 2561 Jarukorn Thuengjitvilas. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var mainPieChart: UIView! let chart = VBPieChart() override func viewDidLoad() { super.viewDidLoad() initMainGraph() } func initMainGraph() { mainPieChart.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) self.mainPieChart.addSubview(chart) chart.frame = CGRect(x: 50 , y: 0, width: view.frame.width-100, height: 300) chart.holeRadiusPrecent = 0 chart.centerXAnchor.constraint(equalTo: view.centerXAnchor) chart.centerYAnchor.constraint(equalTo: view.centerYAnchor) chart.widthAnchor.constraint(equalToConstant: 200) chart.heightAnchor.constraint(equalToConstant: 150) let chartValues = [ ["name":"first", "value": 50, "color":UIColor(hexString:"dd191daa")], ["name":"second", "value": 20, "color":UIColor(hexString:"d81b60aa")], ["name":"third", "value": 40, "color":UIColor(hexString:"8e24aaaa")], ["name":"fourth 2", "value": 70, "color":UIColor(hexString:"3f51b5aa")], ["name":"fourth 3", "value": 65, "color":UIColor(hexString:"5677fcaa")], ["name":"fourth 4", "value": 23, "color":UIColor(hexString:"2baf2baa")], ["name":"fourth 5", "value": 34, "color":UIColor(hexString:"b0bec5aa")], ["name":"fourth 6", "value": 54, "color":UIColor(hexString:"f57c00aa")] ] chart.setChartValues(chartValues as [AnyObject], animation:true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
true
32a1ab151a063ca12b93e33b944cb7e47eeae49d
Swift
devlloyd/intro_classes
/classes_testing/vehicle.swift
UTF-8
844
3.578125
4
[]
no_license
// // vehicle.swift // classes_testing // // Created by Devon Lloyd on 4/20/17. // Copyright © 2017 Devon Lloyd. All rights reserved. // import Foundation class Vehicle { private var engine = "4 cylinder" private var color = "Silver" private var _odometer = 500 //Getter / Setter (Accessors & Mutators) var odometer: Int { get { return _odometer } set { if newValue > _odometer { _odometer = newValue } //else { // _odometer = odometer //why does this work without the else statement? //} } } init(engine: String, color: String) { self.engine = engine self.color = color } init() { } func enterMiles(miles: Int) { odometer += miles } }
true
542ba0dea1c53a5e8291a342da4d2849b14b4ed6
Swift
hemmlj/aural-player
/Source/Favorites/Favorite.swift
UTF-8
908
3.21875
3
[]
no_license
import Cocoa class Favorite: StringKeyedItem { // The file of the track being favorited let file: URL private var _name: String // Used by the UI (track.displayName) var name: String { get { self.track?.displayName ?? _name } set(newValue) { _name = newValue } } var key: String { get { return file.path } set { // Do nothing } } var track: Track? init(_ track: Track) { self.track = track self.file = track.file self._name = track.displayName } init(_ file: URL, _ name: String) { self.file = file self._name = name } func validateFile() -> Bool { return FileSystemUtils.fileExists(file) } }
true
c9ae395376b203a6b5c7f745394e0b62f6f0d804
Swift
GiselleSerate/suitelife
/SuiteLife/SuiteLife/Group.swift
UTF-8
557
3
3
[]
no_license
// // Group.swift // SuiteLife // // Created by cssummer17 on 7/5/17. // Copyright © 2017 cssummer17. All rights reserved. // import Foundation class Group: NSObject { var groupID: String var name: String init(groupID: String, name: String) { self.groupID = groupID self.name = name } override func isEqual(_ object: Any?) -> Bool { if let object = object as? Group { return self.groupID == object.groupID } else { return false } } }
true