text
stringlengths
8
1.32M
// // Home.swift // myDiner // // Created by Matt Frohman on 5/25/20. // Copyright © 2020 Matt Frohman. All rights reserved. // import UIKit import LinearProgressBar class Home: UIViewController { let meals = ["Breakfast", "Lunch", "Dinner", "Snack", "Water", "Exercise"] let totals = ["/400 cals", "/600 cals", "/600 cals", "/200 cals", "/2.00 liters", "/300 cals burned"] var opened = [false, false, false, false, false, false] var parentStack : UIStackView! var progress : LinearProgressBar! var calorieCount : UILabel! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.titleView = UIImageView(image: UIImage(named: "restaurant")?.withRenderingMode(.alwaysTemplate)) // Set up title/calories let title = UILabel() title.translatesAutoresizingMaskIntoConstraints = false view.addSubview(title) title.widthAnchor.constraint(equalToConstant: 60).isActive = true title.heightAnchor.constraint(equalToConstant: 20).isActive = true title.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true title.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true title.font = UIFont(name: "Roboto-Medium", size: 18) title.text = "Today" // Set up progress bar progress = LinearProgressBar() progress.translatesAutoresizingMaskIntoConstraints = false view.addSubview(progress) progress.widthAnchor.constraint(equalToConstant: view.bounds.width - 50).isActive = true progress.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true progress.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 20).isActive = true progress.heightAnchor.constraint(equalToConstant: 25).isActive = true progress.progressValue = 6/7 * 100 progress.layer.borderWidth = 3.0 progress.layer.cornerRadius = 10 progress.backgroundColor = .clear progress.barThickness = 25 progress.barPadding = -25 progress.clipsToBounds = true progress.trackColor = .white progress.barColor = .red//UIColor(red: 0.754 * 255, green: 0.079 * 255, blue: 0.079 * 255, alpha: 1.0) calorieCount = UILabel() calorieCount.font = UIFont(name: "Roboto-Regular", size: 14) calorieCount.textAlignment = .center view.addSubview(calorieCount) calorieCount.translatesAutoresizingMaskIntoConstraints = false calorieCount.updateConstraints() calorieCount.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true calorieCount.heightAnchor.constraint(equalToConstant: 20).isActive = true calorieCount.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true calorieCount.topAnchor.constraint(equalTo: progress.bottomAnchor, constant: 15).isActive = true // Set up meal calorie counts parentStack = UIStackView() parentStack.translatesAutoresizingMaskIntoConstraints = false view.addSubview(parentStack) parentStack.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true // parentStack.heightAnchor.constraint(equalToConstant: 360).isActive = true parentStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true parentStack.topAnchor.constraint(equalTo: progress.topAnchor, constant: 100).isActive = true parentStack.axis = .vertical for num in 0...11 { if num % 2 == 0 { let subv = UIView() subv.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true subv.heightAnchor.constraint(equalToConstant: 60).isActive = true subv.tag = num / 2 subv.isUserInteractionEnabled = true subv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(show(_:)))) let meal = UILabel() meal.font = UIFont(name: "Roboto-Regular", size: meal.font.pointSize) subv.addSubview(meal) meal.translatesAutoresizingMaskIntoConstraints = false meal.widthAnchor.constraint(equalToConstant: 100).isActive = true meal.heightAnchor.constraint(equalToConstant: 40).isActive = true meal.centerYAnchor.constraint(equalTo: subv.centerYAnchor).isActive = true meal.leadingAnchor.constraint(equalTo: subv.leadingAnchor, constant: 25).isActive = true meal.text = meals[num / 2] let count = UILabel() count.numberOfLines = 0 subv.addSubview(count) count.translatesAutoresizingMaskIntoConstraints = false count.widthAnchor.constraint(equalToConstant: 100).isActive = true count.heightAnchor.constraint(equalToConstant: 80).isActive = true count.centerYAnchor.constraint(equalTo: subv.centerYAnchor).isActive = true count.leadingAnchor.constraint(equalTo: subv.trailingAnchor, constant: -180).isActive = true count.text = "0" + totals[num / 2] count.font = UIFont(name: "Roboto-Regular", size: count.font.pointSize) let img = UIButton() img.setImage(UIImage(named: "add")?.withRenderingMode(.alwaysTemplate), for: .normal) img.tintColor = UIColor(red: 0.754, green: 0.079, blue: 0.079, alpha: 1.0) subv.addSubview(img) img.translatesAutoresizingMaskIntoConstraints = false img.widthAnchor.constraint(equalToConstant: 25).isActive = true img.heightAnchor.constraint(equalToConstant: 25).isActive = true img.centerYAnchor.constraint(equalTo: subv.centerYAnchor).isActive = true img.leadingAnchor.constraint(equalTo: subv.trailingAnchor, constant: -50).isActive = true parentStack.addArrangedSubview(subv) } else { let subv = UIView() subv.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true subv.heightAnchor.constraint(equalToConstant: 60).isActive = true subv.isHidden = true parentStack.addArrangedSubview(subv) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) calorieCount.text = "-/- total calories for the day" } @objc func show(_ sender : UITapGestureRecognizer) { var spot = 0 for view in parentStack.subviews { if view.tag == sender.view!.tag && !opened[sender.view!.tag] { UIView.animate(withDuration: 0.25) { self.parentStack.subviews[spot + 1].isHidden = false } opened[sender.view!.tag] = !opened[sender.view!.tag] break } else if view.tag == sender.view!.tag && opened[sender.view!.tag] { //trickery UIView.animate(withDuration: 0.25) { self.parentStack.subviews[spot + 1].isHidden = true } opened[sender.view!.tag] = !opened[sender.view!.tag] break } spot += 1 } } }
// // PhotoView.swift // Lec19HWFilters // // Created by badyi on 16.06.2021. // import UIKit final class PhotoView: UIView { weak var controller: PhotoViewControllerProtocol? private var previewIsVisibleConstraint: NSLayoutConstraint? private var previewIsHiddenConstraint: NSLayoutConstraint? private var previewHeightConstraint: NSLayoutConstraint? private var editMode: Bool = false private lazy var imageView: UIImageView = { let view = UIImageView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .white view.contentMode = .scaleAspectFit view.isUserInteractionEnabled = true return view }() private lazy var previewCollectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.contentInset = UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1) cv.register(PreviewCell.self, forCellWithReuseIdentifier: PreviewCell.id) cv.translatesAutoresizingMaskIntoConstraints = false cv.backgroundColor = .white cv.dataSource = self cv.delegate = self return cv }() } extension PhotoView: PhotoViewProtocol { func updatePreviews() { previewCollectionView.reloadData() } func updateImage() { imageView.image = controller?.image() } func updateCell(at index: IndexPath) { previewCollectionView.reloadItems(at: [index]) } func viewDidLoad() { addSubview(imageView) addSubview(previewCollectionView) previewIsVisibleConstraint = imageView.bottomAnchor.constraint(equalTo: previewCollectionView.topAnchor) previewIsHiddenConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor) previewHeightConstraint = previewCollectionView.heightAnchor.constraint(equalToConstant: 100) hidePreview() NSLayoutConstraint.activate([ imageView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor), imageView.leadingAnchor.constraint(equalTo: leadingAnchor), imageView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) NSLayoutConstraint.activate([ previewCollectionView.topAnchor.constraint(equalTo: imageView.bottomAnchor), previewCollectionView.leadingAnchor.constraint(equalTo: leadingAnchor), previewCollectionView.trailingAnchor.constraint(equalTo: trailingAnchor), previewCollectionView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor) ]) } func showPreview() { editMode = true previewCollectionView.isHidden = false previewIsHiddenConstraint?.isActive = false previewIsVisibleConstraint?.isActive = true previewHeightConstraint?.isActive = true } func hidePreview() { editMode = false previewCollectionView.isHidden = true previewHeightConstraint?.isActive = false previewIsVisibleConstraint?.isActive = false previewIsHiddenConstraint?.isActive = true } func setImage(_ image: UIImage) { imageView.image = image } } extension PhotoView: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { controller?.didSelect(at: indexPath) } } extension PhotoView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return controller?.filtersCount() ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PreviewCell.id, for: indexPath) as! PreviewCell if let image = controller?.preview(at: indexPath) { cell.configView(with: image) } else { cell.spinner.startAnimating() } return cell } } extension PhotoView: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = collectionView.bounds.height - 2 let width = height - 2 return CGSize (width: width, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 2 } }
// Parse.swift // OnThaMap // // Created by Khaled Kutbi on 19/09/1441 AH. // Copyright © 1441 udacity. All rights reserved. import UIKit //MARK: - Parse APIs class ParseClient { enum Endpoints { case getStudentsLocations var stringValue: String { switch self { case .getStudentsLocations: return "https://onthemap-api.udacity.com/v1/StudentLocation" } } var url: URL { return URL(string: stringValue)! } } class func getStudentsLocations(completion:@escaping([StudentLocations],Error?) -> Void){ let task = URLSession.shared.dataTask(with: ParseClient.Endpoints.getStudentsLocations.url) { (data, response, error) in guard let data = data else{ completion([],error) return } let decoder = JSONDecoder() do { let objectResponse = try decoder.decode(StudentLocations.self, from: data) completion([objectResponse],nil) }catch{ print(error) } } task.resume() } }
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" str = "Hello, swift" let contastStr = str //Specifying Types var nextYear: Int var bodyTekmp: Float var hasPet: Bool //Collection Types //ARRAYS // var arrayOfInts: Array<Int> var arrayOfInts: [Int] // DICTIONARIES // var dictonaryOfCapitalsByCountry: Dictionary<String, String> var dictionaryOfCapitalsByCountry: [String: String] // SETS var winningLotteryNumbers: Set<Int> // LITERALS let number = 42 let fmStation = 91.1 var countingUp = ["one", "two"] let secondElement = countingUp[1] let nameByParkingSpace = [13: "alice", 27: "bob"] // INITIALIZERS let emptyString = String() let emptyArrayOfInts = [Int]() let emptySetOfFloats = Set<Float>() let defaultNumber = Int() let defaultBool = Bool() var testArray = [Int]() testArray.append(3) let newNumber = 45 let meaningOfLife = String(newNumber) let availableRooms = Set([46, 27, 3]) let defaultFloat = Float() let floatFromLiteral = Float(3.14) let easyPi = 3.14 let floatFromDouble = Float(easyPi) let floatingPi: Float = 3.14 //PROPERTIES countingUp.count emptyString.isEmpty // INSTANCE METHODS countingUp.append("three") // OPTIONALS var reading1: Float? var reading2: Float? var reading3: Float? reading1 = 9.8 reading2 = 9.2 reading3 = 9.7 // let avgReading = (reading1 + reading2 + reading3) / 3 // let avgReading = (reading1! + reading2! + reading3!) / 3 if let r1 = reading1, let r2 = reading2, let r3 = reading3 { let avgReading = (r1 + r2 + r3) / 3 } else { let errorstring = "Instrument reported a reading that was nil" } // SUBSCRIPTING DICTIONARIES // let space13Assignee: String? = nameByParkingSpace[13] if let space13Assignee = nameByParkingSpace[13] { print("Key 13 is assigned in the dictionary") } // let space42Assignee: String? = nameByParkingSpace[42] if let space42Assignee = nameByParkingSpace[42] { print("Key 42 is assinged in the dictionary") } else { print("Key 42 is NOT assinged in the dictionary") } // LOOPS AND STRING INTERPOLATION let range = 0..<countingUp.count for i in range { let string = countingUp[i] print(string) } for (i, string) in countingUp.enumerated() { print("\(i) \(string)") } for (space, name) in nameByParkingSpace { let permit = "Space \(space): \(name)" print(permit) } // ENUMERATIONS AND THE SWITCH STATEMENT enum PieType: Int { case apple = 0 case cherry case pecan } let favoritePie = PieType.apple let name: String switch favoritePie { case .apple: name = "Apple" case .cherry: name = "Cherry" case .pecan: name = "Pecan" } // ENUMERATIONS AND RAW VALUES let pieRawValue = PieType.pecan.rawValue if let pieType = PieType(rawValue: pieRawValue) { }
// // ItemCollectionTableViewCell.swift // colectionView // // Created by Macbook on 19/09/18. // Copyright © 2018 Macbook. All rights reserved. // import UIKit class ItemCollectionTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
import UIKit struct DataManager { static let sharedInstance = DataManager() private let jsonFileName = "data" private let fileType = "json" func getAllRecords()-> [Contact]? { return [Contact].getObjectFromJSONFile(fileName: jsonFileName, forKey: nil, fileType: fileType) } func addNewRecord(_ contact: Contact)-> Bool { if var contacts = getAllRecords() { contacts.append(contact) return writeToFile(contacts, jsonFileName, fileType: fileType) } else { return false } } func updateRecord(_ contact: Contact)-> Bool { let contacts = getAllRecords() if var _contacts = contacts, let row = _contacts.firstIndex(where: {$0.id == contact.id}) { _contacts[row] = contact return writeToFile(_contacts, jsonFileName, fileType: fileType) } else { return false } } private func writeToFile(_ records: [Contact], _ fileName: String, fileType: String)-> Bool { if let jsonFilePath = Bundle.main.path(forResource: fileName, ofType: fileType) { do { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let JsonData = try encoder.encode(records) try JsonData.write(to: URL(fileURLWithPath: jsonFilePath)) return true } catch { return false } } else { return false } } }
// // NavigatorHelper.swift // Biirr // // Created by Ana Márquez on 08/03/2021. // import UIKit class NavigatorHelper { static func pushToLogIn(from sender: UIViewController) { let vc = LogInViewController(LogInViewModel()) vc.modalPresentationStyle = .fullScreen sender.present(vc, animated: true) } static func pushToSignUp(from sender: UIViewController) { let vc = SignUpViewController(SignUpViewModel()) vc.modalPresentationStyle = .automatic sender.present(vc, animated: true) } static func pushToHome(from sender: UIViewController, user: AppUser) { let homeVC = HomeViewController(user) homeVC.modalTransitionStyle = .crossDissolve homeVC.modalPresentationStyle = .fullScreen sender.present(homeVC, animated: true) } static func pushToDetail(from sender: UIViewController, beer: Beer) { let vc = BeerDetailViewController(viewModel: BeerDetailViewModel(beer)) vc.modalPresentationStyle = .fullScreen vc.modalTransitionStyle = .crossDissolve sender.present(vc, animated: true) } }
// // CustomNewsTableViewCellData.swift // Tinkoff News // // Created by Sergey Korobin on 26.12.17. // Copyright © 2017 SergeyKorobin. All rights reserved. // import Foundation protocol NewsListCellProtocol: class{ var id: Int? {get set} var title: String? {get set} var content: String? {get set} var publicationDate: String? {get set} var counter: Int? {get set} var isViewed: Bool {get set} } class CustomNewsTableViewCellData : NewsListCellProtocol{ var id: Int? var title: String? var content: String? var publicationDate: String? var counter: Int? var isViewed: Bool init(id: Int?, title: String?, content: String?, publicationDate: Int?, counter: Int? = 0, isViewed: Bool = false) { self.id = id self.title = title self.content = content self.counter = counter self.isViewed = isViewed if let publicationDate = publicationDate { self.publicationDate = publicationDate.makeMilisecToDate(timeInMillisec: publicationDate) } else { let date = "Date not stayed" self.publicationDate = date } } init(id: Int?, title: String?, content: String?, publicationDate: String?, counter: Int?, isViewed: Bool = false) { self.id = id self.title = title self.content = content self.publicationDate = publicationDate self.counter = counter self.isViewed = isViewed } }
// // Copyright © 2016 Landet. All rights reserved. // import UIKit protocol TextFieldCellDelegate: class { func text(text: String, wasEnteredInCell cell: TextFieldCell) } class TextFieldCell: UITableViewCell { @IBOutlet weak var textField: LandetTextField! weak var delegate: TextFieldCellDelegate? override func awakeFromNib() { super.awakeFromNib() textField.delegate = self } func configure(placeholder placeholder: String) { textField.placeholder = placeholder } } extension TextFieldCell: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { if let text = textField.text where !text.isEmpty { delegate?.text(text, wasEnteredInCell: self) } return false } } private let kSpinnerTag = 0x1231; extension TextFieldCell { func lockWithSpinner() { let spinner = UIActivityIndicatorView() spinner.alpha = 0.0 spinner.activityIndicatorViewStyle = .WhiteLarge spinner.color = Colors.yellow spinner.sizeToFit() spinner.tag = kSpinnerTag spinner.center = contentView.bounds.center contentView.addSubview(spinner) spinner.startAnimating() self.textField.userInteractionEnabled = false UIView.animateWithDuration(0.3) { self.textField.alpha = 0.2 spinner.alpha = 1.0 } } func unlock() { let spinner = contentView.viewWithTag(kSpinnerTag) UIView.animateWithDuration(0.3, animations: { self.textField.alpha = 1.0 spinner?.alpha = 0.0 }) { (_) in self.textField.userInteractionEnabled = true spinner?.removeFromSuperview() } } }
// // CharactersViewController.swift // CodeHeroCharacters // // Created by Rafael Escaleira on 17/07/21. // import UIKit import CodeHeroModels import CodeHeroPagination public class CharactersViewController: UIViewController { let tableView = UITableView() var paginationView: PaginationView! let viewModel = CharactersViewModel() var searchController = UISearchController(searchResultsController: nil) public init() { super.init(nibName: "CharactersViewController", bundle: Bundle(for: CharactersViewController.self)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() title = "Characters" tabBarItem = UITabBarItem(title: "Characters", image: UIImage(systemName: "rectangle.stack.person.crop.fill"), tag: 0) navigationController?.navigationBar.prefersLargeTitles = true self.setupView() viewModel.character.bind(to: self.tableView.rx.items(cellIdentifier: "CharacterTableViewCell", cellType: CharacterTableViewCell.self)) { _, character, cell in self.tableView.separatorStyle = self.viewModel.character.value.isEmpty == false ? .singleLine : .none self.paginationView.maxOffset = self.viewModel.maxOffset cell.setCell(character: character) }.disposed(by: viewModel.disposeBag) self.tableView.rx.modelSelected(Character.CharacterData.Result.self).subscribe(onNext: { [weak self] character in let controllerDetail = CharacterDetailViewController(character: character) guard let row = self?.viewModel.character.value.firstIndex(where: { $0.id == character.id }) else { return } self?.present(controllerDetail, animated: true, completion: { self?.tableView.deselectRow(at: IndexPath(row: row, section: 0), animated: true) }) }).disposed(by: viewModel.disposeBag) viewModel.bindScrollToTop = { self.tableView.separatorStyle = self.viewModel.character.value.isEmpty == false ? .singleLine : .none if self.viewModel.character.value.isEmpty == false { self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .bottom, animated: true) } } viewModel.bindMode = { mode in self.paginationView.setCurrentOffset(mode == .search ? self.viewModel.currentPageFind : self.viewModel.offset) } } private func setupView() { self.setSearchBar(searchController: self.searchController, viewModel, viewModel) self.tableView.separatorStyle = .none self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0) view.addSubview(self.tableView) self.paginationView = PaginationView(frame: CGRect(x: 15, y: 200, width: 400, height: 60)) self.paginationView.delegate = viewModel view.insertSubview(self.paginationView, aboveSubview: self.tableView) let nib = UINib(nibName: "CharacterTableViewCell", bundle: Bundle(for: CharacterTableViewCell.self)) self.tableView.register(nib, forCellReuseIdentifier: "CharacterTableViewCell") self.tableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0), self.tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0), self.tableView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0.0), self.tableView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0.0) ]) self.paginationView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.paginationView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -105), self.paginationView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0) ]) } func setSearchBar(searchController: UISearchController, placeholder: String = "Search", _ searchBarDelegate: UISearchBarDelegate, _ searchResultsUpdater: UISearchResultsUpdating) { searchController.searchResultsUpdater = searchResultsUpdater searchController.searchBar.delegate = searchBarDelegate searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.placeholder = placeholder self.navigationItem.searchController = searchController self.navigationItem.hidesSearchBarWhenScrolling = false self.definesPresentationContext = true } }
// // AppDependencies.swift // VIPER TODO // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import UIKit import DipUI func configureContainer(container rootContainer: DependencyContainer) { Dip.logLevel = .Verbose //This is an example of a simplest definition: //DeviceClock is registered as implementation of Clock protocol in Singleton scope rootContainer.register(.Singleton) { DeviceClock() as Clock } //Or you can register concrete types rootContainer.register(.Singleton) { CoreDataStore() } //List module and add module should be connected through AddWireframe and ListPresenter //so we make them to collaborate to be able to share these instance //You can also do it manually referencing add module container in definitions of list module container, //but that is not possible with auto-wiring (as well as auto-inection) that we use for ListWireframe definition //Also containers collaboration can be used to share some base definitions //and to modularize yor configurations. listModule.collaborate(with: addModule, rootContainer) addModule.collaborate(with: listModule, rootContainer) //UI containers will be used to resolve dependencies of controllers //(or other NSObject's) created from storyboards if the conform to StoryboardInstantiatable DependencyContainer.uiContainers = [listModule, addModule] } //MARK: List module let listModule = DependencyContainer() { container in //This is an example of auto-wiring - container will resolve factory arguments by itself let listWireframe = container.register(.WeakSingleton) { ListWireframe(listPresenter: $0) } .resolvingProperties { container, wireframe in //resolveDependencies block is usually used to resolve dependencies with property injection //As you will see below we register controller with a tag, so we have to use it //to inject the same controller that was created from a storyboard wireframe.listViewController = try container.resolve(tag: ListViewControllerIdentifier) wireframe.addWireframe = try container.resolve() } container.register(listWireframe, type: Router.self) //Alternatively we can explicitly resolve factory arguments //DataStore will be resolved from root container through containers collaboration container.register(.Shared) { try ListDataManager( //you can explicitly specify type to resolve instead of letting compiler to infer it dataStore: container.resolve() as CoreDataStore ) } //Another example of auto-wiring definition but with passing initializer as a factory //instead of calling it in closure let interactor = container.register(.Shared, factory: ListInteractor.init) //This is an example of type-forwarding. Previous definition (and thus instance resolved using it) //will be used to resolve `ListInteractorInput` type. .implements(ListInteractorInput.self) .resolvingProperties { container, interactor in //While developing it is usefull to catch exceptions if something fails to resolve //For that use `try!` when calling container `resolve` method. //Otherwise the error will be just logged in the debugger. interactor.output = try! container.resolve() } let presenter = container.register(.Shared, factory: ListPresenter.init) .resolvingProperties { container, presenter in presenter.listInteractor = try container.resolve() //This is an example of circular dependencies: //wireframe has a reference to presenter, //presenter has a reference to wireframe. //We inject presenter in wireframe with constructor injection, //so to inject wirefreme in presenter we need to use property injection presenter.listWireframe = try container.resolve() presenter.userInterface = try container.resolve(tag: ListViewControllerIdentifier) } //Another examples of type-forwarding. container.register(presenter, type: ListInteractorOutput.self) container.register(presenter, type: ListModuleInterface.self) //This type will be resolved from add module through containers collaboration container.register(presenter, type: AddModuleDelegate.self) //This is an example of registering controller created from a storyboard. //For such controllers use the same tag as dipTag property (or nil) to register them. //Provided factory will be not called as controller is already instantiated from a storyboard. let controller = container.register(.Shared, tag: ListViewControllerIdentifier) { ListViewController() } .resolvingProperties { container, controller in //to use tag "ListViewController" to resolve dependencies graph we can use `container.context.tag` //but we don't do that because then list module will resolve one instance of AddWireframe //and then add module will resolve another instance of it instead of reusing the same instance controller.eventHandler = try container.resolve() controller.router = try container.resolve() } //we register ListViewController as ListViewInterface with the same tag //to be able to reuse instance created from storyboard container.register(controller, type: ListViewInterface.self, tag: ListViewControllerIdentifier) } //The only thing needed to inject in view controllers created from storyboards - to adopt StoryboardInstantiatable extension ListViewController: StoryboardInstantiatable { } //MARK: Add module let addModule = DependencyContainer() { container in //AddWireframe is registered as Singleton to make it reusable between collaborating containers. //Shared instances are also reused, but Singleton makes them to be reused across different graphs. //We can also use WeakSingleton so when the last strong reference to the instance is release //next instance will be created from scratch. That is usefull for cases when you have to reset //some components and create them based on a new application state. //For example when user logs in or logs out you may recreate the whole app graph //simply by resolving new instance of root wireframe. container.register(.Singleton, factory: AddWireframe.init) container.register(.Shared) { try AddDataManager( //You can use weakly-typed methods to resolve components dataStore: container.resolve(CoreDataStore.self) as! DataStore ) } container.register(.Shared, factory: AddInteractor.init) //We use Singleton scope for presenter because it will be first resolved by list module //when resolving ListWireframe that has dependency on AddWireframe that in turn depends on AddPresenter. //Shared scope reuses instances only while resolving single object graph, //in other words until the outermost call to `resolve` method returns. //When AddViewController is created later at runtime add module object graph will be resolved. //Because of that Shared scope will produce new AddPresenter (and it's dependencies) //With Singleton scope already created instance will be reused. //AddPresenter also makes extensive use of auto-injection to inject its dependencies with property injection. let presenter = container.register(.Singleton, factory: AddPresenter.init) container.register(presenter, type: AddModuleInterface.self) //To register controller with nil tag set dipTag in storyboard as Nil instead of String container.register(.Shared) { AddViewController() } } extension AddViewController: StoryboardInstantiatable { }
// // Copyright © 2016 Landet. All rights reserved. // import UIKit protocol TopicsTableViewControllerScrollDelegate: class { func topicsTableViewController(tableViewController: TopicsTableViewController, didScrollToOffset offset: CGPoint) } class TopicsTableViewController: UITableViewController { weak var scrollDelegate: TopicsTableViewControllerScrollDelegate? var topicsRepository: TopicsRepository! override func viewDidLoad() { super.viewDidLoad() LandetTableViewStyle.setup(tableView, cells: [.Comment, .Spinner]) tableView.estimatedRowHeight = 62 tableView.rowHeight = UITableViewAutomaticDimension topicsRepository.commentsRepository.delegate = self } } extension TopicsTableViewController: TopicCommentsRepositoryDelegate { func repository(repository: TopicCommentsRepository, didChangeToTopic topic: Topic?) { tableView.setContentOffset(CGPoint.zero, animated: true) tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, 2)), withRowAnimation: .Fade) } func repository(repository: TopicCommentsRepository, loadedNewCommentsInRange range: Range<Int>) { tableView.beginUpdates() let newCommentIndexPaths = range.map({ NSIndexPath(forRow: $0, inSection: 0) }) tableView.insertRowsAtIndexPaths(newCommentIndexPaths, withRowAnimation: .Automatic) tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic) tableView.endUpdates() } func repositoryLoadedComments(repository: TopicCommentsRepository) { tableView.reloadData() } } extension TopicsTableViewController { // UIScrollViewDelegate override func scrollViewDidScroll(scrollView: UIScrollView) { scrollDelegate?.topicsTableViewController(self, didScrollToOffset: scrollView.contentOffset) } } extension TopicsTableViewController { // UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 { return topicsRepository.commentsRepository.canLoadMore ? 1 : 0 } return topicsRepository.commentsRepository.comments.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 1 { let cell: SpinnerCell = tableView.dequeueLandetCell(.Spinner, forIndexPath: indexPath) cell.spin() cell.separatorInset = UIEdgeInsets(top: 0, left: view.bounds.width, bottom: 0, right: 0) return cell } let cell: CommentCell = tableView.dequeueLandetCell(.Comment, forIndexPath: indexPath) cell.configure(topicComment: topicsRepository.commentsRepository.comments[indexPath.row]) return cell } } extension TopicsTableViewController { // UITableViewDelegate override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 && indexPath.row == 0 { topicsRepository.commentsRepository.loadNextPage() } } }
// // UserListViewController.swift // SKILL_TEST // // Created by Кирилл Чуянов on 01.09.2018. // Copyright © 2018 Kirill Chuyanov. All rights reserved. // import UIKit protocol UserListViewSource: UITableViewDataSource, UITableViewDelegate { } protocol UserListViewProtocol: class { func reloadData() func showMessage(_ title: String?, body: String) } class UserListViewController: UIViewController { var interactor: UserListInteractorProtocol? weak var source: UserListViewSource? { didSet { if tableview != nil { tableview.delegate = source tableview.dataSource = source } } } @IBOutlet private var tableview: UITableView! override func viewDidLoad() { super.viewDidLoad() title = "Twitter DM" navigationController?.navigationBar.prefersLargeTitles = true tableview.dataSource = source tableview.delegate = source interactor?.loadData() //TODO: Refactor to custom cell tableview.register(UITableViewCell.self, forCellReuseIdentifier: "UserListCell") } } extension UserListViewController: UserListViewProtocol { func reloadData() { tableview.reloadData() } func showMessage(_ title: String?, body: String) { let alert = UIAlertController(title: title, message: body, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Retry", style: .default, handler: { _ in self.interactor?.loadData() })) present(alert, animated: true, completion: nil) } }
// // SeaViewController.swift // CaptainDemo // // Created by Vincent Esche on 5/25/18. // Copyright © 2018 Vincent Esche. All rights reserved. // import UIKit protocol SeaReceiver { func set(sea: Sea) } class SeaViewController: UIViewController { private(set) public var sea: Sea? { didSet { guard let sea = self.sea else { return } self.update(sea: sea) } } @IBOutlet var label: UILabel? override func viewDidLoad() { super.viewDidLoad() if let sea = self.sea { self.update(sea: sea) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // If shown modally, make sure the user can actually close the controller: if self.presentingViewController != nil { self.addCloseButton() } } @objc private func close(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } private func addCloseButton() { self.navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Close", style: .plain, target: self, action: #selector(SeaViewController.close(_:)) ) } private func update(sea: Sea) { self.title = sea.name if let label = self.label { label.text = sea.name } } } extension SeaViewController: SeaReceiver { func set(sea: Sea) { self.sea = sea } }
// // ShareTableViewCell.swift // Seeda // // Created by Golden.Eagle on 6/22/16. // Copyright © 2016 Илья Железников. All rights reserved. // import UIKit class ShareTableViewCell: UITableViewCell { @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var detailsLabel: UILabel! @IBOutlet weak var checkImg: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // SmartTransactionKind+UIImage.swift // WavesWallet-iOS // // Created by rprokofev on 07/03/2019. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import UIKit import DomainLayer extension DomainLayer.DTO.SmartTransaction.Kind { var image: UIImage { switch self { case .receive(let tx): if tx.hasSponsorship { return Images.tSponsoredPlus48.image } else { return Images.assetReceive.image } case .sent: return Images.tSend48.image case .startedLeasing: return Images.walletStartLease.image case .exchange: return Images.tExchange48.image case .canceledLeasing: return Images.tCloselease48.image case .tokenGeneration: return Images.tTokengen48.image case .tokenBurn: return Images.tTokenburn48.image case .tokenReissue: return Images.tTokenreis48.image case .selfTransfer: return Images.tSelftrans48.image case .createdAlias: return Images.tAlias48.image case .incomingLeasing: return Images.tIncominglease48.image case .unrecognisedTransaction: return Images.tUndefined48.image case .massSent: return Images.tMasstransfer48.image case .massReceived: return Images.tMassreceived48.image case .spamReceive: return Images.tSpamReceive48.image case .spamMassReceived: return Images.tSpamMassreceived48.image case .data: return Images.tData48.image case .script(let isHasScript): if isHasScript { return Images.tSetscript48.image } else { return Images.tSetscriptCancel48.image } case .assetScript: return Images.tSetassetscript48.image case .sponsorship(let isEnabled, _): if isEnabled { return Images.tSponsoredEnable48.image } else { return Images.tSponsoredDisable48.image } case .invokeScript: return Images.tInvocationscript48.image } } }
// // DatabaseLockTests.swift // DatabaseTests // // Created by Christopher G Prince on 7/12/20. // import XCTest @testable import Server @testable import TestsCommon import LoggerAPI import HeliumLogger import Foundation import ServerShared class DatabaseLockTests: ServerTestCase { let testLockName = "TestLock" override func setUp() { super.setUp() HeliumLogger.use(.debug) } override func tearDown() { super.tearDown() } func testSingleGetLock() throws { let result = try db.getLock(lockName: testLockName) Log.debug("testGetLock: \(result)") XCTAssert(result) } func testTwoGetLocksFail() throws { let result1 = try db.getLock(lockName: testLockName) XCTAssert(result1) // Second attempt must be on a different connection. If we use the same connection, it succeeds. guard let db2 = Database() else { XCTFail() return } let result2 = try db2.getLock(lockName: testLockName) XCTAssert(!result2) } func testGetLockAndReleaseLock() throws { let result1 = try db.getLock(lockName: testLockName) XCTAssert(result1) let result2 = try db.releaseLock(lockName: testLockName) XCTAssert(result2) } }
import GraphQL import NIO /** # GraphQL Schema A GraphQL Schema describes the entire API that is available. It's basically only a name space for your Query and Mutation Types. Your Query and Mutation Types have to be Root Types with the same Viewer Context. - A Query Type is mandatory. - A Mutation Type is optional. ## Examples If you only want to offer a Query Type, you only need to implement that class: ```swift enum MySchema { class Query: QueryType { func greeting(name: String = "World") -> String { return "Hello, \(name)!" } init(viewerContext: ()) { ... } } } ``` that gets translated to the following schema: ```graphql type Query { greeting(name: String! = "World"): String! } ``` Alternatively you can also specify a Mutation Type: ```swift enum MySchema { class Query: QueryType { func greeting(name: String = "World") -> String { return "Hello, \(name)!" } init(viewerContext: ()) { ... } } class Mutation: MutationType { func store(status: String) -> String { ... } init(viewerContext: ()) { ... } } } ``` Which would generate this Schema: ```graphql type Query { greeting(name: String! = "World"): String! } type Mutation { store(status: String!): String! } ``` If your types need to have a context for the current user, they need to use the exact same `ViewerContext`: ```swift enum MySchema { typealias ViewerContext = User class Query: QueryType { let user: User var greeting: String { return "Hello, \(user.name)!" } init(viewerContext: User) { ... } } class Mutation: MutationType { let user: User func store(status: String) -> String { ... } init(viewerContext: User) { ... } } } ``` */ public protocol GraphQLSchema { /** Type of the Response of the Schema */ typealias Result = GraphQLResult /** Type of an Empty Mutation Type. Signals GraphZahl that no mutations are allowed */ typealias None = EmptyRootType<ViewerContext> /** Type that tells the Query/Mutation type everything about the User. This defaults to Void, to signal that all requests are treated the same, and this API does not compute anything different on a by user basis. */ associatedtype ViewerContext = Void /** Type of the Query for this Schema. Should conform to `QueryType`. And should have the same Viewer Context as the Schema */ associatedtype Query: QueryType where Query.ViewerContext == ViewerContext /** Type of the Mutation for this Schema. Should conform to `MutationType`. And should have the same Viewer Context as the Schema. Defaults to `None` signalling GraphZahl that no mutations are allowed. */ associatedtype Mutation: MutationType = None where Mutation.ViewerContext == ViewerContext }
// // MapViewController.swift // DemoLeaPh // // Created by 谷口健一郎 on 2017/01/10. // Copyright © 2017年 谷口健一郎. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController,MKMapViewDelegate { var latitude:Double? var longitude:Double? @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self let myLatitude: CLLocationDegrees = latitude! let myLongitude: CLLocationDegrees = longitude! // 中心点. let center: CLLocationCoordinate2D = CLLocationCoordinate2DMake(myLatitude, myLongitude) // 表示領域. let mySpan: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1) let myRegion: MKCoordinateRegion = MKCoordinateRegionMake(center, mySpan) // MapViewにregionを追加. mapView.region = myRegion // MapViewに中心点を設定. mapView.setCenter(center, animated: true) var myPin: MKPointAnnotation = MKPointAnnotation() // 座標を設定. myPin.coordinate = center mapView.addAnnotation(myPin) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // PaymentService.swift // PicPayment // // Created by Hundily Cerqueira on 26/12/19. // Copyright © 2019 PicPayment. All rights reserved. // import Foundation protocol PaymentServiceProtocol { // typealias PaymentResult = Result<PaymentResponse, WebserviceError> // func fetchPayment(payment: Payment, completion: @escaping (PaymentResult) -> Void) } final class PaymentService: NSObject, PaymentServiceProtocol { let service: Webservice init(service: Webservice = BaseWebservice()) { self.service = service } // func fetchPayment(payment: Payment, completion: @escaping (PaymentResult) -> Void) { // let parameters: [String: Any] = [ // "card_number": payment.cardNumber, // "cvv": payment.cvv, // "value": payment.value, // "expiry_date": payment.expiryDate, // "destination_user_id": payment.destinationUserId // ] // // service.request(urlString: API.Path.payment.value, method: .post, parameters: parameters, encoding: .json) { (result: PaymentResult) in // switch result { // case let .success(payment): // completion(.success(payment)) // case let .failure(error): // completion(.failure(error)) // } // } // } }
// // AddPublicTransportSearchDelegate.swift // Travel Companion // // Created by Stefan Jaindl on 31.10.18. // Copyright © 2018 Stefan Jaindl. All rights reserved. // import Foundation class AddPublicTransportSearchDelegate: NSObject, AddTransportSearchDelegate { func buildSearchQueryItems(origin: String, destination: String) -> [String: String] { return [ Rome2RioConstants.ParameterKeys.key: SecretConstants.apiKeyRomeToRio, Rome2RioConstants.ParameterKeys.originName: origin, Rome2RioConstants.ParameterKeys.destinationName: destination, Rome2RioConstants.ParameterKeys.noAir: "true", Rome2RioConstants.ParameterKeys.noAirLeg: "true" ] } }
public enum PlaylistSortType: Int { /** * The Default sort order for playlist. DEFAULT value the playlist * query will return playlists sorted by alphabetically */ case DEFAULT /** * The most recent playlists will come first in playlist queries. * */ case NEWEST_FIRST /** * The most old playlists will come first in playlist queries. */ case LDEST_FIRST }
import Foundation struct Link { let title: String? let appURL: String? let webURL: String? }
// // Room+CoreDataProperties.swift // Rooms // // Created by David Malicke on 10/25/21. // // import Foundation import CoreData import UIKit extension Room { @nonobjc public class func fetchRequest() -> NSFetchRequest<Room> { return NSFetchRequest<Room>(entityName: "Room") } @NSManaged public var name: String @NSManaged public var width: Double @NSManaged public var length: Double @NSManaged public var color: UIColor? } extension Room : Identifiable { }
import UIKit import Alamofire import AlamofireImage //import CarbonKit import SeamlessSlideUpScrollView import XLPagerTabStrip import Kingfisher import CTSlidingUpPanel class OrdersVC: ButtonBarPagerTabStripViewController,CTBottomSlideDelegate{ var bottomController:CTBottomSlideController?; var tabs = [Int]() @IBOutlet weak var bottomView: UIView! @IBOutlet weak var coffeeImg: UIImageView! @IBOutlet weak var button: UIButton! @IBOutlet weak var slideUpView: SeamlessSlideUpView! @IBOutlet weak var bgBottomConstraint: NSLayoutConstraint! @IBOutlet weak var companyNameLbl: UILabel! @IBOutlet weak var spotAddressLbl: UILabel! @IBOutlet weak var companyLogoImg: UIImageView! @IBOutlet weak var heightConstraint: NSLayoutConstraint! @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var parrent : UIView! let cellReuseIdentifier = "cell" override func viewDidLoad() { bottomBar() super.viewDidLoad() sliderView() } func bottomBar(){ settings.style.buttonBarBackgroundColor = .init(red: 1, green: 120/255, blue: 0, alpha: 1) settings.style.buttonBarItemBackgroundColor = .init(red: 1, green: 120/255, blue: 0, alpha: 1) settings.style.selectedBarBackgroundColor = .white settings.style.selectedBarHeight = 2.0 settings.style.buttonBarMinimumLineSpacing = 0 settings.style.buttonBarItemTitleColor = .black settings.style.buttonBarItemsShouldFillAvailiableWidth = true settings.style.buttonBarLeftContentInset = 0 settings.style.buttonBarRightContentInset = 0 changeCurrentIndexProgressive = { [weak self] (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in guard changeCurrentIndex == true else { return } oldCell?.label.textColor = .white newCell?.label.textColor = UIColor.white } } func sliderView(){ OrderData.orderList.removeAll() bottomController = CTBottomSlideController(parent: view, bottomView: bottomView, tabController: self.tabBarController!, navController: self.navigationController, visibleHeight: 20) bottomController?.delegate = self; bottomController?.set(table: OrderData.controller.tableView) OrderData.controller.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) self.navigationController?.navigationItem.backBarButtonItem?.isEnabled = false cornerRatio(view: coffeeImg, ratio: 40/2, shadow: false) cornerRatio(view: bottomView, ratio: 20, shadow: false) let avatar_url = URL(string: current_coffee_net.logo_img)! coffeeImg.kf.setImage(with: avatar_url) companyNameLbl.text = current_coffee_net.name_other spotAddressLbl.text = current_coffee_spot.address OrderData.controller.limitLbl.text = "Лимит: \(current_coffee_spot.max_order_limit!) грн" OrderData.controller.sumLbl.text = "Сумма: \(0) грн" } @objc func toggleAction(sender:UIButton){ bottomController?.expandPanel() } // override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { // super.viewWillTransition(to: size, with: coordinator) // bottomController?.viewWillTransition(to: size, with: coordinator) // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func didPanelCollapse() { print("Collapsed"); } func didPanelExpand(){ print("Expanded") } func didPanelAnchor(){ print("Anchored") // OrderData.controller.tableView.reloadData() } func didPanelMove(panelOffset: CGFloat) { // let Storyboard = UIStoryboard(name: "Main", bundle: nil) // let cell = Storyboard.instantiateViewController(withIdentifier: "OrderList") as! OrderListVC cornerRatio(view: bottomView, ratio: 15 - (panelOffset * 15), shadow: false) } override func viewWillAppear(_ animated: Bool) { // let color = UIColor(red: 1, green: 0.585, blue: 0, alpha: 100) // UIApplication.shared.statusBarView?.backgroundColor = color // self.navigationController?.navigationBar.backgroundColor = color } override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { var storyboard = [UIViewController]() for i in tabs{ if i == 1{ storyboard.append(UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Coffee")) } else if i == 2{ storyboard.append(UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Cake")) } else if i == 9{ storyboard.append(UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "BottleWater")) } else if i == 10{ storyboard.append(UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Pie")) } else if i == 11{ storyboard.append(UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Other")) } else if i == 12{ storyboard.append(UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HotDrink")) } } return storyboard } @IBAction func togglePanel(_ sender: Any) { bottomController?.expandPanel() } }
// // LoadingIndicatorTableViewCell.swift // PaginationDemoPOC // // Created by Harsha on 12/03/20. // Copyright © 2020 Harsha. All rights reserved. // import Foundation import UIKit class LoadingIndicatorTableViewCell: UITableViewCell { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! override func awakeFromNib() { super.awakeFromNib() } }
// // KeyboardHandler.swift // PoseIt // // Created by Evgeniya on 31.10.2019. // Copyright © 2019 Broadsay. All rights reserved. // import UIKit class KeyboardHandler: NSObject { var keyboardWillAppear: ((_ height: CGFloat, _ animationDuration: CGFloat) -> ())? var keyboardWillDisappear: ((_ animationDuration: CGFloat) -> ())? private(set) var height : CGFloat = 0 override init() { super.init() self.setupKeyboardObserver() } private func setupKeyboardObserver() { NotificationCenter.default.addObserver(self, selector: #selector(KeyboardHandler.keyboardWillShow(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(KeyboardHandler.keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc private func keyboardWillShow(notification: NSNotification) { guard let height = self.heightForKeyboardFromNotification(notification: notification), let duration = self.animationDurationForKeyboardFromNotification(notificaiton: notification) else { return } self.height = height self.keyboardWillAppear?(height, duration) } @objc private func keyboardWillHide(notification: NSNotification) { guard let animationDuration = self.animationDurationForKeyboardFromNotification(notificaiton: notification) else { return } self.height = 0 self.keyboardWillDisappear?(animationDuration) } private func heightForKeyboardFromNotification(notification: NSNotification) -> CGFloat? { guard let info = notification.userInfo as? [String : AnyObject], let kbFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return nil } let keyboardFrame = kbFrame.cgRectValue return keyboardFrame.size.height } private func animationDurationForKeyboardFromNotification(notificaiton: NSNotification) -> CGFloat? { guard let info = notificaiton.userInfo as? [String : AnyObject], let value = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSValue else { return nil } var duration:CGFloat = 0 value.getValue(&duration) return duration } deinit { NotificationCenter.default.removeObserver(self) self.keyboardWillDisappear = nil self.keyboardWillAppear = nil } }
// // LoginViewController.swift // RoadTripPlanner // // Created by Deepthy on 10/11/17. // Copyright © 2017 Deepthy. All rights reserved. // import UIKit import FBSDKLoginKit import FBSDKCoreKit import Parse class LoginViewController: UIViewController { @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! static func storyboardInstance() -> LoginViewController? { let storyboard = UIStoryboard(name: "LoginViewController", bundle: nil) return storyboard.instantiateInitialViewController() as? LoginViewController } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let backButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: navigationController, action: nil) navigationItem.leftBarButtonItem = backButton } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Constants.Colors.ViewBackgroundColor loginButton.backgroundColor = Constants.Colors.ButtonBackgroundColor // Round the corners of the loginButton loginButton.layer.cornerRadius = 5 } // MARK: IBAction @IBAction func loginButtonPressed(_ sender: Any) { loginUser() } @IBAction func forgotPasswordButtonPressed(_ sender: Any) { } @IBAction func onFbLogin(_ sender: Any) { if FBSDKAccessToken.current() != nil { User.fetchProfile() } else { let loginManager = FBSDKLoginManager() loginManager.logIn(withReadPermissions: ["email","public_profile","user_friends"], from: self, handler: { (loginResults: FBSDKLoginManagerLoginResult?, error: Error?) -> Void in if !(loginResults?.isCancelled)! { User.fetchProfile() } else { // Sign in request cancelled // handle error object print("Error \(String(describing: error?.localizedDescription))") } }) } } // MARK: fileprivate func loginUser() { let username = usernameTextField.text ?? "" let password = passwordTextField.text ?? "" PFUser.logInWithUsername(inBackground: username, password: password) { (user: PFUser?, error: Error?) in if let error = error { log.error("Error: \(error)") self.showErrorAlert(title: "Login Failed", message: error.localizedDescription) } else { log.info("User logged in successfully") // manually segue to logged in view self.presentLoggedInScreen() } } } fileprivate func showErrorAlert(title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in // dismiss the view } alertController.addAction(cancelAction) let okAction = UIAlertAction(title: "OK", style: .default) { (action) in // handle response } alertController.addAction(okAction) present(alertController, animated: true) { } } fileprivate func presentLoggedInScreen() { let tabBarViewController = TabBarViewController() self.present(tabBarViewController, animated: true, completion: nil) } } extension LoginViewController: FBSDKLoginButtonDelegate { func loginButtonWillLogin(_ loginButton: FBSDKLoginButton!) -> Bool { return true } func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { // On logOut, the user is logged out of the app. it will not logout from user fb account. Only workaround is it to go into safari, get to Facebook.com and logout from user account. let loginManager: FBSDKLoginManager = FBSDKLoginManager() loginManager.logOut() } func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if error != nil { print(error) } else { User.fetchProfile() } } }
// // SettingsVC.swift // Podcast // // Created by Andrew Roach on 7/28/18. // Copyright © 2018 Andrew Roach. All rights reserved. // import UIKit class SettingsVC: UIViewController, UITableViewDelegate, UITableViewDataSource { var results = [Podcast: Int]() var keys = [Podcast]() override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() } override func viewWillAppear(_ animated: Bool) { reloadData() } @IBOutlet var tableView: UITableView! @IBAction func doneButtonPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } func reloadData() { results = FileSystemInteractor().fetchFileSizes()! keys = Array(results.keys) tableView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return keys.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let podcast = keys[indexPath.row] cell.textLabel?.text = podcast.name cell.detailTextLabel?.text = formatSize(size: results[podcast]!) cell.imageView?.image = UIImage(data: podcast.artwork600x600!) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let podcast = keys[indexPath.row] let alert = UIAlertController(title: "Confirm Delete", message: "Confirm you would like to delete data for: \(podcast.name!)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { (action) in FileSystemInteractor().deleteFilesFor(podcast: podcast) self.reloadData() })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true) tableView.deselectRow(at: indexPath, animated: true) } func formatSize(size: Int) -> String { let MB = Double(size) / 1000000 return String(format: "%.01f", MB) + " MB" } }
// deal with puzzle data in the form of Strings import Foundation import Cocoa enum Difficulty { case easy case medium case hard case evil } enum MoveType { case insertion case deletion case substitution } let letters = "ABCDEFGHI" let letterArray = Array(arrayLiteral: letters) let digits = "123456789" let digitArray = Array(arrayLiteral: digits) func orderedKeyArray() -> [String] { var kL = [String]() for l in letters.characters { for d in digits.characters { kL.append(String([l,d])) } } return kL } func validatedPuzzleString(s: String) -> String? { // let ws = NSCharacterSet.whitespaceAndNewlineCharacterSet() // doesn't work properly for \n var a = [Character]() for c in s.characters { if " \n".characters.contains(c) { continue } a.append(c) } if !(a.count == 81) { return nil } if !Set(a).isSubsetOf(validChars) { return nil } return String(a) } // returns true for success func loadPuzzleDataFromString(s: String) -> Bool { let ns = validatedPuzzleString(s) if ns == nil { let _ = runAlert("something wrong with that one") Swift.print(s) Swift.print(ns) return false } constructNewPuzzle(ns!) refreshScreen() return true } func getCurrentStateAsString() -> String { var arr = [String]() for (i,key) in dataD.keys.sort().enumerate() { if i != 0 { if (i % 9 == 0) { arr.append("\n") } } let data = Array(dataD[key]!) if data.count > 1 { arr.append("0") } else { arr.append(String(data[0])) } } let s = arr.joinWithSeparator("") Swift.print(s) return s } func addNewlinesToPuzzleString(s: String) -> String { Swift.print("add newlines to \(s)") var current = s var ret = [String]() while current.characters.count > 0 { Swift.print("count \(current.characters.count)") let i = current.startIndex.advancedBy(9) let front = current.substringToIndex(i) Swift.print(front) ret.append(front) ret.append("\n") current = current.substringFromIndex(i) } return s }
// // Card.swift // Game of Set // // Created by Dawid Nadolski on 08/01/2020. // Copyright © 2020 Dawid Nadolski. All rights reserved. // import Foundation struct Card: Equatable { var color: Int var shape: Int var count: Int var fill : Int init (color: Int, shape: Int, count: Int, fill: Int) { self.color = color self.shape = shape self.count = count self.fill = fill } }
// // AppCoordinator.swift // PokeApp // // Created by Taufik Rohmat on 19/08/21. // Copyright © 2021. All rights reserved. // final class AppCoordinator: BaseCoordinator { private let router: Router private let coordinatorFactory: CoordinatorFactory init(router: Router, coordinatorFactory: CoordinatorFactory) { self.router = router self.coordinatorFactory = coordinatorFactory } override func start() { runMainFlow() } private func runMainFlow() { let coordinator = coordinatorFactory.makeMainCoordinator(router: self.router) addDependency(coordinator) coordinator.start() } }
// // BaseConfig.swift // HFUTER // // Created by HD on 15/2/3. // Copyright (c) 2015年 HD. All rights reserved. // import Foundation class BaseConfig { var defaults: NSUserDefaults! = NSUserDefaults.standardUserDefaults() ///保存integer类型 func saveValue(value: Int, key: String) { self.defaults.setInteger(value, forKey: key) } ///保存integer64类型 func saveValue(value: Int64, key: String) { self.defaults.setValue("\(value)", forKey: key) } ///保存string类型数据 func saveValue(value: String, key: String) { self.defaults.setValue(value, forKey: key) } ///保存bool类型数据 func saveValue(value: Bool, key: String) { self.defaults.setBool(value, forKey: key) } ///保存float类型数据 func saveValue(value: Float, key: String) { self.defaults.setFloat(value, forKey: key) } ///保存double类型数据 func saveValue(value: Double, key: String) { self.defaults.setDouble(value, forKey: key) } ///获取integer类型数据 func getInteger(key: String, defaultValue: Int) -> Int { let value: AnyObject? = self.defaults.objectForKey(key) return value == nil ? defaultValue : value as! Int } ///获取integer类型数据 func getInt64(key: String, defaultValue: Int64) -> Int64 { let value: AnyObject? = self.defaults.objectForKey(key) let int64 = (value == nil ? "\(defaultValue)" : value as! String) return (int64 as NSString).longLongValue } ///获取string类型数据 func getString(key: String, defaultValue: String!) -> String! { let value: AnyObject? = self.defaults.objectForKey(key) return value == nil ? defaultValue : value as! String } ///获取bool类型数据 func getBool(key: String, defaultValue: Bool) -> Bool { let value: AnyObject? = self.defaults.objectForKey(key) return value == nil ? defaultValue : value as! Bool } ///获取float类型数据 func getFloat(key: String, defaultValue: Float) -> Float { let value: AnyObject? = self.defaults.objectForKey(key) return value == nil ? defaultValue : value as! Float } ///获取bool类型数据 func getDouble(key: String, defaultValue: Double) -> Double { let value: AnyObject? = self.defaults.objectForKey(key) return value == nil ? defaultValue : value as! Double } ///移除一个数据 func removeKey(key: String) { self.defaults.removeObjectForKey(key) } ///是否含有key func hasKey(key: String) -> Bool { return defaults.objectForKey(key) != nil } ///保存 func save() { self.defaults.synchronize() } }
import UIKit import VideoToolbox protocol WorkoutModelDelegate { func showDebugImage(_ resizedPixelBuffer: CVPixelBuffer, transform:CGAffineTransform) func showPrediction(label: String, score: String) } protocol WorkoutPreviewDelegate: AnyObject { func cameraPermissionManager() } class ViewController: UIViewController, WorkoutModelDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! @IBOutlet weak var score: UILabel! let model = InferenceModel() override func viewDidLoad() { super.viewDidLoad() model.delegate = self cameraPermissionManager() model.startInference() } override func viewWillDisappear(_ animated: Bool) { model.frameExtractor.stop() } override func viewWillAppear(_ animated: Bool) { if model.inferenceStarted { model.frameExtractor.start() } } private func navigateToCameraPermission() { guard let cameraPermissionVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "cameraTurnedOffViewController") as? CameraTurnedOffViewController else { return } navigationController?.pushViewController(cameraPermissionVC, animated: true) // needed in order to prevent to be stuck if dismiss this cameraPermission } func showDebugImage(_ resizedPixelBuffer: CVPixelBuffer, transform:CGAffineTransform) { DispatchQueue.main.async { var debugImage: CGImage? let img = UIImage.init(ciImage: CIImage(cvPixelBuffer: resizedPixelBuffer), scale:1, orientation:UIImage.Orientation.upMirrored) VTCreateCGImageFromCVPixelBuffer(resizedPixelBuffer, options: nil, imageOut: &debugImage) self.imageView.image = img // flip the image self.imageView.transform = transform } } func showPrediction(label: String, score: String) { DispatchQueue.main.async { self.label.text = label self.score.text = score } } } extension ViewController: WorkoutPreviewDelegate { func cameraPermissionManager() { // case to show tutorial or camera permission switch self.model.cameraPermission { case .authorized: self.model.setUpCamera() self.model.startInference() case .notDetermined: self.model.requestCameraAccess { granted in DispatchQueue.main.sync { if granted { self.model.setUpCamera() self.model.startInference() } else { self.navigationController?.setNavigationBarHidden(false, animated: false) self.navigateToCameraPermission() } } } default: self.navigationController?.setNavigationBarHidden(false, animated: false) navigateToCameraPermission() } } }
// // FileManager.swift // TwitterApp // // Created by Heikki on 2018-11-20. // Copyright © 2018 Heikki. All rights reserved. // import Foundation extension FileManager { // Helper method for accessing app's documents folder class func documentsDir() -> String { var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String] return paths[0] } }
// // LocationNotification.swift // GonzagaCampusWalkingTour // // Created by Max Heinzelman on 4/21/20. // Copyright © 2020 Senior Design Group 8. All rights reserved. // import Foundation import CoreLocation import UserNotifications class LocationNotificationCenter: NSObject, UNUserNotificationCenterDelegate { var notificationsPermissions: Bool = false func requestLocationNotificationPermissions(callback: @escaping (Bool) -> Void) { guard CLLocationManager.locationServicesEnabled() else { return } UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(granted,error) in self.notificationsPermissions = granted callback(granted); }) UNUserNotificationCenter.current().delegate = self } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) } func sendNotification(title: String, body: String) { let notificationContent = UNMutableNotificationContent() notificationContent.title = title notificationContent.body = body let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) let request = UNNotificationRequest(identifier: "entering_location_alert", content: notificationContent, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: {(error) in if let error = error { print(error) } else { print("notification successfully sent") } }) } }
// // String+FilterHTML.swift // DicodingMovieFirst // // Created by Kevin Yulias on 19/07/20. // Copyright © 2020 Kevin Yulias. All rights reserved. // import Foundation struct StringHelper { @available(*, unavailable) private init() {} static func eraseAllHTMLTags(from string: String) -> String? { do { guard let data = string.data(using: .unicode) else { return nil } let attributed = try NSAttributedString( data: data, options: [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil ) return attributed.string } catch { return nil } } }
// // ConfirmRequestSystem.swift // WavesWallet-iOS // // Created by rprokofev on 26.08.2019. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import DomainLayer import RxFeedback import RxSwift import RxCocoa import Extensions import WavesSDKExtensions import WavesSDK import WavesSDKCrypto private typealias Types = ConfirmRequest final class ConfirmRequestSystem: System<ConfirmRequest.State, ConfirmRequest.Event> { private lazy var assetsUseCase: AssetsUseCaseProtocol = UseCasesFactory.instance.assets private lazy var mobileKeeperRepository: MobileKeeperRepositoryProtocol = UseCasesFactory.instance.repositories.mobileKeeperRepository private let input: ConfirmRequest.DTO.Input init(input: ConfirmRequest.DTO.Input) { self.input = input } override func initialState() -> State! { return ConfirmRequest.State(ui: uiState(), core: coreState(input: self.input)) } override func internalFeedbacks() -> [Feedback] { return [prepareRequest] } struct PrepareRequest: Equatable { let assetsIds: [String] let request: DomainLayer.DTO.MobileKeeper.Request let signedWallet: DomainLayer.DTO.SignedWallet let timestamp: Date static func ==(lhs: PrepareRequest, rhs: PrepareRequest) -> Bool { return lhs.timestamp == rhs.timestamp } } private lazy var prepareRequest: Feedback = { return react(request: { (state) -> PrepareRequest? in if case .prepareRequest = state.core.action { var assetsIds: [String] = [] switch state.core.request.transaction { case .send(let tx): assetsIds.append(tx.feeAssetID) assetsIds.append(tx.assetId) case .data: assetsIds.append(WavesSDKConstants.wavesAssetId) case .invokeScript(let tx): assetsIds.append(tx.feeAssetId ) let list: [String] = (tx.payment.map { $0.assetId }) assetsIds.append(contentsOf: list) default: break } return PrepareRequest(assetsIds: assetsIds, request: state.core.request, signedWallet: state.core.signedWallet, timestamp: state.core.timestamp) } return nil }, effects: { [weak self] (request) -> Signal<Event> in guard let self = self else { return Signal.never() } let prepareRequest = self .mobileKeeperRepository .prepareRequest(request.request, signedWallet: request.signedWallet, timestamp: request.timestamp) let assets = self .assetsUseCase .assets(by: request.assetsIds, accountAddress: "") return Observable.zip(prepareRequest, assets) .map { Types.Event.prepareRequest($1, $0) } .asSignal(onErrorRecover: { error in return Signal.just(.handlerError) }) }) }() override func reduce(event: Event, state: inout State) { switch event { case .handlerError: state.ui.action = .closeRequest state.core.action = .none case .none: break case .prepareRequest(let assets, let prepareRequest): let map = assets.reduce(into: [String: DomainLayer.DTO.Asset].init()) { (result, asset) in result[asset.id] = asset } guard let txRequest = state .core .request .transaction .transactionDTO(assetsMap: map, signedWallet: state.core.signedWallet) else { //TODO: Error? //Transaction not support state.ui.action = .closeRequest state.core.action = .none state.core.prepareRequest = prepareRequest return } let complitingRequest = ConfirmRequest .DTO .ComplitingRequest.init(transaction: txRequest, prepareRequest: prepareRequest, signedWallet: state.core.signedWallet, timestamp: prepareRequest.timestamp, proof: prepareRequest.proof, txId: prepareRequest.txId) state.ui.sections = sections(complitingRequest: complitingRequest) state.ui.action = .update state.core.action = .none state.core.prepareRequest = prepareRequest state.core.complitingRequest = complitingRequest case .viewDidAppear: state.ui.sections = [Types.Section(rows: [.skeleton])] state.ui.action = .update state.core.action = .prepareRequest state.core.timestamp = Date() } } private func uiState() -> State.UI! { return ConfirmRequest.State.UI(sections: [], action: .none) } private func coreState(input: ConfirmRequest.DTO.Input) -> State.Core! { return State.Core(action: .none, request: input.request, signedWallet: input.signedWallet, prepareRequest: nil, complitingRequest: nil, timestamp: Date()) } private func sections(complitingRequest: ConfirmRequest.DTO.ComplitingRequest) -> [Types.Section] { var rows: [Types.Row] = [.transactionKind(complitingRequest.transaction.transactionKindViewModel), .fromTo(complitingRequest.fromToViewModel)] switch complitingRequest.transaction { case .invokeScript(let tx): //TODO: Localization let address = ConfirmRequestKeyValueCell.Model(title: Localizable.Waves.Transactioncard.Title.scriptAddress, value: tx.dApp) if let function = tx.call?.function { let function = ConfirmRequestKeyValueCell.Model(title: Localizable.Waves.Keeper.Label.function, value: function) rows.append(.keyValue(function)) } rows.append(.keyValue(address)) for payment in tx.payment { let paymentBalance: BalanceLabel.Model = .init(balance: Balance.init(currency: .init(title: payment.asset.displayName, ticker: payment.asset.ticker), money: .init(payment.amount.amount, payment.asset.precision)), sign: .minus, style: .small) //TODO: Localization let balance = ConfirmRequestBalanceCell.Model.init(title: Localizable.Waves.Transactioncard.Title.payment, feeBalance: paymentBalance) rows.append(.balance(balance)) } default: break } rows.append(.keyValue(complitingRequest.txIdkeyValueViewModel)) rows.append(.feeAndTimestamp(complitingRequest.feeAndTimestampViewModel)) rows.append(.buttons) return [Types.Section(rows: rows)] } } fileprivate extension ConfirmRequest.DTO.ComplitingRequest { var feeAndTimestampViewModel: ConfirmRequestFeeAndTimestampCell.Model { let feeAsset = self.transaction.feeAsset let fee = self.transaction.fee let feeBalance: BalanceLabel.Model = .init(balance: Balance.init(currency: .init(title: feeAsset.displayName, ticker: feeAsset.ticker), money: .init(fee.amount, feeAsset.precision)), sign: .none, style: .small) return ConfirmRequestFeeAndTimestampCell.Model(date: timestamp, feeBalance: feeBalance) } var fromToViewModel: ConfirmRequestFromToCell.Model { return ConfirmRequestFromToCell.Model.init(accountName: signedWallet.wallet.name, address: signedWallet.address, dAppIcon: prepareRequest.request.dApp.iconUrl, dAppName: prepareRequest.request.dApp.name) } var txIdkeyValueViewModel: ConfirmRequestKeyValueCell.Model { //TODO: Localization return ConfirmRequestKeyValueCell.Model(title: Localizable.Waves.Startleasingconfirmation.Label.txid, value: txId) } } fileprivate extension InvokeScriptTransactionSender.Arg { var argDTO: ConfirmRequest.DTO.InvokeScript.Arg { switch self.value { case .binary(let binary): return ConfirmRequest.DTO.InvokeScript.Arg.init(value: .binary(binary)) case .bool(let bool): return ConfirmRequest.DTO.InvokeScript.Arg.init(value: .bool(bool)) case .integer(let int): return ConfirmRequest.DTO.InvokeScript.Arg.init(value: .integer(int)) case .string(let string): return ConfirmRequest.DTO.InvokeScript.Arg.init(value: .string(string)) } } } fileprivate extension InvokeScriptTransactionSender.Call { func invokeScriptCallArgs(assetsMap: [String: DomainLayer.DTO.Asset], signedWallet: DomainLayer.DTO.SignedWallet) -> [ConfirmRequest.DTO.InvokeScript.Arg]? { return self.args.map { $0.argDTO } } func invokeScriptCall(assetsMap: [String: DomainLayer.DTO.Asset], signedWallet: DomainLayer.DTO.SignedWallet) -> ConfirmRequest.DTO.InvokeScript.Call? { guard let args = invokeScriptCallArgs(assetsMap: assetsMap, signedWallet: signedWallet) else { return nil } return ConfirmRequest.DTO.InvokeScript.Call(function: self.function, args: args) } } fileprivate extension InvokeScriptTransactionSender { func paymentDTO(assetsMap: [String: DomainLayer.DTO.Asset], signedWallet: DomainLayer.DTO.SignedWallet) -> [ConfirmRequest.DTO.InvokeScript.Payment] { return self.payment.map { (payment) -> ConfirmRequest.DTO.InvokeScript.Payment? in guard let asset = assetsMap[payment.assetId] else { return nil } let amount = Money(payment.amount, asset.precision) return .init(amount: amount, asset: asset) } .compactMap { $0 } } } fileprivate extension DataTransactionSender.Value { func valueDTO() -> ConfirmRequest.DTO.Data.Value.Kind { switch self.value { case .binary(let value): return .binary(value) case .boolean(let value): return .boolean(value) case .integer(let value): return .integer(value) case .string(let value): return .string(value) } } } fileprivate extension DataTransactionSender { func dataDTO() -> [ConfirmRequest.DTO.Data.Value] { return self.data.map { (data) -> ConfirmRequest.DTO.Data.Value in return ConfirmRequest.DTO.Data.Value(key: data.key, value: data.valueDTO()) } } } fileprivate extension TransactionSenderSpecifications { func transactionDTO(assetsMap: [String: DomainLayer.DTO.Asset], signedWallet: DomainLayer.DTO.SignedWallet) -> ConfirmRequest.DTO.Transaction? { switch self { case .data(let tx): guard let feeAsset = assetsMap[WavesSDKConstants.wavesAssetId] else { return nil } let fee = Money(tx.fee, feeAsset.precision) let data = ConfirmRequest.DTO.Data.init(fee: fee, feeAsset: feeAsset, data: tx.dataDTO(), chainId: tx.chainId ?? "") return .data(data) case .invokeScript(let tx): guard let asset = assetsMap[WavesSDKConstants.wavesAssetId] else { return nil } guard let feeAsset = assetsMap[tx.feeAssetId] else { return nil } guard let call = tx.call?.invokeScriptCall(assetsMap: assetsMap, signedWallet: signedWallet) else { return nil } let fee = Money(tx.fee, feeAsset.precision) let invokeScript = ConfirmRequest.DTO.InvokeScript(asset: asset, fee: fee, feeAsset: feeAsset, chainId: tx.chainId ?? "", dApp: tx.dApp, call: call, payment: tx.paymentDTO(assetsMap: assetsMap, signedWallet: signedWallet) ) return .invokeScript(invokeScript) case .send(let tx): guard let asset = assetsMap[tx.assetId] else { return nil} guard let feeAsset = assetsMap[tx.feeAssetID] else { return nil} let money = Money(tx.amount, asset.precision) let fee = Money(tx.fee, feeAsset.precision) let transfer: ConfirmRequest.DTO.Transfer = .init(recipient: tx.recipient, asset: asset, amount: money, feeAsset: feeAsset, fee: fee, attachment: tx.attachment, chainId: tx.chainId ?? "") return .transfer(transfer) default: return nil } } }
// // MetronomeTests.swift // MetronomeTests // // Created by luca strazzullo on 30/9/19. // Copyright © 2019 luca strazzullo. All rights reserved. // import XCTest class MetronomeTests: XCTestCase { private var tickExpectation: XCTestExpectation? private var metronome: Metronome? // MARK: Test life cycle override func tearDown() { super.tearDown() metronome?.reset() } // MARK: 4/4 func test120bpm44ts() { tickExpectation = expectation(description: "120-4/4") tickExpectation?.expectedFulfillmentCount = 4 let configuration = MetronomeConfiguration(timeSignature: .default, tempo: Tempo(bpm: 120)) metronome = Metronome(with: configuration, soundOn: false) metronome?.delegate = self metronome?.start() wait(for: [tickExpectation!], timeout: 2) } func test90bpm44ts() { tickExpectation = expectation(description: "90-4/4") tickExpectation?.expectedFulfillmentCount = 3 let configuration = MetronomeConfiguration(timeSignature: .default, tempo: Tempo(bpm: 90)) metronome = Metronome(with: configuration, soundOn: false) metronome?.delegate = self metronome?.start() wait(for: [tickExpectation!], timeout: 2) } func test60bpm44ts() { tickExpectation = expectation(description: "60-4/4") tickExpectation?.expectedFulfillmentCount = 2 let configuration = MetronomeConfiguration(timeSignature: .default, tempo: Tempo(bpm: 60)) metronome = Metronome(with: configuration, soundOn: false) metronome?.delegate = self metronome?.start() wait(for: [tickExpectation!], timeout: 2) } // MARK: 4/8 func test120bpm48ts() { tickExpectation = expectation(description: "120-4/8") tickExpectation?.expectedFulfillmentCount = 8 let configuration = MetronomeConfiguration(timeSignature: TimeSignature(barLength: .default, noteLength: .eigth), tempo: Tempo(bpm: 120)) metronome = Metronome(with: configuration, soundOn: false) metronome?.delegate = self metronome?.start() wait(for: [tickExpectation!], timeout: 2) } } extension MetronomeTests: MetronomeDelegate { func metronome(_ metronome: Metronome, didUpdate configuration: MetronomeConfiguration) { } func metronome(_ metronome: Metronome, didUpdate isSoundOn: Bool) { } func metronome(_ metronome: Metronome, willStartWithSuspended beat: Beat?) { } func metronome(_ metronome: Metronome, willResetAt beat: Beat?) { } func metronome(_ metronome: Metronome, didPulse beat: Beat) { tickExpectation?.fulfill() } }
// // Validation.swift // FundooApp // // Created by admin on 25/05/20. // Copyright © 2020 admin. All rights reserved. // import Foundation class TextFieldValidator { public func validateName(name: String) ->Bool { let nameRegix = "^\\w{3,12}" let validateName = NSPredicate(format: "SELF MATCHES%@",nameRegix) return validateName.evaluate(with: name) } public func validateEmailId(emailID: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let validateEmail = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return validateEmail.evaluate(with: emailID) } public func validatePassword(password: String) -> Bool { let passRegEx = "(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])(?=.*[@#$%^&*]).{8,}" let validatePassord = NSPredicate(format:"SELF MATCHES %@", passRegEx) return validatePassord.evaluate(with: password) } }
// // ObjectiveC.swift // // // Created by Adam Bell on 5/26/20. // import Accelerate import simd import Foundation import QuartzCore /// This class wraps the Swift interface for `CATransform3D.DecomposedTransform` in a means that it can be used from Objective-C. @objcMembers public class DEDecomposedCATransform3D: NSObject { /// The translation of the transform. public var translation: simd_double3 { get { return decomposed.translation } set { decomposed.translation = newValue } } /// The scale of the transform. public var scale: simd_double3 { get { return decomposed.scale } set { decomposed.scale = newValue } } /// The rotation of the transform (expressed as a quaternion). public var rotation: simd_quatd { get { return decomposed.rotation } set { decomposed.rotation = newValue } } /// The rotation of the transform (expressed as euler angles, expressed in radians). public var eulerAngles: simd_double3 { get { return decomposed.eulerAngles } set { decomposed.eulerAngles = newValue } } /// The shearing of the transform. public var skew: simd_double3 { get { return decomposed.skew } set { decomposed.skew = newValue } } /// The perspective of the transform (e.g. .m34). public var perspective: simd_double4{ get { return decomposed.perspective } set { decomposed.perspective = newValue } } @nonobjc private var decomposed: matrix_double4x4.DecomposedTransform /// Default initializer. @objc(initWithTransform:) public init(_ transform: CATransform3D) { self.decomposed = matrix_double4x4(transform).decomposed() } /// Class initializer. public class func decomposedTransformWith(transform: CATransform3D) -> DEDecomposedCATransform3D { return DEDecomposedCATransform3D(transform) } /// Returns a recomposed `CATransform3D`. public func recomposed() -> CATransform3D { return CATransform3D(decomposed.recomposed()) } } /// This class wraps the Swift interface for `matrix_double4x4.DecomposedTransform` in a means that it can be used from Objective-C. @objcMembers public class DEDecomposedMatrixDouble4x4: NSObject { /// The translation of the transformation matrix. public var translation: simd_double3 { get { return decomposed.translation } set { decomposed.translation = newValue } } /// The scale of the transformation matrix. public var scale: simd_double3 { get { return decomposed.scale } set { decomposed.scale = newValue } } /// The rotation of the transformation matrix (expressed as a quaternion). public var rotation: simd_quatd { get { return decomposed.rotation } set { decomposed.rotation = newValue } } /// The rotation of the transformation matrix (expressed as euler angles, expressed in radians). public var eulerAngles: simd_double3 { get { return decomposed.eulerAngles } set { decomposed.eulerAngles = newValue } } /// The shearing of the transformation matrix. public var skew: simd_double3 { get { return decomposed.skew } set { decomposed.skew = newValue } } /// The perspective of the transformation matrix (e.g. .m34). public var perspective: simd_double4{ get { return decomposed.perspective } set { decomposed.perspective = newValue } } @nonobjc private var decomposed: matrix_double4x4.DecomposedTransform /// Default initializer. @objc(initWithMatrixDouble4x4:) public init(_ matrix: matrix_double4x4) { self.decomposed = matrix.decomposed() } /// Class initializer. public class func decomposedMatrixWith(_ matrix: matrix_double4x4) -> DEDecomposedMatrixDouble4x4 { return DEDecomposedMatrixDouble4x4(matrix) } /// Returns a recomposed `CATransform3D`. public func recomposed() -> matrix_double4x4 { return decomposed.recomposed() } } /// This class wraps the Swift interface for `matrix_float4x4.DecomposedTransform` in a means that it can be used from Objective-C. @objcMembers public class DEDecomposedMatrixFloat4x4: NSObject { /// The translation of the transformation matrix. public var translation: simd_float3 { get { return decomposed.translation } set { decomposed.translation = newValue } } /// The scale of the transformation matrix. public var scale: simd_float3 { get { return decomposed.scale } set { decomposed.scale = newValue } } /// The rotation of the transformation matrix (expressed as a quaternion). public var rotation: simd_quatf { get { return decomposed.rotation } set { decomposed.rotation = newValue } } /// The rotation of the transformation matrix (expressed as euler angles, expressed in radians). public var eulerAngles: simd_float3 { get { return decomposed.eulerAngles } set { decomposed.eulerAngles = newValue } } /// The shearing of the transformation matrix. public var skew: simd_float3 { get { return decomposed.skew } set { decomposed.skew = newValue } } /// The perspective of the transformation matrix (e.g. .m34). public var perspective: simd_float4{ get { return decomposed.perspective } set { decomposed.perspective = newValue } } @nonobjc private var decomposed: matrix_float4x4.DecomposedTransform /// Default initializer. @objc(initWithMatrixFloat4x4:) public init(_ matrix: matrix_float4x4) { self.decomposed = matrix.decomposed() } /// Class initializer. public class func decomposedTransformWith(_ matrix: matrix_float4x4) -> DEDecomposedMatrixFloat4x4 { return DEDecomposedMatrixFloat4x4(matrix) } /// Returns a recomposed `CATransform3D`. public func recomposed() -> matrix_float4x4 { return decomposed.recomposed() } }
// // StudentDataSource.swift // OnTheMap // // Created by Aniket Ghode on 4/19/17. // Copyright © 2017 Aniket Ghode. All rights reserved. // import UIKit class StudentDataSource: NSObject { var studentData = [UdacityStudentInformation]() static let sharedInstance = StudentDataSource() private override init() {} //This prevents others from using the default '()' initializer for this class. }
// // TBMovieCell.swift // Movie // // Created by Aditya Tanna on 4/26/17. // Copyright © 2017 Tanna Inc. All rights reserved. // import UIKit class TBMovieCell: UITableViewCell { @IBOutlet var imgMovieThumb: UIImageView! @IBOutlet var lblMovieTitle: UILabel! @IBOutlet var lblMovieDescription: UILabel! @IBOutlet var lblMovieCategory: UILabel! @IBOutlet var lblMovieReleaseDate: UILabel! @IBOutlet var btnDetails: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // GZERateCommentRepositoryProtocol.swift // Gooze // // Created by Yussel Paredes Perez on 5/21/18. // Copyright © 2018 Gooze. All rights reserved. // import Foundation import ReactiveSwift protocol GZERateCommentRepositoryProtocol { func findAll() -> SignalProducer<[GZERateComment], GZEError> }
import UIKit import Flutter import Foundation @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let controller = window?.rootViewController as! FlutterViewController let channel = FlutterMethodChannel(name: "battery", binaryMessenger: controller as! FlutterBinaryMessenger) channel.setMethodCallHandler({ (call: FlutterMethodCall, result: FlutterResult) -> Void in guard call.method == "getBattery" else { result(FlutterMethodNotImplemented) return } self.receiveBatteryLevel(result: result) }) let channel2 = FlutterMethodChannel(name: "date", binaryMessenger: controller as! FlutterBinaryMessenger) channel2.setMethodCallHandler({ (call: FlutterMethodCall, result: FlutterResult) -> Void in guard call.method == "getDate" else { result(FlutterMethodNotImplemented) return } self.receiveDate(result: result); }) GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } private func receiveDate(result: FlutterResult) { let formatter = DateFormatter() formatter.timeStyle = .full let dateString = formatter.string(from:Date()) result(dateString) } private func receiveBatteryLevel(result: FlutterResult) { let device = UIDevice.current device.isBatteryMonitoringEnabled = true if device.batteryState == UIDevice.BatteryState.unknown { result(FlutterError(code: "Unavailable", message: "Battery info unavailable", details: nil)) } else { result(Int(device.batteryLevel * 100)) } } }
// // BooksViewController.swift // iOSTakeHomeChallenge // // Created by James Malcolm on 09/03/2021. // import Foundation import UIKit class BooksViewController: RootViewController, UITableViewDataSource { @IBOutlet var tableView: UITableView! private var viewModel: BooksViewModelType = BooksViewModel() var cachedBooks: [Book] = [] override func viewDidLoad() { super.viewDidLoad() addActivityIndicator(center: view.center) setupBindings() getBooks() } private func setupBindings() { viewModel.books.bind { books in if let books = books { self.cachedBooks = books } } } private func getBooks() { startActivityIndicator() viewModel.fetchBooks(fetchCompletion: loadData, errorCompletion: errorAlert) } private func loadData() { reload(tableView: tableView) stopActivityIndicator() } private func errorAlert() { showAlertAndStopActivityIndicator() } func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { cachedBooks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: BooksTableViewCell.reuseIdentifierCell) as! BooksTableViewCell cell.setupWith(bookViewModel: BookViewModel(book: cachedBooks[indexPath.row])) return cell } } class BooksTableViewCell: UITableViewCell { static let reuseIdentifierCell = "BooksTableViewCell" @IBOutlet var titleLabel: UILabel! @IBOutlet var dateLabel: UILabel! @IBOutlet var pagesLabel: UILabel! override func prepareForReuse() { titleLabel.text = "" dateLabel.text = "" pagesLabel.text = "" } func setupWith(bookViewModel: BookViewModel) { titleLabel.text = bookViewModel.name dateLabel.text = bookViewModel.released pagesLabel.text = bookViewModel.numberOfPages } }
// // UIFont+Extensions.swift // Frames-App // // Created by Tyler Zhao on 12/7/18. // Copyright © 2018 Tyler Zhao. All rights reserved. // import UIKit extension UIFont { }
// // API_ProfileEditing.swift // ETBAROON // // Created by imac on 10/9/17. // Copyright © 2017 IAS. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class API_ProfileEditing: NSObject { class func updateUserPage(fldAppUserID: String, fldAppUserFirstName: String,fldAppUserLastName: String, fldAppUserPhone: String , completion: @escaping (_ error: Error?, _ success: Bool ,_ updateUserPage: [res]?)->Void){ let url = DomainInfo.getDomainUrl()+"EditUserProfile/apiUpdateUserProfile.php" let parameter = [ "fldAppUserID" : fldAppUserID, "fldAppUserFirstName" : fldAppUserFirstName , "fldAppUserLastName" : fldAppUserLastName, "fldAppUserPhone" : fldAppUserPhone ] print(parameter) Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .failure(let error): completion(error, false, nil ) print(error) case .success(let value): let json = JSON(value) let message = json["message"].string var rss = [res]() let rs = res() rs.message = message! rss.append(rs) completion(nil, true , rss) } } } class func changeUserToPlayer(fldAppUserID: String ,completion: @escaping (_ error: Error?, _ success: Bool ,_ sendUpdatePlayerPage: [res]? )->Void){ let url = DomainInfo.getDomainUrl()+"PlayerOperations/apiChangeUserToPlayer.php" let parameter = [ "fldAppUserID" : fldAppUserID ] print(parameter) Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .failure(let error): completion(error, false , nil) print(error) case .success(let value): let json = JSON(value) let message = json["message"].string let fldAppPlayerID = json["fldAppPlayerID"] helper.saveMyPlayerId(MyPlayerId: "\(fldAppPlayerID)") print(helper.getMyPlayerId() ?? "no player id") var rss = [res]() let rs = res() rs.message = message! rss.append(rs) completion(nil , true, rss) } } } class func updatePlayerPage(fldAppUserID: String, fldAppUserFirstName: String,fldAppUserLastName: String, fldAppUserPhone: String ,fldAppPlayerSkills : String , completion: @escaping (_ error: Error?, _ success: Bool,_ updatePlayerPage: [res]?)->Void){ let url = DomainInfo.getDomainUrl()+"EditUserProfile/apiUpdatePlayerProfile.php" let parameter = [ "fldAppUserID" : fldAppUserID, "fldAppUserFirstName" : fldAppUserFirstName , "fldAppUserLastName" : fldAppUserLastName, "fldAppUserPhone" : fldAppUserPhone , "fldAppPlayerSkills" : fldAppPlayerSkills ] print(parameter) Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .failure(let error): completion(error, false , nil) print(error) case .success(let value): let json = JSON(value) print(helper.getMyPlayerId() ?? "no player id") let message = json["message"].string var rss = [res]() let rs = res() rs.message = message! rss.append(rs) completion(nil, true , rss) } } } class func changePlayerStatusToNotAvailalbe(fldAppPlayerID: String ,completion: @escaping (_ error: Error?, _ success: Bool , _ changePlayerStatus: [res]? )->Void){ let url = DomainInfo.getDomainUrl()+"PlayerOperations/apiChangePlayerStatusToNotAvailable.php" let parameter = [ "fldAppPlayerID" : fldAppPlayerID ] print(parameter) Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .failure(let error): completion(error, false , nil) print(error) case .success(let value): let json = JSON(value) let message = json["message"].string var rss = [res]() let rs = res() rs.message = message! rss.append(rs) completion(nil ,true , rss) } } } class func changePlayerStatusToAvailable(fldAppPlayerID: String ,completion: @escaping (_ error: Error?, _ success: Bool ,_ changePlayerStatus: [res]? )->Void){ let url = DomainInfo.getDomainUrl()+"PlayerOperations/apiChangePlayerStatusToAvailable.php" let parameter = [ "fldAppPlayerID" : fldAppPlayerID ] print(parameter) Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .failure(let error): completion(error, false , nil) print(error) case .success(let value): let json = JSON(value) let message = json["message"].string var rss = [res]() let rs = res() rs.message = message! rss.append(rs) completion(nil ,true , rss) } } } class func UploadProfilePhoto(fldAppPlayerProfilePhoto: UIImage, completion: @escaping (_ error: Error?, _ success: Bool , _ message : String? )->Void) { let url = URLs.URL_UPLOAD_USER_IMAGE guard let fldAppUserID = helper.getUserId() else { completion(nil, false , nil) return } let parameters: [String: String] = [ "fldAppUserID": fldAppUserID ] let size = CGSize(width: 150.0, height: 150.0) let imageResized : UIImage = fldAppPlayerProfilePhoto.resizeImage(targetSize: size) Alamofire.upload(multipartFormData: { (form: MultipartFormData) in for (key, value) in parameters { form.append(value.data(using: String.Encoding.utf8)! , withName: key) } if let data = UIImageJPEGRepresentation(imageResized, 1) { form.append( data.base64EncodedData() , withName: "fldAppPlayerProfileImage" , mimeType: "image/jpeg") } } , to: url , method : .post , headers : nil) { (result ) in switch result { case .failure(let error): print("--------------------------------") print(error) completion(error, false , nil) case .success(request: let upload, streamingFromDisk: _, streamFileURL: _): upload.uploadProgress(closure: { (progress: Progress) in print(progress) }) .responseJSON(completionHandler: { (response: DataResponse<Any>) in print("responseJSON") switch response.result { case .failure(let error): print("-----------error---------------") print(error) completion(error, false , nil) case .success(let value): let json = JSON(value) print("----------json--------------") print(json) let status = json["message"].string print(status as Any) if (status == "Image Uploaded") { print("Upload Succeed") completion(nil, true , status) } else { print("Upload Failed") completion(nil, false , "upload failed") } } }) } } } class func UploadGalleryPhoto(fldAppPlayerGalleryPhoto: UIImage, completion: @escaping (_ error: Error?, _ success: Bool , _ message : String?)->Void) { let url = URLs.UPLOAD_PLAYER_IMAGE_GALLERY_URL let fldAppPlayerID = helper.getMyPlayerId()! let parameters: [String: String] = [ "fldAppPlayerID": fldAppPlayerID ] let size = CGSize(width: 300.0, height: 300.0) let imageResized : UIImage = fldAppPlayerGalleryPhoto.resizeImage(targetSize: size) Alamofire.upload(multipartFormData: { (form: MultipartFormData) in for (key, value) in parameters { form.append(value.data(using: String.Encoding.utf8)!, withName: key) } if let data = UIImageJPEGRepresentation(imageResized , 1) { form.append(data.base64EncodedData() , withName: "fldAppPlayerGalleryImage", mimeType: "image/jpeg") } }, to: url, method: .post , headers : nil) { (result) in switch result { case .failure(let error): print(error) completion(error, false , nil) case .success(request: let upload, streamingFromDisk: _, streamFileURL: _): upload.uploadProgress(closure: { (progress: Progress) in print(progress) }) .responseJSON(completionHandler: { (response: DataResponse<Any>) in print("responseJSON") switch response.result { case .failure(let error): print(error) completion(error, false , nil) case .success(let value): let json = JSON(value) print(json) let status = json["message"].string print(status) if (status == " Done") { completion(nil, true , status) } else { print("Upload Failed") completion(nil, false , "Upload Failed") } } }) } } } class func uploadVideo(Video: Data, completion: @escaping (_ error: Error?, _ success : Bool , _ message: String? )->Void) { let url = URLs.UPLOAD_PLAYER_VIDEO_URL let fldAppPlayerID = helper.getMyPlayerId()! print(fldAppPlayerID) //let videoName : String = fldAppPlayerID+".mp4" let parameters: [String: String] = [ "VideoName": fldAppPlayerID ] Alamofire.upload(multipartFormData: { (form: MultipartFormData) in for (key, value) in parameters { form.append(value.data(using: String.Encoding.utf8)!, withName: key) } form.append(Video.base64EncodedData() , withName: "Video", mimeType: "video/mp4") }, to: url, method: .post , headers : nil) { (result) in switch result { case .failure(let error): print(error) completion(error, false , nil) case .success(request: let upload, streamingFromDisk: _, streamFileURL: _): upload.uploadProgress(closure: { (progress: Progress) in print(progress) }) .responseJSON(completionHandler: { (response: DataResponse<Any>) in print("responseJSON") switch response.result { case .failure(let error): print(error) completion(error, false , nil) case .success(let value): let json = JSON(value) print(json) let status = json["message"].string print(status) completion(nil, true , status) if (status == "Video Uploaded Successfully ") { completion(nil, true , status) } else { print("Upload Failed") completion(nil, false , "Upload Failed") } } }) } } } }
import Foundation class AppConfigProvider: IAppConfigProvider { let companyWebPageLink = "https://horizontalsystems.io" let appWebPageLink = "https://unstoppable.money" let reportEmail = "hsdao@protonmail.ch" let telegramWalletHelpAccount = "UnstoppableWallet" var testMode: Bool { Bundle.main.object(forInfoDictionaryKey: "TestMode") as? String == "true" } var officeMode: Bool { Bundle.main.object(forInfoDictionaryKey: "OfficeMode") as? String == "true" } func defaultWords(count: Int) -> [String] { guard let wordsString = Bundle.main.object(forInfoDictionaryKey: "DefaultWords\(count)") as? String else { return [] } return wordsString.split(separator: " ", omittingEmptySubsequences: true).map(String.init) } var defaultEosCredentials: (String, String) { guard let account = Bundle.main.object(forInfoDictionaryKey: "DefaultEosAccount") as? String, let privateKey = Bundle.main.object(forInfoDictionaryKey: "DefaultEosPrivateKey") as? String else { return ("", "") } return (account, privateKey) } var infuraCredentials: (id: String, secret: String?) { let id = (Bundle.main.object(forInfoDictionaryKey: "InfuraProjectId") as? String) ?? "" let secret = Bundle.main.object(forInfoDictionaryKey: "InfuraProjectSecret") as? String return (id: id, secret: secret) } var btcCoreRpcUrl: String { (Bundle.main.object(forInfoDictionaryKey: "BtcCoreRpcUrl") as? String) ?? "" } var etherscanKey: String { (Bundle.main.object(forInfoDictionaryKey: "EtherscanApiKey") as? String) ?? "" } var coinMarketCapApiKey: String { (Bundle.main.object(forInfoDictionaryKey: "CoinMarketCapKey") as? String) ?? "" } let currencyCodes: [String] = ["USD", "EUR", "GBP", "JPY"] var featuredCoins: [Coin] { [ defaultCoins[0], defaultCoins[1], defaultCoins[2], defaultCoins[3], defaultCoins[4], defaultCoins[5], defaultCoins[6], ] } let defaultCoins = [ Coin(id: "BTC", title: "Bitcoin", code: "BTC", decimal: 8, type: .bitcoin), Coin(id: "LTC", title: "Litecoin", code: "LTC", decimal: 8, type: .litecoin), Coin(id: "ETH", title: "Ethereum", code: "ETH", decimal: 18, type: .ethereum), Coin(id: "BCH", title: "Bitcoin Cash", code: "BCH", decimal: 8, type: .bitcoinCash), Coin(id: "DASH", title: "Dash", code: "DASH", decimal: 8, type: .dash), Coin(id: "BNB", title: "Binance DEX", code: "BNB", decimal: 8, type: .binance(symbol: "BNB")), Coin(id: "EOS", title: "EOS", code: "EOS", decimal: 4, type: .eos(token: "eosio.token", symbol: "EOS")), Coin(id: "ZRX", title: "0x Protocol", code: "ZRX", decimal: 18, type: CoinType(erc20Address: "0xE41d2489571d322189246DaFA5ebDe1F4699F498")), Coin(id: "ELF", title: "Aelf", code: "ELF", decimal: 18, type: CoinType(erc20Address: "0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e")), Coin(id: "ANKR", title: "Ankr Network", code: "ANKR", decimal: 8, type: .binance(symbol: "ANKR-E97")), Coin(id: "ANT", title: "Aragon", code: "ANT", decimal: 18, type: CoinType(erc20Address: "0x960b236A07cf122663c4303350609A66A7B288C0")), Coin(id: "BNT", title: "Bancor", code: "BNT", decimal: 18, type: CoinType(erc20Address: "0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C")), Coin(id: "BAT", title: "Basic Attention Token", code: "BAT", decimal: 18, type: CoinType(erc20Address: "0x0D8775F648430679A709E98d2b0Cb6250d2887EF")), Coin(id: "BNB-ERC20", title: "Binance ERC20", code: "BNB", decimal: 18, type: CoinType(erc20Address: "0xB8c77482e45F1F44dE1745F52C74426C631bDD52")), Coin(id: "BUSD", title: "Binance USD", code: "BUSD", decimal: 8, type: .binance(symbol: "BUSD-BD1")), Coin(id: "BTCB", title: "Bitcoin BEP2", code: "BTCB", decimal: 8, type: .binance(symbol: "BTCB-1DE")), Coin(id: "CAS", title: "Cashaa", code: "CAS", decimal: 8, type: .binance(symbol: "CAS-167")), Coin(id: "LINK", title: "Chainlink", code: "LINK", decimal: 18, type: CoinType(erc20Address: "0x514910771AF9Ca656af840dff83E8264EcF986CA")), Coin(id: "CVC", title: "Civic", code: "CVC", decimal: 8, type: CoinType(erc20Address: "0x41e5560054824ea6b0732e656e3ad64e20e94e45")), Coin(id: "CRPT", title: "Crypterium", code: "CRPT", decimal: 8, type: .binance(symbol: "CRPT-8C9")), Coin(id: "MCO", title: "MCO", code: "MCO", decimal: 8, type: CoinType(erc20Address: "0xB63B606Ac810a52cCa15e44bB630fd42D8d1d83d")), Coin(id: "CRO", title: "Crypto.com Coin", code: "CRO", decimal: 8, type: CoinType(erc20Address: "0xA0b73E1Ff0B80914AB6fe0444E65848C4C34450b")), Coin(id: "DAI", title: "Dai", code: "DAI", decimal: 18, type: CoinType(erc20Address: "0x6b175474e89094c44da98b954eedeac495271d0f")), Coin(id: "MANA", title: "Decentraland", code: "MANA", decimal: 18, type: CoinType(erc20Address: "0x0F5D2fB29fb7d3CFeE444a200298f468908cC942")), Coin(id: "DGD", title: "DigixDAO", code: "DGD", decimal: 9, type: CoinType(erc20Address: "0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A")), Coin(id: "DGX", title: "Digix Gold Token", code: "DGX", decimal: 9, type: CoinType(erc20Address: "0x4f3AfEC4E5a3F2A6a1A411DEF7D7dFe50eE057bF", minimumSpendableAmount: 0.001)), Coin(id: "DNT", title: "District0x", code: "DNT", decimal: 18, type: CoinType(erc20Address: "0x0abdace70d3790235af448c88547603b945604ea")), Coin(id: "ENJ", title: "Enjin Coin", code: "ENJ", decimal: 18, type: CoinType(erc20Address: "0xF629cBd94d3791C9250152BD8dfBDF380E2a3B9c")), Coin(id: "EOSDT", title: "EOSDT", code: "EOSDT", decimal: 9, type: .eos(token: "eosdtsttoken", symbol: "EOSDT")), Coin(id: "IQ", title: "Everipedia", code: "IQ", decimal: 3, type: .eos(token: "everipediaiq", symbol: "IQ")), Coin(id: "GUSD", title: "Gemini Dollar", code: "GUSD", decimal: 2, type: CoinType(erc20Address: "0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd")), Coin(id: "GTO", title: "Gifto", code: "GTO", decimal: 8, type: .binance(symbol: "GTO-908")), Coin(id: "GNT", title: "Golem", code: "GNT", decimal: 18, type: CoinType(erc20Address: "0xa74476443119A942dE498590Fe1f2454d7D4aC0d")), Coin(id: "HOT", title: "Holo", code: "HOT", decimal: 18, type: CoinType(erc20Address: "0x6c6EE5e31d828De241282B9606C8e98Ea48526E2")), Coin(id: "HT", title: "Huobi Token", code: "HT", decimal: 18, type: CoinType(erc20Address: "0x6f259637dcD74C767781E37Bc6133cd6A68aa161")), Coin(id: "IDXM", title: "IDEX Membership", code: "IDXM", decimal: 8, type: CoinType(erc20Address: "0xCc13Fc627EFfd6E35D2D2706Ea3C4D7396c610ea")), Coin(id: "IDEX", title: "IDEX", code: "IDEX", decimal: 18, type: CoinType(erc20Address: "0xB705268213D593B8FD88d3FDEFF93AFF5CbDcfAE")), Coin(id: "KCS", title: "KuCoin Shares", code: "KCS", decimal: 6, type: CoinType(erc20Address: "0x039B5649A59967e3e936D7471f9c3700100Ee1ab", minimumRequiredBalance: 0.001)), Coin(id: "KNC", title: "Kyber Network Crystal", code: "KNC", decimal: 18, type: CoinType(erc20Address: "0xdd974D5C2e2928deA5F71b9825b8b646686BD200")), Coin(id: "LOOM", title: "Loom Network", code: "LOOM", decimal: 18, type: CoinType(erc20Address: "0xA4e8C3Ec456107eA67d3075bF9e3DF3A75823DB0")), Coin(id: "LRC", title: "Loopring", code: "LRC", decimal: 18, type: CoinType(erc20Address: "0xEF68e7C694F40c8202821eDF525dE3782458639f")), Coin(id: "MKR", title: "Maker", code: "MKR", decimal: 18, type: CoinType(erc20Address: "0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2")), Coin(id: "MEETONE", title: "MEET.ONE", code: "MEETONE", decimal: 4, type: .eos(token: "eosiomeetone", symbol: "MEETONE")), Coin(id: "MITH", title: "Mithril", code: "MITH", decimal: 18, type: CoinType(erc20Address: "0x3893b9422Cd5D70a81eDeFfe3d5A1c6A978310BB")), Coin(id: "NUT", title: "Native Utility Token", code: "NUT", decimal: 9, type: .eos(token: "eosdtnutoken", symbol: "NUT")), Coin(id: "NDX", title: "Newdex", code: "NDX", decimal: 4, type: .eos(token: "newdexissuer", symbol: "NDX")), Coin(id: "NEXO", title: "Nexo", code: "NEXO", decimal: 18, type: CoinType(erc20Address: "0xB62132e35a6c13ee1EE0f84dC5d40bad8d815206")), Coin(id: "OMG", title: "OmiseGO", code: "OMG", decimal: 18, type: CoinType(erc20Address: "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07")), Coin(id: "ORBS", title: "Orbs", code: "ORBS", decimal: 18, type: CoinType(erc20Address: "0xff56Cc6b1E6dEd347aA0B7676C85AB0B3D08B0FA")), Coin(id: "OXT", title: "Orchid", code: "OXT", decimal: 18, type: CoinType(erc20Address: "0x4575f41308EC1483f3d399aa9a2826d74Da13Deb")), Coin(id: "PAX", title: "Paxos Standard", code: "PAX", decimal: 18, type: CoinType(erc20Address: "0x8E870D67F660D95d5be530380D0eC0bd388289E1")), Coin(id: "PAXG", title: "PAX Gold", code: "PAXG", decimal: 18, type: CoinType(erc20Address: "0x45804880De22913dAFE09f4980848ECE6EcbAf78")), Coin(id: "PTI", title: "Paytomat", code: "PTI", decimal: 4, type: .eos(token: "ptitokenhome", symbol: "PTI")), Coin(id: "POLY", title: "Polymath", code: "POLY", decimal: 18, type: CoinType(erc20Address: "0x9992eC3cF6A55b00978cdDF2b27BC6882d88D1eC")), Coin(id: "PPT", title: "Populous", code: "PPT", decimal: 8, type: CoinType(erc20Address: "0xd4fa1460F537bb9085d22C7bcCB5DD450Ef28e3a")), Coin(id: "PGL", title: "Prospectors Gold", code: "PGL", decimal: 4, type: .eos(token: "prospectorsg", symbol: "PGL")), Coin(id: "NPXS", title: "Pundi X", code: "NPXS", decimal: 18, type: CoinType(erc20Address: "0xA15C7Ebe1f07CaF6bFF097D8a589fb8AC49Ae5B3")), Coin(id: "REP", title: "Augur", code: "REP", decimal: 18, type: CoinType(erc20Address: "0x1985365e9f78359a9B6AD760e32412f4a445E862")), Coin(id: "R", title: "Revain", code: "R", decimal: 0, type: CoinType(erc20Address: "0x48f775EFBE4F5EcE6e0DF2f7b5932dF56823B990")), Coin(id: "XRP", title: "Ripple", code: "XRP", decimal: 8, type: .binance(symbol: "XRP-BF2")), Coin(id: "SAI", title: "Sai", code: "SAI", decimal: 18, type: CoinType(erc20Address: "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359")), Coin(id: "SNX", title: "Synthetix", code: "SNX", decimal: 18, type: CoinType(erc20Address: "0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F")), Coin(id: "EURS", title: "STASIS EURO", code: "EURS", decimal: 2, type: CoinType(erc20Address: "0xdB25f211AB05b1c97D595516F45794528a807ad8")), Coin(id: "SNT", title: "Status", code: "SNT", decimal: 18, type: CoinType(erc20Address: "0x744d70FDBE2Ba4CF95131626614a1763DF805B9E")), Coin(id: "CHSB", title: "SwissBorg", code: "CHSB", decimal: 8, type: CoinType(erc20Address: "0xba9d4199fab4f26efe3551d490e3821486f135ba")), Coin(id: "USDT", title: "Tether USD", code: "USDT", decimal: 6, type: CoinType(erc20Address: "0xdAC17F958D2ee523a2206206994597C13D831ec7")), Coin(id: "TUSD", title: "TrueUSD", code: "TUSD", decimal: 18, type: CoinType(erc20Address: "0x0000000000085d4780B73119b644AE5ecd22b376")), Coin(id: "USDC", title: "USD Coin", code: "USDC", decimal: 6, type: CoinType(erc20Address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")), Coin(id: "WTC", title: "Waltonchain", code: "WTC", decimal: 18, type: CoinType(erc20Address: "0xb7cB1C96dB6B22b0D3d9536E0108d062BD488F74")), Coin(id: "WBTC", title: "Wrapped Bitcoin", code: "WBTC", decimal: 8, type: CoinType(erc20Address: "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599")), Coin(id: "WETH", title: "Wrapped Ethereum", code: "WETH", decimal: 18, type: CoinType(erc20Address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")), ] }
import UIKit public extension UIImage { static func image(named file: String) -> UIImage { do { let image = try Data(contentsOf: Bundle.main.url(forResource: "\(file)Icon", withExtension: "png", subdirectory: "Icons")!) return UIImage(data: image)! } catch { return UIImage() } } static func image(neon file: String) -> UIImage { do { let image = try Data(contentsOf: Bundle.main.url(forResource: "\(file)Neon", withExtension: "jpg", subdirectory: "Neons")!) return UIImage(data: image)! } catch { return UIImage() } } func getPixelColor(pos: CGPoint) -> UIColor { let pixelData = self.cgImage!.dataProvider!.data let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4 let r = CGFloat(data[pixelInfo]) / CGFloat(255.0) let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0) let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0) let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0) return UIColor(red: r, green: g, blue: b, alpha: a) } }
// Human import UIKit class BodyPart { let circulatorySystem = ("veins", "arteries", "capillaries") let blood = ("Erythrocytes", "Leukocytes", "Platelets", "Plasma") var hasO2 = 0 var concentO2 = 0 var timeWithoutO2 = 0 //in minutes var hasEnergy = false init(concent02: Int, timeWithoutO2: Int) { if concentO2 < 50 && timeWithoutO2 <= 1 { cellResp() } else if concentO2 < 50 && concentO2 > 0 && timeWithoutO2 <= 4 { hypoxia() } else { cellDeath() } } func cellResp() { //perform cellular respiration //C6H12O6 + 6O2 -> 6CO2 + 6H2O + ENERGY hasEnergy = true muscle(hasEnergy) } func hypoxia() { //low oxygen concentration //hypoxia } func muscle(hasEnergy : Bool) { //perform muscle contraction } func cellDeath() { //cellular death //necrosis } } class RespiratorySystem : BodyPart { } class Diaphragm : RespiratorySystem { let openings = ["Caval", "Esophageal", "Aortic", ] let nerves = ["C3", "C4", "C5"] let arterialBldSp = [ "Internal Thoracic", "Superior Phrenic", "Internal Intercostal" ] let location = "Base of Thorax" func diaRelax() { //expiration } func diaContract() { //inspiration } func forcedDiaRelax() { //forced expiration, assisted by abdominal and intercostal muscles } } class Lungs : RespiratorySystem { let sections = ["Bronchus", "Bronchioles", "Alveoli", "Right Lobe", "Left Lobe"] let nerves = ["Pulmonary Plexus", "Phrenic nerve"] let arterialBldSp = ["Bronchial Circulation"] let location = "Upper Thorax" func O2diffusion() { //through capillaries in alveoli } func mucusProd() { } func bpRegulaton() { } } class GITract : BodyPart { } class Mouth : GITract { var toothNum = 32 //more or less let wisToothNum = 0 //preferably let sections = ["Lips", "Teeth", "Tongue", "Palate", "Oral Cavity"] let nerves = [ "Trigeminal", "Facial", "Glossopharyngeal", "Vagus", "Hypoglossus" ] let arterialBldSp = ["External Carotid", "Facial",] let location = "Front of Head" func mastication() { } func mouRespiration() { } func salProd() { } } class Stomach : GITract { let stCapacity = 45...75 //in ml let sections = ["Cardia", "Fundus", "Body", "Pylorus"] let arterialBldSp = [ "Right Gastric", "Left Gastric", "Right Gastro-omental", "Left Gastro-omental", "Short Gastric", ] let location = "Left Upper Abdomen" func stDigestion() { } func stAbsorption() { } func stProdAcid() { } } class SmallIntestine : GITract { let diameter = 2...3 //in cm let surfaceArea = 30 // in m let sections = ["Duodenum", "Jejunum", "Ileum"] let arterialBldSp = ["Coeliac Trunk", "Superior Mesenteric "] let location = "Mid Abdomen" func siDigestion() { } func siAbsorption() { } func siImmune() { } } class NervousSystem : BodyPart { } class CenNervSys : NervousSystem { } class Brain : CenNervSys { let sections = [ "Frontal Lobe", "Parietal Lobe", "Occiptal Lobe", "Temporal Lobe", "Cerebellum" ] let location = "Skull" let size = 1130...1260 //in cm^3 func language() { } func cognition() { } func passSigToPNS() { PeripheralNervSys() } } class SpinalCord : CenNervSys { let sections = ["Cervical", "Thoracic", "Lumbar", "Sacral", "Coccygeal"] let avgLength = 43...45 let location = "Along the spinal column" func somatoSensOrg() { } func motorOrg() { } func spinoCerebTr() { } } class PeripheralNervSys: NervousSystem { let sections = [ "Cervical Spinal Nerves", "Brachial Plexus", "Lumbosacral Plexus", ] let location = "Throughout the body and all extremeties" let neurotransmitters = ["Acetylcholine", "Noradrenaline"] func bodySysControl() { } func touch() { } func heatSens() { } } class Head : BodyPart { } class Eye : Head //inherits properties of BodyPart, but can have its own properties { let sections = [ "Iris", "Pupil", "Lens", ] let location = "The orbits of the skull" let irisColor = "Brown" func vision() { } func pupilSize() { } func focus() { } } class Nose : Head { let sections = ["Nasal Root", "Anterior Nasal Spine", "Anterior Nasal Passage"] let sectionInterior = ["Olfactory Bulb", "Olfactory Tract", "Nasal Cavity"] let nerves = ["C1"] func smell() { } func sniff() { } func sneeze() { } } class Ear : Head { let outerEar = [ "Auricle", "Ear Canal", "Tympanic Membrane" ] let midEar = [ "Tensor Tympani", "Tympanic Cavity", "Malleus" ] let innerEar = [ "Vestibule", "Saccule", "Cochlea" ] func hearing() { } func balance() { } func vertigo() { //not a good thing } } class Arm : BodyPart { let sections = ["Upper Arm", "Forearm", "Hand"] let bones = ["Humerus", "Ulna", "Radius", "Elbow Joint"] let arterialBldSp = ["Brachial Artery"] let nerves = ["Musculocutaneous"] func flexion() { } func extens() { } func rotation() { } } class Hand : Arm { let handParts = ["Wrist", "Back", "Palm"] let handBones = ["Metacarpals", "Carpals"] let handNerves = ["Radial", "Median", "Ulnar"] func palmAbduction() { } func anteposition() { } func radialAbduction() { } } class Finger : Hand { let fingerParts = ["Thumb", "Index", "Middle", "Ring", "Pinky"] let fingerBones = ["Proximal Phalanges", "Intermediate Phalanges", "Distal Phalanges"] let fingerTendons = ["Extensor Tendon", "Flexor Digitorum Superficialis Tendon", "Flexor Digitorum Profundus Tendon"] override func flexion() { } func extes() { } func adduction() { } func abduction() { } } class Leg : BodyPart { let legParts = ["Thigh", "Knee", "Shin"] let legBones = ["Femur", "Patella", "Tibia", "Fibula"] let legNerves = [ "Common Peroneal", "Common Plantar", "Lateral Plantar", "Medial Plantar" ] func flexion() { } func extes() { } func adduction() { } func abduction() { } } class Foot : Leg { let footParts = ["Ankle", "Heel", "Instep", "Ball"] let footBones = ["Talus", "Tarsal", "Calcaneus", "Metatarsals"] let footNerves = ["Lateral Planar", "Medial Plantar", "Posterior Tibial"] func dorsiflexion() { } func plantarFlexion() { } func eversion() { } func inversion() { } } class CirculatorySystem : BodyPart { } class CardioSystem : CirculatorySystem { } class LymphSystem: CirculatorySystem { } class Heart: CardioSystem { let sections = ["Left Atrium", "Right Atrium", "Left Ventricle", "Right Ventricle"] let arterialBldSp = ["Pulmonary Vein"] let nerves = ["Vagus", "Spinal Ganglionic"] let location = "Left Upper Thorax" var elecImpulse = 0 func cardiacCycle() { if elecImpulse == 0 { systole() } else if elecImpulse == 1 { diastole()//this is definitely how the heart works in real life } } func systole() { ventricleContract() } func diastole() { ventricleRelax() } func ventricleContract() { } func ventricleRelax() { } } class Thymus: LymphSystem { let sections = ["Cortex", "Medulla",] let arterialBldSp = ["Internal Thoracic", ] let nerves = ["Vagi derivation", "Descendens Hypoglossi branch", "Phrenic branch"] let location = "Mid Upper Thorax" func thymosinProd() { } func thymopoietinProd() { } func tCellMaturation() { } } class Spleen: LymphSystem { let sections = ["Phrenic", "Visceral"] let arterialBldSp = ["Splenic"] let nerves = ["Splenic Plexus"] let location = "Left Lower Thorax" func rbcFilt() { } func immunResponse() { } func rbcStor() { } } class LymphNode: LymphSystem { let sections = ["Cortex", "Medulla", "Cortex"] let location = ["Underarm", "Groin", "Neck", "Abdomen"] let length = 1...2 //in cm func lymphFluidStor() { } func lymphFiltration() { } func lymphDrain() { } }
// // Meal.swift // eggplant-brownie // // Created by Paulo Rodrigues on 22/03/21. // Copyright © 2021 Paulo Rodrigues. All rights reserved. // import UIKit class Meal: NSObject { let name: String let happy: Int var items: Array<Item> = [] init(name: String, happy: Int, items: [Item] = []) { self.name = name self.happy = happy self.items = items } func totalOfCalories() -> Double { var total: Double = 0.0 for item in items { total += item.calories } return total } }
// // ViewController.swift // D4.L10 - Actions & Outlets Lesson // // Created by Mark Cheng on 4/12/20. // Copyright © 2020 KWK. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textAppearsHere: UILabel! @IBOutlet weak var typeTextHere: UITextField! @IBAction func submitButton(_ sender: UIButton) { if let data2display = typeTextHere.text { textAppearsHere.text = data2display } else { return } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
// // ViewController.swift // MCFinalProject // // Created by Son D. Ngo on 4/17/16. // Copyright © 2016 Son D. Ngo. All rights reserved. // import UIKit import CoreData //THIS FILE IS FOR TESTING PURPOSE ONLY! class BookDatabaseController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var bookTableView: UITableView! var bookLibrary = [NSManagedObject]() @IBAction func addBookItem(sender: UIBarButtonItem) { let alert = UIAlertController(title: "New Book", message: "Add a new book", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Save", style: .Default, handler: { (action:UIAlertAction) -> Void in let bookItem = Book() let authorField = alert.textFields![0] let titleField = alert.textFields![1] let genreField = alert.textFields![2] bookItem.author = authorField.text! bookItem.title = titleField.text! bookItem.genre = genreField.text! self.saveName(bookItem) self.bookTableView.reloadData() }) let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in } alert.addTextFieldWithConfigurationHandler { (authorField: UITextField) -> Void in authorField.placeholder = "author" } alert.addTextFieldWithConfigurationHandler { (titleField: UITextField) -> Void in titleField.placeholder = "book title" } alert.addTextFieldWithConfigurationHandler { (genreField: UITextField) -> Void in genreField.placeholder = "genre" } alert.addAction(saveAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() title = "\"Core Data Book List\"" bookTableView.estimatedRowHeight = 44.0 bookTableView.rowHeight = UITableViewAutomaticDimension // self.bookTableView.registerClass(BookTableViewCell.self, // forCellReuseIdentifier: "bookCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext //2 let fetchRequest = NSFetchRequest(entityName: "Book") //3 do { let results = try managedContext.executeFetchRequest(fetchRequest) bookLibrary = results as! [NSManagedObject] } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } //Replace both UITableViewDataSource methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //print("table rows: \(bookLibrary.count)") return bookLibrary.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("bookCell") as! BookTableViewCell let bookItem = bookLibrary[indexPath.row] if let cellName = cell.name { cellName.text = bookItem.valueForKey("title") as? String } if let cellAuthor = cell.author { cellAuthor.text = bookItem.valueForKey("author") as? String } if let cellGenre = cell.genre { cellGenre.text = bookItem.valueForKey("genre") as? String } return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext managedContext.deleteObject(bookLibrary[indexPath.row]) appDelegate.saveContext() bookLibrary.removeAtIndex(indexPath.row) // bookTableView.reloadData() bookTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } func saveName(item: Book) { //1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext //2 let entity = NSEntityDescription.entityForName("Book", inManagedObjectContext: managedContext) let bookItem = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) //3 bookItem.setValue(item.author, forKey: "author") bookItem.setValue(item.title, forKey: "title") bookItem.setValue(item.genre, forKey: "genre") //4 do { try managedContext.save() bookLibrary.append(bookItem) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } }
// // BookingTableViewC.swift // IDine // // Created by App on 04/12/18. // Copyright © 2018 appventurez. All rights reserved. // import UIKit class BookingTableViewC: UIViewController { //MARK:- Properties var dataArr = [[String : AnyObject]]() //MARK:- IBOutlet @IBOutlet weak var tblView: UITableView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var lblResturantOpenTime: UILabel! @IBOutlet weak var lblResturantAddress: UILabel! @IBOutlet weak var lblResturantName: UILabel! @IBOutlet weak var imgView: UIImageView! //MARK:- Life Cycle override func viewDidLoad() { super.viewDidLoad() registerNib() } //MARK:- Private Method func registerNib() { let nib = UINib(nibName: "OfferCell", bundle: nil) self.collectionView.register(nib, forCellWithReuseIdentifier: "OfferCell") let tblNib = UINib(nibName: "BookingTableCell", bundle: nil) self.tblView.register(tblNib, forCellReuseIdentifier: "BookingTableCell") loadData() } func loadData() { let tblDict = ["resturant": "Coral" as AnyObject, "offer": "20% off on Fodd Bill Valid only on Inhouse dining" as AnyObject, "image": #imageLiteral(resourceName: "HomeImage1") as AnyObject] let tblDict2 = ["resturant": "Mykonos" as AnyObject, "offer": "20% off on Fodd Bill Valid only on Inhouse dining" as AnyObject, "image": #imageLiteral(resourceName: "HomeImage2") as AnyObject] let tblDict3 = ["resturant": "Tea Lounge" as AnyObject, "offer": "20% off on Fodd Bill Valid only on Inhouse dining" as AnyObject, "image": #imageLiteral(resourceName: "HomeImage3") as AnyObject] dataArr.append(contentsOf: [tblDict, tblDict2, tblDict3]) self.tblView.reloadData() self.collectionView.reloadData() } func moveToBooking() { let sb = UIStoryboard(name: "Main", bundle: nil) if let bookingViewc = sb.instantiateViewController(withIdentifier: "TableBookDetailsViewC") as? TableBookDetailsViewC { self.navigationController?.pushViewController(bookingViewc, animated: true) } } //MARK:- Public Method //MARK:- IBAction @IBAction func tapBookNow(_ sender: Any) { moveToBooking() } @IBAction func tapDownload(_ sender: Any) { } @IBAction func tapBackButton(_ sender: Any) { self.navigationController?.popViewController(animated: true) } } //MARK:- Extension extension BookingTableViewC: UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource { //MARK:- Table View Delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = self.tblView.dequeueReusableCell(withIdentifier: "BookingTableCell", for: indexPath) as? BookingTableCell { return cell } return UITableViewCell() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArr.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "OfferCell", for: indexPath) as? OfferCell { let dict = dataArr[indexPath.row] if let name = dict["resturant"] as? String { cell.lblResturant.text = name } if let offer = dict["offer"] as? String { cell.lblOfferDescription.text = offer } if let image = dict["image"] as? UIImage { cell.imgView.image = image } return cell } return UICollectionViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 518.0 } //MARK:- Collection View Delegate func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 356, height: 152) } }
// // ContentViewController.swift // YSMSandbox // // Created by duanzengguang on 2020/4/4. // import UIKit class ContentViewController: UIViewController { var textView: UITextView = UITextView(frame: .zero) var document: Document! override func viewDidLoad() { super.viewDidLoad() textView.frame = view.bounds view.addSubview(textView) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .done, target: self, action: #selector(dissmissAction)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) fatchData() } } extension ContentViewController{ func fatchData() { DispatchQueue.global().async { guard let fileContent = try? String(contentsOfFile: self.document.fullPath, encoding: .utf8) else {return} DispatchQueue.main.async { self.textView.text = fileContent } } } @objc func dissmissAction() { dismiss(animated: true, completion: nil) } }
// // StudentinfoViewController.swift // StudentApp // // Created by Naguru Abdur,Rehaman on 3/24/22. // import UIKit class StudentInfoViewController: UIViewController { @IBOutlet weak var SIDOutlet: UILabel! @IBOutlet weak var emailOutlet: UILabel! @IBOutlet weak var nameOutlet: UILabel! @IBOutlet weak var courseOutlet: UIButton! //variable created to hold the Student object we recieve from the LoginController var studentObj = Student() var guestUser:Bool = false override func viewDidLoad() { super.viewDidLoad() if guestUser { //if the user is guest we will hide all the outlets and display 'Guest User' emailOutlet.isHidden = true nameOutlet.text = "Name: Guest User" SIDOutlet.isHidden = true courseOutlet.isHidden = true }else{ //If the student is found, then we assign the values of the studentObj to the outelts SIDOutlet.text = "SID: " + studentObj.sid emailOutlet.text = "Email: " + studentObj.email nameOutlet.text = "Name: " + studentObj.name } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let transition = segue.identifier //We need to view courses of the logged in student in CourseViewController, // So we pass the courses from the 'studentObj' variable if transition == "courseSegue" { let destination = segue.destination as! CourseViewController //we will assign the courses to 'courseArray' in the CourseViewController destination.coursesArray = studentObj.courses } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // TWButton.swift // // The MIT License (MIT) // // Created by Txai Wieser on 25/02/15. // Copyright (c) 2015 Txai Wieser. // // //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 SpriteKit protocol TWControlDelegate: class { func controlValueChanged(control:TWControl) } class TWControl: SKSpriteNode { // MARK: Nested Types enum TWControlState: Int { case Normal = 0 case Highlighted = 1 case Selected = 2 case Disabled = 3 } enum TWControlType { case Texture case Color case Label } // Mark: Public Properties internal weak var delegate:TWControlDelegate! internal var boundsTolerance:CGFloat? internal var tag:Int? internal var isOn:Bool = false internal var enabled:Bool { get { return self.state != .Disabled } set { if newValue { self.state = .Normal self.userInteractionEnabled = true } else { self.state = .Disabled self.userInteractionEnabled = false } updateVisualInterface() } } internal var selected:Bool { get { return self.state == .Selected } set { if newValue { self.state = .Selected } else { self.state = .Normal } updateVisualInterface() } } internal var highlighted:Bool { get { return self.state == .Highlighted } set { if newValue { self.state = .Highlighted } else { self.state = .Normal } updateVisualInterface() } } // MARK: Customization Properties internal static var defaultTouchDownSoundFileName:String? internal static var defaultTouchUpSoundFileName:String? internal var touchDownSoundFileName:String? internal var touchUpSoundFileName:String? // TYPE Color Customizations internal var stateDisabledColor:SKColor! { didSet { updateVisualInterface() } } internal var stateHighlightedColor:SKColor! { didSet { updateVisualInterface() } } internal var stateNormalColor:SKColor! { didSet { updateVisualInterface() } } internal var stateSelectedColor:SKColor! { didSet { updateVisualInterface() } } // TYPE Texture Customizations internal var stateDisabledTexture:SKTexture! { didSet { updateVisualInterface() } } internal var stateHighlightedTexture:SKTexture! { didSet { updateVisualInterface() } } internal var stateNormalTexture:SKTexture! { didSet { updateVisualInterface() } } internal var stateSelectedTexture:SKTexture! { didSet { updateVisualInterface() } } // TEXT Labels Customizations internal var stateDisabledLabelText:String? { didSet { if stateDisabledLabelText != nil { stateDisabledLabel.text = stateDisabledLabelText! } } } internal var stateHighlightedLabelText:String? { didSet { if stateHighlightedLabelText != nil { stateHighlightedLabel.text = stateHighlightedLabelText! } } } internal var stateNormalLabelText:String? { didSet { if stateNormalLabelText != nil { stateNormalLabel.text = stateNormalLabelText! } } } internal var stateSelectedLabelText:String? { didSet { if stateSelectedLabelText != nil { stateSelectedLabel.text = stateSelectedLabelText! } } } internal var allStatesLabelText:String! { didSet { stateDisabledLabelText = allStatesLabelText stateHighlightedLabelText = allStatesLabelText stateNormalLabelText = allStatesLabelText stateSelectedLabelText = allStatesLabelText } } internal var stateDisabledFontColor:SKColor! { didSet { stateDisabledLabel.fontColor = stateDisabledFontColor } } internal var stateHighlightedFontColor:SKColor! { didSet { stateHighlightedLabel.fontColor = stateHighlightedFontColor } } internal var stateNormalFontColor:SKColor! { didSet { stateNormalLabel.fontColor = stateNormalFontColor } } internal var stateSelectedFontColor:SKColor! { didSet { stateSelectedLabel.fontColor = stateSelectedFontColor } } internal var allStatesFontColor:SKColor! { didSet { stateDisabledFontColor = allStatesFontColor stateHighlightedFontColor = allStatesFontColor stateNormalFontColor = allStatesFontColor stateSelectedFontColor = allStatesFontColor } } internal var allStatesLabelFontSize:CGFloat! { didSet { stateDisabledLabel.fontSize = allStatesLabelFontSize stateHighlightedLabel.fontSize = allStatesLabelFontSize stateNormalLabel.fontSize = allStatesLabelFontSize stateSelectedLabel.fontSize = allStatesLabelFontSize } } internal var allStatesLabelFontName:String! { didSet { stateDisabledLabel.fontName = allStatesLabelFontName stateHighlightedLabel.fontName = allStatesLabelFontName stateNormalLabel.fontName = allStatesLabelFontName stateSelectedLabel.fontName = allStatesLabelFontName } } // Labels Direct Access internal let stateDisabledLabel:SKLabelNode = { let l = SKLabelNode() l.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center l.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center return l }() internal let stateHighlightedLabel:SKLabelNode = { let l = SKLabelNode() l.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center l.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center return l }() internal let stateNormalLabel:SKLabelNode = { let l = SKLabelNode() l.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center l.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center return l }() internal let stateSelectedLabel:SKLabelNode = { let l = SKLabelNode() l.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center l.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center return l }() // MARK: Private Properties private let type:TWControlType private var state:TWControlState = .Normal private var eventClosures:[(event: UIControlEvents, closure: TWControl -> ())] = [] private var touch:UITouch? private var touchLocationLast:CGPoint? private var moved = false // MARK: Initializers init(normalTexture:SKTexture, highlightedTexture:SKTexture, selectedTexture:SKTexture, disabledTexture:SKTexture) { type = .Texture super.init(texture: normalTexture, color: nil, size: normalTexture.size()) self.userInteractionEnabled = true self.stateDisabledTexture = disabledTexture self.stateHighlightedTexture = highlightedTexture self.stateNormalTexture = normalTexture self.stateSelectedTexture = selectedTexture self.addChild(self.stateDisabledLabel) self.addChild(self.stateHighlightedLabel) self.addChild(self.stateNormalLabel) self.addChild(self.stateSelectedLabel) updateVisualInterface() } init(normalColor:SKColor, highlightedColor:SKColor, selectedColor:SKColor, disabledColor:SKColor, size:CGSize) { type = .Color super.init(texture: nil, color: normalColor, size: size) self.userInteractionEnabled = true self.stateDisabledColor = disabledColor self.stateHighlightedColor = highlightedColor self.stateNormalColor = normalColor self.stateSelectedColor = selectedColor self.addChild(self.stateDisabledLabel) self.addChild(self.stateHighlightedLabel) self.addChild(self.stateNormalLabel) self.addChild(self.stateSelectedLabel) updateVisualInterface() } init(normalText:String, highlightedText:String, selectedText:String, disabledText:String) { type = .Label super.init(texture: nil, color: SKColor.blackColor(), size: CGSizeZero) self.userInteractionEnabled = true self.stateDisabledLabel.text = disabledText self.stateHighlightedLabel.text = highlightedText self.stateNormalLabel.text = normalText self.stateSelectedLabel.text = selectedText self.addChild(self.stateDisabledLabel) self.addChild(self.stateHighlightedLabel) self.addChild(self.stateNormalLabel) self.addChild(self.stateSelectedLabel) updateVisualInterface() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Control Actions /** * Add a closure to a event action. You should use in your closure only the objects that are on the capture list of the closure (target)! Using objects capture automatically by the closure can cause cycle-reference, and your objects will never be deallocate. You have to be VERY CAREFUL! */ func addClosureFor<T: AnyObject>(event: UIControlEvents, target: T, closure: (target:T, sender:TWControl) -> ()) { self.eventClosures.append((event:event , closure: { [weak target] (ctrl: TWControl) -> () in if let obj = target { closure(target: obj, sender: ctrl) } return })) } private func removeClosuresFor(event:UIControlEvents) { assertionFailure("TODO: Implement Remove Target") } private func executeClosuresOf(event: UIControlEvents) { for eventClosure in eventClosures { if eventClosure.event == event { eventClosure.closure(self) } } } // MARK: Control Functionality private func updateVisualInterface() { switch type { case .Color: switch state { case .Disabled: self.color = self.stateDisabledColor case .Highlighted: self.color = self.stateHighlightedColor case .Normal: self.color = self.stateNormalColor case .Selected: self.color = self.stateSelectedColor } case .Texture: switch state { case .Disabled: self.texture = self.stateDisabledTexture self.size = self.texture!.size() case .Highlighted: self.texture = self.stateHighlightedTexture self.size = self.texture!.size() case .Normal: self.texture = self.stateNormalTexture self.size = self.texture!.size() case .Selected: self.texture = self.stateSelectedTexture self.size = self.texture!.size() } case .Label: break //Doesnt need to do nothing } stateDisabledLabel.alpha = 0 stateHighlightedLabel.alpha = 0 stateNormalLabel.alpha = 0 stateSelectedLabel.alpha = 0 switch state { case .Disabled: stateDisabledLabel.alpha = 1 case .Highlighted: stateHighlightedLabel.alpha = 1 case .Normal: stateNormalLabel.alpha = 1 case .Selected: stateSelectedLabel.alpha = 1 } } // Control Events internal func touchDown() { self.highlighted = true playSound(instanceSoundFileName: touchDownSoundFileName, defaultSoundFileName: self.dynamicType.defaultTouchDownSoundFileName) executeClosuresOf(.TouchDown) } internal func drag() {} internal func dragExit() { self.highlighted = false executeClosuresOf(.TouchDragExit) } internal func dragOutside() { executeClosuresOf(.TouchDragOutside) } internal func dragEnter() { self.highlighted = true executeClosuresOf(.TouchDragEnter) } internal func dragInside() { executeClosuresOf(.TouchDragInside) } internal func touchUpInside() { self.highlighted = false executeClosuresOf(.TouchUpInside) playSound(instanceSoundFileName: touchUpSoundFileName, defaultSoundFileName: self.dynamicType.defaultTouchUpSoundFileName) } internal func touchUpOutside() { executeClosuresOf(.TouchUpOutside) playSound(instanceSoundFileName: touchUpSoundFileName, defaultSoundFileName: self.dynamicType.defaultTouchUpSoundFileName) } // MARK: UIResponder Methods internal override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch let touchPoint = touch.locationInNode(self.parent) if self.containsPoint(touchPoint) { self.touch = touch self.touchLocationLast = touchPoint touchDown() } } internal override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch let touchPoint = touch.locationInNode(self.parent) drag() self.moved = true if self.containsPoint(touchPoint) { // Inside if let lastPoint = self.touchLocationLast where self.containsPoint(lastPoint) { // All along dragInside() } else { self.dragEnter() } } else { // Outside if let lastPoint = self.touchLocationLast where self.containsPoint(lastPoint) { // Since now dragExit() } else { // All along dragOutside() } } self.touchLocationLast = touchPoint } internal override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch let touchPoint = touch.locationInNode(self.parent) if self.moved { if let lastPoint = self.touchLocationLast where self.containsPoint(lastPoint) { // Ended inside touchUpInside() } else { // Ended outside touchUpOutside() } } else { // Needed?? touchUpInside() } self.moved = false } internal override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) { touchesEnded(touches, withEvent: event) } // ............................................................................. // MARK: Helpers private func playSound(#instanceSoundFileName:String?, defaultSoundFileName:String?) { if let soundFileName = instanceSoundFileName { let action = SKAction.playSoundFileNamed(soundFileName, waitForCompletion: true) self.runAction(action) } else if let soundFileName = defaultSoundFileName { let action = SKAction.playSoundFileNamed(soundFileName, waitForCompletion: true) self.runAction(action) } } internal override func containsPoint(p: CGPoint) -> Bool { if let bounds = self.boundsTolerance { let local = CGPoint(x: p.x - self.position.x, y: p.y - self.position.y) let width = self.size.width + bounds let height = self.size.height + bounds if (fabs(local.x) <= 0.5*width) && (fabs(local.y) <= 0.5*height) { return true } return false } else { return super.containsPoint(p) } } } // MARK: Array Extension extension Array { mutating func removeObject<U: Equatable>(object: U) { var index: Int? for (idx, objectToCompare) in enumerate(self) { if let to = objectToCompare as? U { if object == to { index = idx } } } if(index != nil) { self.removeAtIndex(index!) } } }
// // Friend.swift // Day 13 - Dynamic Data for Each Cell // // Created by 杜赛 on 2020/3/5. // Copyright © 2020 Du Sai. All rights reserved. // import Foundation struct Friend: Codable { var index: Int? var name: String? var avatar: String? var mobile: String? var email: String? var notes: String? }
// // Emoji.swift // Emoji_Dictionary // // Created by Bill Boughton on 6/5/17. // Copyright © 2017 Bill Boughton. All rights reserved. // class Emoji { var stringEmoji = "" var defintion = "" var category = "" var birthYear = 0 }
// // SpriteObstacle.swift // Hit The Mice // // Created by Jingrong Chen on 2015-09-10. // Copyright © 2015 Jingrong Chen. All rights reserved. // import SpriteKit class SpriteObstacle:SKSpriteNode { convenience init(imageName:String,rotation:CGFloat,size:CGSize) { self.init(texture: SKTexture(imageNamed: imageName)) name = imageName configurePhysicsBody() zRotation = rotation self.size=size } func configurePhysicsBody() { physicsBody = SKPhysicsBody(rectangleOf:frame.size) physicsBody!.categoryBitMask = CategoryBitMask.Obstacle.rawValue physicsBody!.contactTestBitMask = CategoryBitMask.Ball.rawValue physicsBody!.friction = 0 physicsBody!.restitution = 1 physicsBody!.linearDamping = 0 physicsBody!.angularDamping = 0 physicsBody!.allowsRotation = false physicsBody!.isDynamic = false physicsBody!.affectedByGravity = false } }
// // User.swift // HoorayGitHub // // Created by Francisco Ragland Jr on 11/13/15. // Copyright © 2015 Francisco Ragland. All rights reserved. // import Foundation class User { var name: String var profileImageUrl: String init(name: String, profileImageUrl: String){ self.name = name self.profileImageUrl = profileImageUrl } }
import TensorFlow import PythonKit %include "EnableIPythonDisplay.swift" print(IPythonDisplay.shell.enable_matplotlib("inline")) let plt = Python.import("matplotlib.pyplot") import Foundation import FoundationNetworking func download(from sourceString: String, to destinationString: String) { let source = URL(string: sourceString)! let destination = URL(fileURLWithPath: destinationString) let data = try! Data.init(contentsOf: source) try! data.write(to: destination) } let trainDataFilename = "iris_training.csv" download(from: "http://download.tensorflow.org/data/iris_training.csv", to: trainDataFilename) let f = Python.open(trainDataFilename) for _ in 0..<5 { print(Python.next(f).strip()) } print(f.close()) let featureNames = ["sepal_length", "sepal_width", "petal_length", "petal_width"] let labelName = "species" let columnNames = featureNames + [labelName] print("Features: \(featureNames)") print("Label: \(labelName)") let classNames = ["Iris setosa", "Iris versicolor", "Iris virginica"] let batchSize = 32 /// A batch of examples from the iris dataset. struct IrisBatch { /// [batchSize, featureCount] tensor of features. let features: Tensor<Float> /// [batchSize] tensor of labels. let labels: Tensor<Int32> } /// Conform `IrisBatch` to `Collatable` so that we can load it into a `TrainingEpoch`. extension IrisBatch: Collatable { public init<BatchSamples: Collection>(collating samples: BatchSamples) where BatchSamples.Element == Self { /// `IrisBatch`es are collated by stacking their feature and label tensors /// along the batch axis to produce a single feature and label tensor features = Tensor<Float>(stacking: samples.map{$0.features}) labels = Tensor<Int32>(stacking: samples.map{$0.labels}) } } /// Initialize an `IrisBatch` dataset from a CSV file. func loadIrisDatasetFromCSV( contentsOf: String, hasHeader: Bool, featureColumns: [Int], labelColumns: [Int]) -> [IrisBatch] { let np = Python.import("numpy") let featuresNp = np.loadtxt( contentsOf, delimiter: ",", skiprows: hasHeader ? 1 : 0, usecols: featureColumns, dtype: Float.numpyScalarTypes.first!) guard let featuresTensor = Tensor<Float>(numpy: featuresNp) else { // This should never happen, because we construct featuresNp in such a // way that it should be convertible to tensor. fatalError("np.loadtxt result can't be converted to Tensor") } let labelsNp = np.loadtxt( contentsOf, delimiter: ",", skiprows: hasHeader ? 1 : 0, usecols: labelColumns, dtype: Int32.numpyScalarTypes.first!) guard let labelsTensor = Tensor<Int32>(numpy: labelsNp) else { // This should never happen, because we construct labelsNp in such a // way that it should be convertible to tensor. fatalError("np.loadtxt result can't be converted to Tensor") } return zip(featuresTensor.unstacked(), labelsTensor.unstacked()).map{IrisBatch(features: $0.0, labels: $0.1)} } let trainingDataset: [IrisBatch] = loadIrisDatasetFromCSV(contentsOf: trainDataFilename, hasHeader: true, featureColumns: [0, 1, 2, 3], labelColumns: [4]) let trainingEpochs: TrainingEpochs = TrainingEpochs(samples: trainingDataset, batchSize: batchSize) let firstTrainEpoch = trainingEpochs.next()! let firstTrainBatch = firstTrainEpoch.first!.collated let firstTrainFeatures = firstTrainBatch.features let firstTrainLabels = firstTrainBatch.labels print("First batch of features: \(firstTrainFeatures)") print("firstTrainFeatures.shape: \(firstTrainFeatures.shape)") print("First batch of labels: \(firstTrainLabels)") print("firstTrainLabels.shape: \(firstTrainLabels.shape)") let firstTrainFeaturesTransposed = firstTrainFeatures.transposed() let petalLengths = firstTrainFeaturesTransposed[2].scalars let sepalLengths = firstTrainFeaturesTransposed[0].scalars plt.scatter(petalLengths, sepalLengths, c: firstTrainLabels.array.scalars) plt.xlabel("Petal length") plt.ylabel("Sepal length") plt.show()
// // DexLastTradesPresenterProtocol.swift // WavesWallet-iOS // // Created by Pavel Gubin on 8/22/18. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import RxCocoa import DomainLayer protocol DexLastTradesPresenterProtocol { typealias Feedback = (Driver<DexLastTrades.State>) -> Signal<DexLastTrades.Event> var interactor: DexLastTradesInteractorProtocol! { get set } func system(feedbacks: [Feedback]) var moduleOutput: DexLastTradesModuleOutput? { get set } var priceAsset: DomainLayer.DTO.Dex.Asset! { get set } var amountAsset: DomainLayer.DTO.Dex.Asset! { get set } }
@testable import ABA_Music import XCTest class HomeViewModelTests: XCTestCase { var viewModel: HomeViewModelType! override func setUp() { super.setUp() viewModel = HomeViewModel(repository: MockSearchRepository()) } override func tearDown() { viewModel = nil super.tearDown() } // MARK: Data source updated by term or scope changes func testArtistSearch() { let searchTerm = "Search this artist" let searchScopeIndex = 0 let searchScopeExpectation = expectation(description: "dataSourceWasMutated(_:) has been called") let delegate = MockDataSourceControllerDelegate() delegate.didMutateDataSource = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 0) XCTAssertNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, "") XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchScopeExpectation.fulfill() } viewModel.dataSource.delegate = delegate viewModel.updateSearchScope(searchScopeIndex) waitForExpectations(timeout: 1.0) let searchTermExpectation = expectation(description: "dataSourceWasMutated(_:) has been called") delegate.didMutateDataSource = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 5) XCTAssertNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, searchTerm) XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchTermExpectation.fulfill() } viewModel.updateSearchTerm(searchTerm) waitForExpectations(timeout: 1.0) } func testSongSearch() { let searchTerm = "Search this song" let searchScopeIndex = 1 let searchScopeExpectation = expectation(description: "dataSourceWasMutated(_:) has been called") let delegate = MockDataSourceControllerDelegate() delegate.didMutateDataSource = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 0) XCTAssertNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, "") XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchScopeExpectation.fulfill() } viewModel.dataSource.delegate = delegate viewModel.updateSearchScope(searchScopeIndex) waitForExpectations(timeout: 1.0) let searchTermExpectation = expectation(description: "dataSourceWasMutated(_:) has been called") delegate.didMutateDataSource = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 1) XCTAssertNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, searchTerm) XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchTermExpectation.fulfill() } viewModel.updateSearchTerm(searchTerm) waitForExpectations(timeout: 1.0) } func testAlbumSearch() { let searchTerm = "Search this song" let searchScopeIndex = 2 let searchScopeExpectation = expectation(description: "dataSourceWasMutated(_:) has been called") let delegate = MockDataSourceControllerDelegate() delegate.didMutateDataSource = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 0) XCTAssertNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, "") XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchScopeExpectation.fulfill() } viewModel.dataSource.delegate = delegate viewModel.updateSearchScope(searchScopeIndex) waitForExpectations(timeout: 1.0) let searchTermExpectation = expectation(description: "dataSourceWasMutated(_:) has been called") delegate.didMutateDataSource = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 3) XCTAssertNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, searchTerm) XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchTermExpectation.fulfill() } viewModel.updateSearchTerm(searchTerm) waitForExpectations(timeout: 1.0) } // MARK: Delegate triggered by error func testArtistSearchError() { let searchTerm = "error" let searchScopeIndex = 0 let searchTermExpectation = expectation(description: "viewModelFailedToFetchData(_:) has been called") let delegate = MockHomeViewModelDelegate() delegate.didFailToFetchData = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 0) XCTAssertNotNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, searchTerm) XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchTermExpectation.fulfill() } viewModel.delegate = delegate viewModel.updateSearchTerm(searchTerm) waitForExpectations(timeout: 1.0) } func testSongSearchError() { let searchTerm = "error" let searchScopeIndex = 1 viewModel.updateSearchScope(searchScopeIndex) let searchTermExpectation = expectation(description: "viewModelFailedToFetchData(_:) has been called") let delegate = MockHomeViewModelDelegate() delegate.didFailToFetchData = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 0) XCTAssertNotNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, searchTerm) XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchTermExpectation.fulfill() } viewModel.delegate = delegate viewModel.updateSearchTerm(searchTerm) waitForExpectations(timeout: 1.0) } func testAlbumSearchError() { let searchTerm = "error" let searchScopeIndex = 2 viewModel.updateSearchScope(searchScopeIndex) let searchTermExpectation = expectation(description: "viewModelFailedToFetchData(_:) has been called") let delegate = MockHomeViewModelDelegate() delegate.didFailToFetchData = { [weak self] in guard let self = self else { return } XCTAssertEqual(self.viewModel.dataSource.totalRowCount, 0) XCTAssertNotNil(self.viewModel.delegate) XCTAssertEqual(self.viewModel.searchTerm, searchTerm) XCTAssertEqual(self.viewModel.searchScopeIndex, searchScopeIndex) searchTermExpectation.fulfill() } viewModel.delegate = delegate viewModel.updateSearchTerm(searchTerm) waitForExpectations(timeout: 1.0) } }
import XCTest import BowLaws import Bow class TryTest: XCTestCase { func testEquatableLaws() { EquatableKLaws<TryPartial, Int>.check() } func testHashableKLaws() { HashableKLaws<TryPartial, Int>.check() } func testFunctorLaws() { FunctorLaws<TryPartial>.check() } func testApplicativeLaws() { ApplicativeLaws<TryPartial>.check() } func testSelectiveLaws() { SelectiveLaws<TryPartial>.check() } func testMonadLaws() { MonadLaws<TryPartial>.check() } func testCustomStringConvertibleLaws() { CustomStringConvertibleLaws<Try<Int>>.check() } func testFoldableLaws() { FoldableLaws<TryPartial>.check() } func testTraverseLaws() { TraverseLaws<TryPartial>.check() } func testFunctorFilterLaws() { FunctorFilterLaws<TryPartial>.check() } func testSemigroupLaws() { SemigroupLaws<Try<Int>>.check() } func testMonoidLaws() { MonoidLaws<Try<Int>>.check() } }
// // Weather+CoreDataClass.swift // // // Created by Rob Whitaker on 05/04/2017. // // import Foundation import CoreData final public class Weather: NSManagedObject {}
// // LoginViewController.swift // Exercise_3 // // Created by AST on 6/9/17. // Copyright © 2017 AST. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet weak var labelWarning: UILabel! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var userNameOutlet: UITextField! override func viewDidLoad() { labelWarning.isHidden = true super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginAction(_ sender: Any) { if (userNameOutlet.text?.isEmpty)! && (txtPassword.text?.isEmpty)! { labelWarning.isHidden = false labelWarning.text = "Please input full field" } else if (userNameOutlet.text?.isEmpty)! { labelWarning.isHidden = false labelWarning.text = "Please input username" } else if (txtPassword.text?.isEmpty)! { labelWarning.isHidden = false labelWarning.text = "Please input password" } else { let userlog = ["username": userNameOutlet.text, "password": txtPassword.text] if let path = Bundle.main.path(forResource: "user", ofType: "plist") { if let dic = NSDictionary(contentsOfFile: path) as? [String: Any] { if (NSDictionary(dictionary: dic).isEqual(to: userlog)){ let vc = HomeViewController() self.navigationController?.pushViewController(vc, animated: true) //vc.username = usertf.text let userdefault = UserDefaults.standard userdefault.set(userNameOutlet.text, forKey: "username") userdefault.synchronize() } else { labelWarning.text = "Wrong username or password" } } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // ButtonTableViewCell.swift // Encuesta // // Created by Paolo Eduardo Arámbulo Calderon on 8/3/19. // Copyright © 2019 Paolo Eduardo Arámbulo Calderon. All rights reserved. // import UIKit protocol showAndHideDelegate{ func showHide(index: IndexPath) } class ButtonTableViewCell: UITableViewCell { var showHideDelegate: showAndHideDelegate? var indice: IndexPath! @IBOutlet weak var btnShowAndHide: UIButton! override func awakeFromNib() { super.awakeFromNib() } @IBAction func showAndHide(_ sender: Any) { indice.row = 1 showHideDelegate?.showHide(index: indice) } }
// // ViewController.swift // earthquakeForiOS // // Created by akihiro on 2014/09/06. // Copyright (c) 2014年 gecko655. All rights reserved. // import UIKit import Accounts import SwifteriOS // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class ViewController: UITableViewController { var twitterAccounts: [ACAccount]? func openPrivacySettings(_ action: UIAlertAction?){ let url = URL(string:UIApplicationOpenSettingsURLString) UIApplication.shared.openURL(url!) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let accountStore = ACAccountStore() let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccounts(with: accountType, options: nil) { granted, error in if granted { self.twitterAccounts = accountStore.accounts(with: accountType) as! [ACAccount]? if self.twitterAccounts?.count > 0 { DispatchQueue.main.async{ self.tableView.reloadData() } } else { self.alertWithTitle("Error", message: "There are no Twitter accounts configured. You can add or create a Twitter account in Settings.") } } else { self.alertWithTitle("Error", message: "Access to Twitter accounts was denied\n Please configure privacy settings.", handler: self.openPrivacySettings) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return twitterAccounts?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell :UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) let acAccount = self.twitterAccounts![indexPath.row] as ACAccount cell.textLabel?.text = acAccount.accountDescription return cell } func alertWithTitle(_ title: String, message: String, handler: ((UIAlertAction?) -> Void)? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any!) { let indexPath = self.tableView.indexPathForSelectedRow let twitterAccount = self.twitterAccounts![indexPath!.row] let swifter = Swifter(account: twitterAccount) let mainViewController :MainViewController = segue.destination as! MainViewController mainViewController.swifter = swifter } }
// // ForecastCell.swift // WeatherApp // // Created by Yaroslav Tutushkin on 08.03.2020. // import UIKit /// Ячейка с информацией о погоде на 3 часа final class ForecastCell: UICollectionViewCell { var item: ForecastViewModelItem? { didSet { guard item != nil else { return } date.text = item?.date time.text = item?.time temp.text = item?.temp icon.image = UIImage(named: item?.icon ?? "") } } lazy var icon: UIImageView = { let icon = UIImageView() icon.contentMode = .scaleAspectFit return icon }() lazy var temp: UILabel = { let label = UILabel() label.textColor = .black return label }() lazy var date: UILabel = { let date = UILabel() date.textColor = .black return date }() lazy var time: UILabel = { let time = UILabel() time.textColor = .black return time }() lazy var stack: UIStackView = { let stack = UIStackView(arrangedSubviews: [date, time, icon, temp]) stack.axis = .vertical stack.alignment = .center return stack }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear setupLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupLayout() { stack.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(stack) NSLayoutConstraint.activate([ stack.topAnchor.constraint(equalTo: contentView.topAnchor), stack.leftAnchor.constraint(equalTo: contentView.leftAnchor), stack.rightAnchor.constraint(equalTo: contentView.rightAnchor), stack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) ]) } }
// // ViewChainable.swift // delinshe_ios // // Created by Xu on 2020/9/14. // Copyright © 2020 com.delinshe. All rights reserved. // import Foundation import SnapKit protocol ViewChainNameSpace { associatedtype NamespaceType var builder: NamespaceType {get} static var chain: NamespaceType.Type {get} } extension ViewChainNameSpace { var builder: ViewChainWrapper<Self> { return ViewChainWrapper(self) } static var chain: ViewChainWrapper<Self>.Type { return ViewChainWrapper.self } } public struct ViewChainWrapper<Base> { public var base: Base public init(_ base: Base) { self.base = base } } extension UIView: ViewChainNameSpace {} extension ViewChainWrapper where Base: UIView { @discardableResult func addhere(at superview: UIView)-> Self { superview.addSubview(base) return base.builder } @discardableResult func layout(snapKitMaker: (ConstraintMaker)-> Void)-> Self { base.snp.makeConstraints(snapKitMaker) return base.builder } @discardableResult func config(_ config: ((Base)-> Void))-> Self { config(base) return base.builder } }
// // UINavigationBarTests.swift // Bond // // Created by SatoShunsuke on 2015/10/23. // Copyright (c) 2015 Bond. All rights reserved. // import UIKit import XCTest import Bond class UINavigationBarTests : XCTestCase { func testUINavigationBarBarTintColorBond() { let observable = Observable<UIColor>(UIColor.blackColor()) let bar = UINavigationBar() bar.barTintColor = UIColor.redColor() XCTAssert(bar.barTintColor == UIColor.redColor(), "Initial value") observable.bindTo(bar.bnd_barTintColor) XCTAssert(bar.barTintColor == UIColor.blackColor(), "Value after binding") observable.value = UIColor.blueColor() XCTAssert(bar.barTintColor == UIColor.blueColor(), "Value after observable change") } }
// // HomeViewController.swift // UBIEAT // // Created by UBIELIFE on 2016-08-13. // Copyright © 2016 UBIELIFE Inc. All rights reserved. // import UIKit import GooglePlaces import CoreLocation class HomeViewController: UIViewController { let locationManager = CLLocationManager() // MARK outlet @IBOutlet weak var searchTextfield: UITextField! @IBOutlet weak var input1_view: UIView! // MARK -- static let CELL_IDENTIFIER = "AUTOCOMPLETECELL" var autoCompleteTable: UITableView? var autoCompleteResults: [GMSAutocompletePrediction]? var tapGesture: UITapGestureRecognizer? // user location var userLocation: CLLocationCoordinate2D? // Init methods override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?){ super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience init(){ var nibNameOrNil = String?("HomeViewController") if NSBundle.mainBundle().pathForResource(nibNameOrNil, ofType: "xib") == nil{ nibNameOrNil = nil } self.init(nibName: nibNameOrNil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //--------- override func viewDidLoad() { super.viewDidLoad() setupUI() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { self.navigationController?.navigationBarHidden = true self.navigationController?.tabBarController!.tabBar.backgroundImage = UIImageView.imageChangeSize(UIImage(named: "tabbar_bg")!, size: CGSizeMake(UIScreen.mainScreen().bounds.width, 40)) //Require location authentication self.locationManager.requestWhenInUseAuthorization() if let location = UBIAppCenter.sharedInstance.place{ self.searchTextfield.text = location.formattedAddress } } func setupUI(){ // init result table let table_width = Constant.SCREEN_BOUNDS.width - 37 - 38 autoCompleteTable = UITableView(frame: CGRectMake(self.input1_view.frame.origin.x, self.input1_view.frame.origin.y + self.input1_view.frame.height - 3, table_width, 3 * 40)) self.autoCompleteTable?.hidden = true self.autoCompleteTable?.backgroundColor = UIColor.init(red: 83, green: 88, blue: 95, alpha: 0.85) self.autoCompleteTable?.layer.cornerRadius = 5 self.view.addSubview(autoCompleteTable!) self.autoCompleteTable?.delegate = self self.autoCompleteTable?.dataSource = self self.autoCompleteTable?.registerClass(UITableViewCell().classForCoder, forCellReuseIdentifier: HomeViewController.CELL_IDENTIFIER) // add text field delegate self.searchTextfield.delegate = self // add 1-tap gesture tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tapGesture?.numberOfTapsRequired = 1 } func autoComplete(query: String) { let filter = GMSAutocompleteFilter() filter.type = .Establishment GMSPlacesClient.sharedClient().autocompleteQuery(query, bounds: nil, filter: filter) { (results, error: NSError?) -> Void in guard error == nil else{ print("AutoComplete error: \(error)") return } self.autoCompleteResults = results self.autoCompleteTable?.reloadData() // for result in results!{ // print("Result \(result.attributedFullText) with placeID \(result.placeID)") // // } } } func dismissKeyboard() { if self.searchTextfield.isFirstResponder() == true { self.searchTextfield.resignFirstResponder() // self.view.removeGestureRecognizer( tapGesture! ) } } // MARK - button actions @IBAction func useCurrentLocationAction(sender: AnyObject) { if CLLocationManager.locationServicesEnabled() == false { let alertVC = UIAlertController.init(title: "Message", message: "Location service is not allowed, please go to Setting", preferredStyle: .Alert) let okAction = UIAlertAction.init(title: "OK", style: .Default, handler: { (action:UIAlertAction) -> Void in alertVC.dismissViewControllerAnimated(true, completion: nil) }) alertVC.addAction(okAction) self.navigationController?.pushViewController(alertVC, animated: true) return } GMSPlacesClient.sharedClient().currentPlaceWithCallback { (placeLikelihoods, error: NSError?) -> Void in guard error == nil else{ print("Current location error : \(error?.localizedDescription)") return } if let placeLikelihoods = placeLikelihoods { for likelihood in placeLikelihoods.likelihoods { let place = likelihood.place print("Current Place name \(place.name) at likelihood \(likelihood.likelihood)") print("Current Place address \(place.formattedAddress)") print("Current Place attributions \(place.attributions)") print("Current PlaceID \(place.placeID)") } } if (placeLikelihoods?.likelihoods.first) != nil{ let first = placeLikelihoods?.likelihoods.first self.searchTextfield.text = first?.place.formattedAddress UBIAppCenter.sharedInstance.place = first?.place self.userLocation = first?.place.coordinate } } } @IBAction func findMealAction(sender: AnyObject) { if UBIAppCenter.sharedInstance.place != nil{ let restaurantVC = RestaurantViewController.init() self.navigationController?.pushViewController(restaurantVC, animated: true) }else{ print("No location info.") } } @IBAction func placeCateringAction(sender: AnyObject) { let cateringVC = CateringViewController() self.presentViewController(cateringVC, animated: true) { } } } extension HomeViewController: UITableViewDelegate, UITableViewDataSource , UITextFieldDelegate, CLLocationManagerDelegate { // MARK table delegate methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard autoCompleteResults != nil else { return 0 } return (self.autoCompleteResults?.count)! } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 40 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(HomeViewController.CELL_IDENTIFIER, forIndexPath: indexPath) let data = self.autoCompleteResults![indexPath.row] cell.detailTextLabel?.text = data.placeID cell.textLabel?.text = data.attributedFullText.string cell.selectionStyle = .None return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let data = self.autoCompleteResults![indexPath.row] print("place: \(data.attributedFullText) , ID: \(data.placeID)") if self.autoCompleteTable?.hidden == false { self.autoCompleteTable?.hidden = true self.searchTextfield.text = data.attributedFullText.string GMSPlacesClient.sharedClient().lookUpPlaceID(data.placeID!, callback: { (place: GMSPlace?, error: NSError?) in if let error = error{ print("lookup place id query error: \(error.localizedDescription)") return } if let place = place{ UBIAppCenter.sharedInstance.place = place } }) } if self.searchTextfield.isFirstResponder() == true { self.searchTextfield.resignFirstResponder() } } // MARK text field delegate methods func textFieldShouldBeginEditing(textField: UITextField) -> Bool { // self.resultView?.hidden = false // changeSelfFrame() self.autoCompleteTable?.hidden = false // self.view.addGestureRecognizer( tapGesture! ) return true } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { print("\(textField.text!)\(string)") if self.autoCompleteTable?.hidden == true { self.autoCompleteTable?.hidden = false } let query = "\(textField.text!)\(string)" if query == "" { self.autoCompleteTable?.hidden = true }else{ autoComplete("\(textField.text!)\(string)") } return true } func textFieldShouldEndEditing(textField: UITextField) -> Bool { // self.resultView?.hidden = true return true } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() self.autoCompleteTable?.hidden = true return true } func textFieldShouldClear(textField: UITextField) -> Bool { self.autoCompleteTable?.hidden = true return true } // func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { print("New location \(newLocation)") } //重写当发生错误时要调用的方法 func locationManager(manager: CLLocationManager, didFailWithError error: NSError){ print(error) } }
// // ViewController.swift // TextFieldsAndDelegationClassNotes // // Created by C4Q on 10/24/17. // Copyright © 2017 C4Q . All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var guessTextField: UITextField! @IBOutlet weak var messageLabel: UILabel! var model = GuessingGameModel() override func viewDidLoad() { super.viewDidLoad() guessTextField.delegate = self //self is an instance of ViewController that the user is currently working with } func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let text = textField.text else { return false } guard let textAsInt = Int(text) else { messageLabel.text = "\(text) is not a valid input" messageLabel.isHidden = false return false } switch model.guess(textAsInt) { case .tooLow: messageLabel.text = "\(textAsInt) is too low" case .tooHigh: messageLabel.text = "\(textAsInt) is too high" case .correct: messageLabel.text = "\(textAsInt) is correct!" case .alreadyGuessed: messageLabel.text = "You have already guessed \(textAsInt)!" } messageLabel.isHidden = false textField.text = "" textField.resignFirstResponder() return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { print(range.lowerBound, range.upperBound, string) if string == "" { return true } guard let _ = Int(string) else { return false } return true } /* func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { print("Should begin") return true } func textFieldDidBeginEditing(_ textField: UITextField) { print("Did begin") } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { print("Should change") print("range: \(range.lowerBound)-\(range.upperBound)") print("string: \(string)") return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { print("Should clear") return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { print("Should return") textField.resignFirstResponder() return true } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { print("Should end") return false } func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { print("Did end") switch reason { case .committed: print("Because committed") default: print("Because another thing") } } */ }
// // GitHubService.swift // GitHubClient // // Created by Matthew McClure on 8/17/15. // Copyright (c) 2015 Matthew McClure. All rights reserved. // import Foundation class GitHubService { class func repositoriesForSearchTerm(searchTerm: String, completionHandler: (String?, [Repo]?) -> (Void)) { let baseURL = "https://api.github.com/search/repositories" let finalURL = baseURL + "?q=\(searchTerm)" let request = NSMutableURLRequest(URL: NSURL(string: finalURL)!) if let token = KeychainService.loadToken() { request.setValue("token \(token)", forHTTPHeaderField: "Authorization") } if let url = NSURL(string: finalURL) { NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if let error = error { println("error") } else if let httpResponse = response as? NSHTTPURLResponse { println(httpResponse) switch httpResponse.statusCode { case 200...299: NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in let repos = RepoJSONParser.reposFromJSONData(data) completionHandler(nil, repos) }) case 400...499: println("it's your fault: ") println(httpResponse.statusCode) completionHandler("it's our fault", nil) case 500...599: println("it's the server's fault") completionHandler("it's the server's fault", nil) default: println("error occurred") } } completionHandler("There was an issue with the response", nil) }).resume() } } class func usersForSearchTerm(searchTerm: String, completionHandler: (String?, [User]?) -> (Void)) { let baseURL = "https://api.github.com/search/users" let finalURL = baseURL + "?q=\(searchTerm)" let request = NSMutableURLRequest(URL: NSURL(string: finalURL)!) if let token = KeychainService.loadToken() { request.setValue("token \(token)", forHTTPHeaderField: "Authorization") } if let url = NSURL(string: finalURL) { NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if let error = error { println("error") } else if let httpResponse = response as? NSHTTPURLResponse { println(httpResponse) switch httpResponse.statusCode { case 200...299: NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in let users = UserJSONParser.usersFromJSONData(data) completionHandler(nil, users) }) case 400...499: println("it's your fault: ") println(httpResponse.statusCode) completionHandler("it's our fault", nil) case 500...599: println("it's the server's fault") completionHandler("it's the server's fault", nil) default: println("error occurred") } } completionHandler("There was an issue with the response", nil) }).resume() } } }
// // Gir2Swift.swift // libgir2swift // // Created by Rene Hexel on 20/5/21. // Copyright © 2021 Rene Hexel. All rights reserved. // import ArgumentParser import Foundation /// Structure representing the `gir2swift` executable, including command line arguments public struct Gir2Swift: ParsableCommand { /// Produce verbose output if `true` @Flag(name: .short, help: "Produce verbose output.") var verbose = false /// Generate output for everything, including private C types if `true` @Flag(name: .short, help: "Disables all filters. Wrappers for all C types will be generated.") var allFilesGenerate = false /// Create a single output file per class if `true` @Flag(name: .short, help: "Create a single .swift file per class.") var singleFilePerClass = false /// Array of names of pre-parsed `.gir` files. @Option(name: .short, help: "Add pre-requisite .gir files to ensure the types in file.gir are known.") var prerequisiteGir: [String] = [] /// Name of the output directory to write generated files to. /// - Note: Writes generated code to `standardOutput` if `nil` @Option(name: .short, help: "Specify the output directory to put the generated files into.") var outputDirectory: String = "" /// File containing one-off boilerplate code for your module @Option(name: .short, help: "Add the given .swift file as the main (hand-crafted) Swift file for your library target.") var moduleBoilerPlateFile: String = "" /// The actual, main `.gir` file(s) to process @Argument(help: "The .gir metadata files to process.") var girFiles: [String] /// Designated initialiser public init() {} /// Main function to run the `gir2swift command` mutating public func run() throws { let nTypesPrior = GIR.knownTypes.count let moduleBoilerPlate: String if moduleBoilerPlateFile.isEmpty { moduleBoilerPlate = moduleBoilerPlateFile } else { guard let contents = try? String(contentsOfFile: moduleBoilerPlateFile, encoding: .utf8) else { fatalError("Cannot read contents of '\(moduleBoilerPlateFile)'") } moduleBoilerPlate = contents } // pre-load gir files to ensure pre-requisite types are known for girFile in prerequisiteGir { preload_gir(file: girFile) } let target = outputDirectory.isEmpty ? nil : outputDirectory for girFile in girFiles { process_gir(file: girFile, boilerPlate: moduleBoilerPlate, to: target, split: singleFilePerClass, generateAll: allFilesGenerate) } if verbose { let nTypesAfter = GIR.knownTypes.count let nTypesAdded = nTypesAfter - nTypesPrior print("Processed \(nTypesAdded) types (total: \(nTypesAfter)).") } } }
// // DesafiosViewController.swift // Bloomy // // Created by Mayara Mendonça de Souza on 09/12/20. // import UIKit import CoreData class DesafiosViewController: UIViewController { // MARK: Outlets @IBOutlet weak var contentView: UIView! // MARK: Variáveis Globais var challenges:[Challenge] = [] var challengeSummaryDataSource:[String] = [] var challengeImageDataSource: [UIImage] = [] var islandsNames: [String] = [] var currentViewControllerIndex = 0 override func viewDidLoad() { super.viewDidLoad() self.challenges = getAcceptedChallenges() self.challengeSummaryDataSource = getChallengeSummary() self.challengeImageDataSource = getChallengesIslandName() self.islandsNames = getIslandsNames() self.configurePageViewController() } override func viewWillAppear(_ animated: Bool) { challenges = getAcceptedChallenges() challengeSummaryDataSource = getChallengeSummary() challengeImageDataSource = getChallengesIslandName() self.islandsNames = getIslandsNames() hideContentController() } override func viewDidAppear(_ animated: Bool) { configurePageViewController() } override func viewDidDisappear(_ animated: Bool) { currentViewControllerIndex = 0 } // MARK: Navigation Bar func setupNavigationController() { self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for:.default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.topItem?.title = "" self.navigationController?.navigationBar.layoutIfNeeded() } // MARK: Page View Controller func configurePageViewController() { guard let pageViewController = storyboard?.instantiateViewController(withIdentifier: String(describing:DesafiosPageViewController.self)) as? DesafiosPageViewController else { return } pageViewController.delegate = self pageViewController.dataSource = self addChild(pageViewController) pageViewController.didMove(toParent:self) pageViewController.view.backgroundColor = #colorLiteral(red: 0.9938541055, green: 0.9598969817, blue: 0.9428560138, alpha: 1) if (!challenges.isEmpty) { contentView.addSubview(pageViewController.view) pageViewController.view.translatesAutoresizingMaskIntoConstraints = false let views: [String: Any] = ["pageView": pageViewController.view as Any] contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[pageView]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[pageView]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views)) guard let startingViewController = detailViewControllerAt(index: currentViewControllerIndex) else { return } pageViewController.setViewControllers([startingViewController], direction: .forward, animated: true) } } func detailViewControllerAt(index: Int) -> DesafiosDataViewController? { // Garantir que o Page view controller não ultrapasse o limite de páginas if (index >= challengeSummaryDataSource.count || challengeSummaryDataSource.isEmpty) { return nil } guard let dataViewController = storyboard?.instantiateViewController(withIdentifier: String(describing:DesafiosDataViewController.self)) as? DesafiosDataViewController else { return nil } dataViewController.index = index dataViewController.summaryText = challengeSummaryDataSource[index] dataViewController.cardImage = challengeImageDataSource[index] dataViewController.islandName = islandsNames[index] if index == challengeSummaryDataSource.count-1 { dataViewController.lastScreen = true } else { dataViewController.lastScreen = false } return dataViewController } // MARK: Dados que serão usados nas páginas do Page View Controller var islandNameToImage: [String:String] = [ "Atenção Plena": "card_atencao_plena", "Saúde": "card_saude", "Pessoas Queridas": "card_pessoas_queridas", "Lazer": "card_lazer" ] func getAcceptedChallenges() -> [Challenge] { var acceptedChallenges: [Challenge] = [] let islands = getSortedIslands(islands: UserManager.shared.getIslands()!) for island in islands { if let dailyChallenge = island.dailyChallenge { if dailyChallenge.accepted && !dailyChallenge.done { acceptedChallenges.append(dailyChallenge) } } } return acceptedChallenges } func getSortedIslands(islands: [Island]) -> [Island] { var sortedIslands: [Island] = [] let islandsNames = [ IslandsNames.health.rawValue, IslandsNames.leisure.rawValue, IslandsNames.mindfulness.rawValue, IslandsNames.loveds.rawValue ] for islandName in islandsNames { if let island = IslandManager.shared.getIsland(withName: islandName) { sortedIslands.append(island) } } return sortedIslands } func getIslandsNames() -> [String] { var islandsNames: [String] = [] for challenge in challenges { islandsNames.append(challenge.challengeToIsland!.name!) } return islandsNames } func getChallengeSummary() -> [String] { var challengeSummary: [String] = [] for challenge in challenges { challengeSummary.append(challenge.summary!) } return challengeSummary } func getChallengesIslandName() -> [UIImage] { var challengeIslandName: [UIImage] = [] for challenge in challenges { challengeIslandName.append(UIImage(imageLiteralResourceName: islandNameToImage[challenge.challengeToIsland!.name!]!)) } return challengeIslandName } func hideContentController() { guard let pageViewController = storyboard?.instantiateViewController(withIdentifier: String(describing:DesafiosPageViewController.self)) as? DesafiosPageViewController else { return } // Reseta o Delegate do Page View Controller pageViewController.dataSource = nil } @objc func updatePageViewController() { DispatchQueue.main.async { self.hideContentController() self.configurePageViewController() } } } // MARK: Page View Controller Protocols extension DesafiosViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource { func presentationIndex(for pageViewController: UIPageViewController) -> Int { return currentViewControllerIndex } func presentationCount(for pageViewController: UIPageViewController) -> Int { return challengeSummaryDataSource.count } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let dataViewController = viewController as? DesafiosDataViewController guard var currentIndex = dataViewController?.index else { return nil } currentViewControllerIndex = currentIndex if currentIndex == 0 { return nil } currentIndex -= 1 return detailViewControllerAt(index: currentIndex) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let dataViewController = viewController as? DesafiosDataViewController guard var currentIndex = dataViewController?.index else { return nil } if currentIndex == challengeSummaryDataSource.count { return nil } currentIndex += 1 currentViewControllerIndex = currentIndex return detailViewControllerAt(index: currentIndex) } }
// // AlertControllerProtocol.swift // jChat // // Created by Jeevan on 04/05/19. // Copyright © 2019 Jeevan. All rights reserved. // import Foundation import UIKit class BaseViewController : UIViewController { public var activityIndicator: UIActivityIndicatorView! override func viewDidLoad() { self.addActivityIndicator() } func showMessageOnlyAlert(message: String, completion: (()->())?) { let alert = UIAlertController(title: "jChat", message: message, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { (_) in print("User click Dismiss button") })) self.present(alert, animated: true, completion: { if let completion = completion { completion() } print("completion block") }) } func showTextFieldAlert(message: String, placeholder: String, constructiveButtonTitle : String, completion: @escaping ((String)->())) { let alert = UIAlertController(title: "jChat", message: message, preferredStyle: .alert) alert.addTextField(configurationHandler: { (textField) in textField.placeholder = placeholder }) alert.addAction(UIAlertAction(title: constructiveButtonTitle, style: .default, handler: { (_) in let firstTextField = alert.textFields![0] as UITextField if let textFieldText = firstTextField.text { completion(textFieldText) } })) alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { (_) in print("User click Dismiss button") })) self.present(alert, animated: true, completion: { print("completion block") }) } func showTwoOptionsAlert(message: String, text1:String, text2:String, selection1: @escaping ()->(), selection2: @escaping ()->()) { let alert = UIAlertController(title: "jChat", message: message, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: text1, style: .default, handler: { (_) in selection1() })) alert.addAction(UIAlertAction(title: text2, style: .default, handler: { (_) in selection2() })) alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { (_) in print("User click Dismiss button") })) self.present(alert, animated: true, completion: { }) } // MARK: - General Methods func addActivityIndicator() { // Set activity indicator properties and start animating for first time load activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray) var centerPoint = self.view.center centerPoint.x = UIScreen.main.bounds.width / 2 activityIndicator.center = centerPoint activityIndicator.hidesWhenStopped = true self.view.addSubview(activityIndicator) } }
// // ContentView.swift // TabBarCustomiazationInSwiftUI // // Created by ramil on 05.11.2019. // Copyright © 2019 com.ri. All rights reserved. // import SwiftUI struct ContentView: View { @State private var selection = 0 var body: some View { TabView(selection: $selection) { Text("First View") .font(.title) .tabItem { VStack { Image(systemName: "doc") .font(.title) Text("First") .font(.title) } } .tag(0) Text("Second View") .font(.title) .tabItem { VStack { Image(systemName: "paperclip") .font(.title) Text("Second") .font(.title) } } .tag(1) } } } extension UITabBarController { override open func viewDidLoad() { let standardAppearance = UITabBarAppearance() // standardAppearance.backgroundColor = .orange // or // standardAppearance.backgroundImage = UIImage(named: "img3") // or //standardAppearance.configureWithTransparentBackground() standardAppearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.red] standardAppearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.red] standardAppearance.inlineLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.green] standardAppearance.inlineLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.green] standardAppearance.compactInlineLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.blue] standardAppearance.compactInlineLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.blue] tabBar.standardAppearance = standardAppearance } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // CTypeExtensions.swift // OpenSetRecognition // // Created by Foltányi Kolos on 2019. 04. 22.. // Copyright © 2019. Foltányi Kolos. All rights reserved. // extension Array where Element == String { var cStringArray: [UnsafeMutablePointer<Int8>?] { return self.map { $0.cString } } } extension Int { var cInt: Int32 { return Int32(self) } } extension String { var cString: UnsafeMutablePointer<Int8>? { return strdup(self) } }
// // Course.swift // KanjiApp // // Created by DT Dat on 2017/08/15. // Copyright © 2017 DT Dat. All rights reserved. // import Foundation class Course: NSObject { var id: NSNumber? var name: String? var category: String? var imageName: String? var price:NSNumber? var screenshots:[String]? var desc: String? var appInformation:AnyObject? //ko thay doi ten bien vi no dung de parse json override func setValue(_ value: Any?, forKey key: String) { if key == "description"{ self.desc = value as? String } else{ super.setValue(value, forKey: key) } } }
// // CoreAnimations.swift // Animatify // // Created by Shubham Singh on 15/06/20. // Copyright © 2020 Shubham Singh. All rights reserved. // import UIKit /// CoreAnimations enum LayerAnimationFactory { static func getStrokeStartAnimation(duration: TimeInterval, toValue: CGFloat = 1.0) -> CABasicAnimation { let strokeStart = CABasicAnimation(keyPath: "strokeStart") strokeStart.duration = duration strokeStart.toValue = toValue strokeStart.isRemovedOnCompletion = false strokeStart.fillMode = .forwards return strokeStart } static func getStrokeEndAnimation(duration: TimeInterval, toValue: CGFloat = 1.0) -> CABasicAnimation { let strokeEnd = CABasicAnimation(keyPath: "strokeEnd") strokeEnd.duration = duration strokeEnd.toValue = toValue strokeEnd.isRemovedOnCompletion = false strokeEnd.fillMode = .forwards return strokeEnd } }
// // JsonManagedObject.swift // JsonManagedObject-Swift // // Created by christophe on 08/06/14. // Copyright (c) 2014 cdebortoli. All rights reserved. // import Foundation let jsonManagedObjectSharedInstance = JsonManagedObject() class JsonManagedObject { let dateFormatter = NSDateFormatter() @lazy var configDatasource = JMOConfigDatasource() init() { dateFormatter.dateFormat = JMOConfig.dateFormat } // Analyze an array of Dictionary func analyzeJsonArray(jsonArray:AnyObject[], forClass objectClass:AnyClass) -> AnyObject[] { var resultArray = AnyObject[]() for jsonArrayOccurence:AnyObject in jsonArray { if let jsonDict = jsonArrayOccurence as? Dictionary<String, AnyObject> { if let objectFromJson : AnyObject = analyzeJsonDictionary(jsonDict, forClass: objectClass) { resultArray += objectFromJson } } } return resultArray } // Analyze a dDictionary func analyzeJsonDictionary(jsonDictionary:Dictionary<String, AnyObject>, forClass objectClass:AnyClass) -> AnyObject? { // 1 - Find the config object for the specified class if let configObject = configDatasource[NSStringFromClass(objectClass)] { // 2 - Json Dictionary var jsonFormatedDictionary = jsonDictionary // Envelope if JMOConfig.jsonWithEnvelope { if let dictUnwrapped = jsonDictionary[configObject.classInfo.jsonKey]! as? Dictionary<String, AnyObject> { jsonFormatedDictionary = dictUnwrapped } } // 3a - NSManagedObject Parse & init if class_getSuperclass(objectClass) is NSManagedObject.Type { if JMOConfig.managedObjectContext == nil { return nil } var managedObject:NSManagedObject if JMOConfig.temporaryNSManagedObjectInstance == false { managedObject = NSEntityDescription.insertNewObjectForEntityForName(NSStringFromClass(objectClass), inManagedObjectContext: JMOConfig.managedObjectContext!) as NSManagedObject } else { let entityDescription = NSEntityDescription.entityForName(NSStringFromClass(objectClass), inManagedObjectContext: JMOConfig.managedObjectContext) managedObject = NSManagedObject(entity: entityDescription, insertIntoManagedObjectContext: nil) } for parameter in configObject.parameters { managedObject.setProperty(parameter, fromJson: jsonFormatedDictionary) } return managedObject // 3b - CustomObject Parse & init } else if class_getSuperclass(objectClass) is JMOWrapper.Type { var cobject : AnyObject! = JMOClassFactory.initObjectFromClass(objectClass) (cobject as JMOWrapper).childrenClassReference = objectClass for parameter in configObject.parameters { (cobject as JMOWrapper).setParameter(parameter, fromJson: jsonFormatedDictionary) } } } return nil } }
// // ExpositionViewController.swift // Expo1900 // // Created by 이영우 on 2021/04/12. // import UIKit final class ExpositionViewController: UIViewController { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var visitorsLabel: UILabel! @IBOutlet private weak var posterImageView: UIImageView! @IBOutlet private weak var locationLabel: UILabel! @IBOutlet private weak var durationLabel: UILabel! @IBOutlet private weak var descriptionLabel: UILabel! @IBOutlet private weak var itemsListPageButton: UIButton! @IBOutlet private weak var leftOnButtonImageView: UIImageView! @IBOutlet private weak var rightOnButtonImageView: UIImageView! private var expoData: Exposition? private let navigationTitle: String = "메인" private let posterImage: String = "poster" private let flagImage: String = "flag" private let listPageButtonTitle = "한국의 출품작 보러가기" private let prePhraseVisitors: String = "방문객 : " private let prePhraseLocation: String = "개최지 : " private let prePhraseDuration: String = "개최 기간 : " private let appDelegate = UIApplication.shared.delegate as? AppDelegate override func viewDidLoad() { super.viewDidLoad() decodeExpoData() setTitleLabelAttribute() initializeViews() self.navigationItem.title = navigationTitle } override func viewWillAppear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = true appDelegate?.shouldSelectPortrait = true let orientationValue = UIInterfaceOrientationMask.portrait.rawValue UIDevice.current.setValue(orientationValue, forKey: "orientation") } private func decodeExpoData() { guard let dataAsset: NSDataAsset = NSDataAsset(name: "exposition_universelle_1900", bundle: .main) else { return } do { self.expoData = try JSONDecoder().decode(Exposition.self, from: dataAsset.data) } catch { implementErrorAlert(ExpoError.invalidExpoData) } } private func initializeViews() { guard let data = expoData else { return } titleLabel.text = data.title.replacingOccurrences(of: "(", with: "\n(") visitorsLabel.text = prePhraseVisitors + data.visitorsStringFormat locationLabel.text = prePhraseLocation + data.location durationLabel.text = prePhraseDuration + data.duration descriptionLabel.text = data.description posterImageView.image = UIImage(named: posterImage) itemsListPageButton.setTitle(listPageButtonTitle, for: .normal) leftOnButtonImageView.image = UIImage(named: flagImage) rightOnButtonImageView.image = UIImage(named: flagImage) } private func setTitleLabelAttribute() { titleLabel.textAlignment = .center titleLabel.numberOfLines = Int.zero visitorsLabel.numberOfLines = Int.zero locationLabel.numberOfLines = Int.zero durationLabel.numberOfLines = Int.zero descriptionLabel.numberOfLines = Int.zero } @IBAction private func pushItemsListPageButton(_ sender: UIButton) { let storyboard = UIStoryboard(name: "Main", bundle: .main) let viewController = storyboard.instantiateViewController(identifier: "KoreanItemsListVC") self.navigationController?.pushViewController(viewController, animated: true) } }
import UIKit class TransactionResponsePresenter : NSObject {} extension TransactionResponsePresenter : TransactionResponseViewControllerDelegate { func getViewData(refID: String, parentRefID: String, viewController: TransactionResponseViewControllerInput) { guard let projectID = viewController.projectID else { return } let transactionID = refID let serviceID = parentRefID viewController.displayLoadingIndicator() viewController.displayBlockedLoadingIndicator() Composed .action(UseCaseBuildAndSendTransaction.action(projectID: projectID, serviceID: serviceID, transactionID: transactionID)) .onFailure { error in let error = error as? PCError DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { viewController.hideLoadingIndicator() viewController.hideBlockedLoadingIndicator() viewController.presentBasicAlert(title: "Hsss! Grrr.", message: error?.text, button: "Meow!", handler: nil) } } .execute { result in let result = result! let viewData = TransactionResponseViewDataBuilder.constructViewData( transaction: result.transaction, response: result.response ) DispatchQueue.main.async { viewController.displayViewData(viewData) } if (result.transaction.parsing) { UseCaseParseParser .action(response: result.response, transaction: result.transaction, projectID: projectID) .execute() } DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { viewController.hideLoadingIndicator() viewController.hideBlockedLoadingIndicator() } } } }
// // InfoViewController.swift // BFKitDemo // // Created by Fabrizio on 24/06/15. // Copyright (c) 2015 Fabrizio Brancati. All rights reserved. // import UIKit class InfoViewController : UIViewController { @IBAction func closeInfo(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } }
// // ViewController.swift // AlamofireRequest // // Created by chao on 2021/3/26. // import UIKit import Alamofire class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func GetPostClick(_ sender: UIButton) { let urlString = "http:baidu.com?page=1" // AF.request(<#T##convertible: URLConvertible##URLConvertible#>) // AF.request(<#T##convertible: URLRequestConvertible##URLRequestConvertible#>) // AF.request(<#T##convertible: URLRequestConvertible##URLRequestConvertible#>, interceptor: <#T##RequestInterceptor?#>) // AF.request(<#T##convertible: URLConvertible##URLConvertible#>, method: <#T##HTTPMethod#>, parameters: <#T##Encodable?#>, encoder: <#T##ParameterEncoder#>, headers: <#T##HTTPHeaders?#>, interceptor: <#T##RequestInterceptor?#>, requestModifier: <#T##Session.RequestModifier?##Session.RequestModifier?##(inout URLRequest) throws -> Void#>) let adapter = ECAdapter() // AF.request(urlString, method: .get, parameters: ["siteId":"100000"], encoding:JSONEncoding.default , headers: nil, interceptor: adapter, requestModifier: nil).re AF.request(urlString, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil, interceptor: adapter, requestModifier: nil).responseJSON { (res) in print(res); } // let request = AF.request(urlString).responseJSON { (resp) in // print(resp) // // } } }
// // Renderables.swift // RayTraceUI // // Created by Neal Sidhwaney on 9/24/20. // Copyright © 2020 Neal Sidhwaney. All rights reserved. // import Foundation import simd enum BoundsDictKey { case MINX case MAXX case MINY case MAXY case MINZ case MAXZ } protocol WorldObject { func intersections(origin: v3d, direction: v3d, intersections : inout [Intersection]) var isBounding : Bool { get } func getBoundedIntersectables() -> [WorldObject] func getBounds() -> [BoundsDictKey : Double] var material : Material? { get } } class PointLight : NSObject, WorldObject { let specular : RGB // specular intensity let location : v3d let diffuse : RGB // diffuse intensity var material : Material? { get { return nil } } // KVC helpers, since types we use are Swift structs and not KVC. @objc dynamic var specularString : String { return self.specular.description } @objc dynamic var diffuseString : String { return self.diffuse.description } @objc dynamic var x : v3d.ArrayLiteralElement { get { return location.x } } @objc dynamic var y : v3d.ArrayLiteralElement { get { return location.y } } @objc dynamic var z : v3d.ArrayLiteralElement { get { return location.z } } init (atLocation location : v3d, specular : RGB, diffuse : RGB) { self.location = location self.specular = specular self.diffuse = diffuse } func intersections(origin: v3d, direction: v3d, intersections : inout [Intersection]) { // origin + t*direction = location at what t let t = (location - origin) / direction if (t.x >= 0.0000001 && eq3(t.x, t.y, t.z)) { intersections.append(Intersection(atPoint: origin + t.x * direction, parameter: t.x, object: self)) } } var isBounding : Bool { get { return false } } func getBoundedIntersectables() -> [WorldObject] { return [] } func getBounds() -> [BoundsDictKey : Double] { return [ .MINX : location.x, .MAXX : location.x, .MINY : location.y, .MAXY : location.y, .MINZ : location.z, .MAXZ : location.z ] } } struct Triangle : WorldObject { var material : Material? let vertices : [v3d] init(_ points : [v3d], material : Material?) { self.vertices = points self.material = material assert(points.count == 3) } var isBounding : Bool { get { return false } } func getBoundedIntersectables() -> [WorldObject] { return [] } func intersections(origin: v3d, direction: v3d, intersections: inout [Intersection]) { let v0v1 = vertices[1] - vertices[0] let v0v2 = vertices[2] - vertices[0] let v1v2 = vertices[2] - vertices[1] let v2v0 = -v0v2 let normal = normalize(cross(v0v1, v0v2)) let planeConstant = dp(normal, vertices[0]) let nddot = dp(normal, -direction) if nddot <= 0 { // back side of triangle or the ray is parallel to the triangle. return } let intersectionParameter = (planeConstant - dp(normal, origin)) / -nddot // TODO fix negative sign (should be on origin?) if (intersectionParameter > 0) { let point : v3d = origin + intersectionParameter * direction let v0p = point - vertices[0] let v1p = point - vertices[1] let v2p = point - vertices[2] let a = cross(v0v1, v0p) let b = cross(v1v2, v1p) let c = cross(v2v0, v2p) if dp(a, normal) >= 0 && dp(b, normal) >= 0 && dp(c, normal) >= 0 { intersections.append(Intersection(atPoint: point, withNormal: normal, parameter: intersectionParameter, object: self)) } } } func getBounds() -> [BoundsDictKey : Double] { var minX, maxX, minY, maxY, minZ, maxZ : Double minX = Double.infinity minY = Double.infinity minZ = Double.infinity maxX = -Double.infinity maxY = -Double.infinity maxZ = -Double.infinity vertices.forEach { (vertex : v3d) in setOnCondition(A : &minX, toB : vertex.x, ifTrue : >) setOnCondition(A : &minY, toB : vertex.y, ifTrue : >) setOnCondition(A : &minZ, toB : vertex.z, ifTrue : >) setOnCondition(A : &maxX, toB : vertex.x, ifTrue : <) setOnCondition(A : &maxY, toB : vertex.y, ifTrue : <) setOnCondition(A : &maxZ, toB : vertex.z, ifTrue : <) } return [ .MINX : minX, .MAXX : maxX, .MINY : minY, .MAXY : maxY, .MINZ : minZ, .MAXZ : maxZ ] } } struct Sphere : WorldObject { var location: v3d let radius : Double let radiusSquared : Double let bounding : Bool let boundedShapes : [WorldObject] var material : Material? = nil init(_ sphereCenter : v3d, _ sphereRadius : Double) { self.location = sphereCenter self.radius = sphereRadius self.radiusSquared = pow(self.radius, 2) self.bounding = false self.boundedShapes = [] } init(boundingObjects : [WorldObject]) { var minX, maxX, minY, maxY, minZ, maxZ : Double minX = Double.infinity minY = Double.infinity minZ = Double.infinity maxX = -Double.infinity maxY = -Double.infinity maxZ = -Double.infinity for intersectable in boundingObjects { let boundsDict = intersectable.getBounds() setOnCondition(A: &minX, toB: boundsDict[.MINX]!, ifTrue: >) setOnCondition(A: &minY, toB: boundsDict[.MINY]!, ifTrue: >) setOnCondition(A: &minZ, toB: boundsDict[.MINZ]!, ifTrue: >) setOnCondition(A: &maxX, toB: boundsDict[.MAXX]!, ifTrue: <) setOnCondition(A: &maxY, toB: boundsDict[.MAXY]!, ifTrue: <) setOnCondition(A: &maxZ, toB: boundsDict[.MAXZ]!, ifTrue: <) } let xDistance = abs(maxX - minX) let yDistance = abs(maxY - minY) let zDistance = abs(maxZ - minZ) self.radius = [xDistance, yDistance, zDistance].max()! / 2 self.location = v3d(maxX - (xDistance / 2), maxY - (yDistance / 2), maxZ - (zDistance / 2)) self.radiusSquared = pow(self.radius, 2) self.boundedShapes = boundingObjects self.bounding = true } func intersections(origin : v3d, direction : v3d, intersections : inout [Intersection]) { let centerToEye = origin - location let a = -dp(direction, centerToEye) let delta = pow(a, 2) - (lenSquared(centerToEye) - radiusSquared) if delta < 0 { // No intersections. return } let sqrtdelta = sqrt(delta) var d : [Double] = [] if delta == 0 { d = [a] } else { let t1 = a + sqrtdelta let t2 = a - sqrtdelta if t1 < t2 { d = [t1, t2] } else { d = [t2, t1] } } d.filter({ $0 >= 0.0000001 }).forEach() { let p : v3d = origin + $0 * direction let normalAtPoint = normalize(p - location) intersections.append(Intersection(atPoint: p, withNormal: normalAtPoint, parameter: $0, object : self)) } } func getBounds() -> [BoundsDictKey : Double] { return [ .MINX : location.x - radius, .MAXX : location.x + radius, .MINY : location.y - radius, .MAXY : location.y + radius, .MINZ : location.z - radius, .MAXZ : location.z + radius ] } func getBoundedIntersectables() -> [WorldObject] { return boundedShapes } var isBounding : Bool { get { return bounding } } }
// // InfoViewController.swift // 01-rgbColorPicker // // Created by Alberto Talaván on 31/05/2020. // Copyright © 2020 Alberto Talavan. All rights reserved. // import UIKit import WebKit class InfoViewController: UIViewController { var colorType: String? var color: UIColor? @IBOutlet weak var webView: WKWebView! @IBOutlet weak var closeButton: UIButton! override func viewDidLoad() { super.viewDidLoad() configureButton() simpleNetworkRequest() } @IBAction func close (_ sender: UIButton) { dismiss(animated: true, completion: nil) } func simpleNetworkRequest(){ //https://en.wikipedia.org/wiki/RGB_color_model //https://en.wikipedia.org/wiki/HSL_and_HSV var urlString: String = "" let request: URLRequest if let colorType = colorType { if colorType == "rgb" { urlString = "https://en.wikipedia.org/wiki/RGB_color_model" }else if colorType == "hsb" { urlString = "https://en.wikipedia.org/wiki/HSL_and_HSV" } } else { urlString = "https://en.wikipedia.org/wiki/RGB_color_model" } request = URLRequest(url: URL(string: urlString)!) webView.load(request) } @IBAction func closeButtonPressed(_ sender: UIButton) { dismiss(animated: true) } func configureButton(){ closeButton.layer.cornerRadius = 5 closeButton.layer.borderWidth = 1 closeButton.backgroundColor = color } }
// // DataManager.swift // TodayNews // // Created by Ron Rith on 1/19/18. // Copyright © 2018 Ron Rith. All rights reserved. // import Foundation struct DataManager{ struct URL{ static let BASE = "https://newiosapi.herokuapp.com/rest" static let NEWS = BASE + "/news/" static let NEWS_SAVE = NEWS + "save/{newsTypeDesEn}/{email}/{authorEmail}" static let FILE = "https://newiosapi.herokuapp.com/rest/uploadfile" static let NEWS_SAVE_DEAUL = "https://newiosapi.herokuapp.com/rest/news/save/Sport/rithronlkh%40gmail.com/author1%40gmail.com" static let NEWS_SAVE_DEFAUL = "https://newiosapi.herokuapp.com/rest/news/save" //user static let USER_LOGIN = "https://newiosapi.herokuapp.com/rest/users/login" static let USER_SIGNUP = "https://newiosapi.herokuapp.com/rest/users" //newstype static let NEWSTYPE = "https://newiosapi.herokuapp.com/rest/newstype" //author static let AUTHOR = "https://newiosapi.herokuapp.com/rest/authors" //newstype and author static let NEWSTYPE_AUTHOR = "https://newiosapi.herokuapp.com/rest/newstypeandauthors" } static let HEADER = ["Authorization":"Basic cml0aHJvbmxraEBnbWFpbC5jb206MTIzNDU2"] //https://newiosapi.herokuapp.com/rest/news/14 }
// // UserDataViewModel.swift // Examenios1 // // Created by Wilder Lopez on 10/23/21. // import Foundation import UIKit protocol UserDataDelegate { func uploadUserData(isSuccess: Bool) } class UserDataViewModel { var delegate : UserDataDelegate? init(delegate: UserDataDelegate) { self.delegate = delegate } func uploadUserData(username: String, imageData: Data){ let imagePath = "image/\(username).png" MyFirebaseManager.share.uploadImage(path: imagePath, imageData: imageData) { isSuccess in if isSuccess{ MyFirebaseManager.share.addUserInfo(username: username, imagePath: imagePath) { isSuccess in self.delegate?.uploadUserData(isSuccess: isSuccess) } }else { self.delegate?.uploadUserData(isSuccess: false) } } } }
// // Accenture_iOSTests.swift // Accenture_iOSTests // // Created by XTGlobal on 21/12/20. // Copyright © 2020 Goutham. All rights reserved. // import XCTest @testable import Accenture_iOS class Accenture_iOSTests: XCTestCase { var apiService: APIService! var session : URLSession! override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func test_get_request_withURL() { guard let url = URL(string: "https://api.mocki.io/v1/4f436f3b") else { fatalError("URL can't be empty") } URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in if error != nil { XCTFail("Fail") } } self.waitForExpectations(timeout: 20) } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
// // main.swift // algorithm.swift // // Created by yaoning on 2020/1/3. // Copyright © 2020 yaoning. All rights reserved. // import Foundation print("Hello, World!") // 数组类型题目 //Solution26.test() //Solution27.test() //Solution80.test() //Solution189.test() //Solution41.test() //Solution299.test() //Soution134.test() //Solution118.test() //Solution119.test() //Solution16.test() //Solution53.test() //------------------------------ //Solution01.test() //Solution02.test() //Solution03.test() //Solution05.test() // 二分查找类型题目 //------------------------------ //Solution278.test() //Solution35.test() //Solution33.test() //Solution81.test() // 链表相关题目 //------------------------------ //Solution206.test() //Solution198.test() // 树相关题目 //------------------------------- //Solution113.test() //Tree.test() //let sizeMB = String(format: "%.2f", Float(22222222) / (1024 * 1024)) //print("sizeMB: \(sizeMB)") // Hot 100 //Solution198.test() //Solution300.test() //Solution70.test() //Solution64.test() //Solution139.test() //Solution406.test() //Solution114.test() //Solution236.test() //Solution347.test() Solution912.test()
// // GalleryView.swift // Pusher // // Created by 奚锐的Mac on 2020/6/11. // Copyright © 2020 奚锐的Mac. All rights reserved. // import SwiftUI struct GalleryView: View { var body: some View { ScrollView(.vertical,showsIndicators: true) { VStack(spacing:0) { ScrollView(.horizontal,showsIndicators: false){ HStack(spacing: 40.0) { ForEach(0..<3){ value in GeometryReader { geo in EventItem(backGroundColor: Color("CalendarGalaryBackGround"),Title:"事件",SecondTitle: "地点",Content: "时间") .padding([.top, .leading, .bottom], 20.0) .rotation3DEffect(Angle(degrees: Double(geo.frame(in:.global).minX)/20), axis: (x:0,y:10,z:0)) }.frame(width :300,height: 240) } } } ScrollView(.horizontal,showsIndicators: false){ HStack(spacing: 40.0) { ForEach(0..<3){ value in GeometryReader { geo in OperationItem(backGroundColor: Color("OperationBackground"),Title:"操作",SecondTitle: "链接",Content: "备注") .padding([.top, .leading, .bottom], 20.0) .rotation3DEffect(Angle(degrees: Double(geo.frame(in:.global).minX)/20), axis: (x:0,y:10,z:0)) }.frame(width :300,height: 240) } } } ScrollView(.horizontal,showsIndicators: false){ HStack(spacing: 40.0) { ForEach(0..<3){ value in GeometryReader { geo in TipItem(backGroundColor: Color("TipBackGround"),Title:"提示",Content: "内容") .padding([.top, .leading, .bottom], 20.0) .rotation3DEffect(Angle(degrees: Double(geo.frame(in:.global).minX)/20), axis: (x:0,y:10,z:0)) }.frame(width :300,height: 240) } } } }.navigationBarTitle(Text("detail")) } } struct GalleryView_Previews: PreviewProvider { static var previews: some View { GalleryView() } } struct EventItem: View { @State var finishAlert = false @State var backGroundColor : Color @State var Title : String! @State var SecondTitle : String! @State var Content : String! var body: some View { ZStack { VStack(alignment: .leading, spacing: 10.0) { HStack { Image(systemName: "calendar") .font(.title) .foregroundColor(.white) Text(self.Title) .font(.title) .multilineTextAlignment(.leading) .foregroundColor(.white) Spacer() }.padding([.top, .leading, .trailing], 15.0) Text(self.SecondTitle) .foregroundColor(.white ) .padding(.horizontal) Text(self.Content) .foregroundColor(.white ) .padding(.horizontal) Spacer() } .background(self.backGroundColor) .cornerRadius(20) .shadow(radius: 5) .frame(width:300,height:150) VStack { Spacer() HStack(spacing:10.0){ Spacer() Button(action: { self.finishAlert = true }) { Image(systemName: "command") .frame(width:12,height:12) .padding(.all) } .background(Color("AcceptButton")) .cornerRadius(20) .alert(isPresented:self.$finishAlert){ Alert(title: Text("已添加到日历中"), message: Text("Message"), dismissButton: .default(Text("dismiss"))) } Button(action: {}) { Image(systemName: "trash") .frame(width:12,height:12) .padding(.all) } .background(Color("RejectButtonBackground")) .cornerRadius(20) }.offset(x:0,y:0) } } } } struct OperationItem: View { @State var finishAlert = false @State var backGroundColor : Color @State var Title : String! @State var SecondTitle : String! @State var Content : String! var body: some View { ZStack { VStack(alignment: .leading, spacing: 10.0) { HStack { Image(systemName: "calendar") .font(.title) .foregroundColor(.white) Text(self.Title) .font(.title) .multilineTextAlignment(.leading) .foregroundColor(.white) Spacer() }.padding([.top, .leading, .trailing], 15.0) Text(self.SecondTitle) .foregroundColor(.white ) .padding(.horizontal) Text(self.Content) .foregroundColor(.white ) .padding(.horizontal) Spacer() } .background(self.backGroundColor) .cornerRadius(20) .shadow(radius: 5) .frame(width:300,height:150) VStack { Spacer() HStack(spacing:10.0){ Spacer() Button(action: { self.finishAlert = true }) { Image(systemName: "airplane") .frame(width:12,height:12) .padding(.all) } .background(Color("AcceptButton")) .cornerRadius(20) .alert(isPresented:self.$finishAlert){ Alert(title: Text("正在跳转到网站"), message: Text("即将前往目标应用"), dismissButton: .default(Text("好的"))) } Button(action: {}) { Image(systemName: "trash") .frame(width:12,height:12) .padding(.all) } .background(Color("RejectButtonBackground")) .cornerRadius(20) }.offset(x:0,y:0) } } } } } struct TipItem: View { @State var finishAlert = false @State var backGroundColor : Color @State var Title : String! @State var Content : String! var body: some View { ZStack { VStack(alignment: .leading, spacing: 10.0) { HStack { Image(systemName: "calendar") .font(.title) .foregroundColor(.white) Text(self.Title) .font(.title) .multilineTextAlignment(.leading) .foregroundColor(.white) Spacer() }.padding([.top, .leading, .trailing], 15.0) Text(self.Content) .foregroundColor(.white ) .padding(.horizontal) Spacer() } .background(self.backGroundColor) .cornerRadius(20) .shadow(radius: 5) .frame(width:300,height:150) VStack { Spacer() HStack(spacing:10.0){ Spacer() Button(action: { self.finishAlert = true }) { Image(systemName: "heart") .frame(width:12,height:12) .padding(.all) .foregroundColor(Color.red) } .background(Color("AcceptButton")) .cornerRadius(20) .alert(isPresented:self.$finishAlert){ Alert(title: Text("正在跳转到网站"), message: Text("即将前往目标应用"), dismissButton: .default(Text("好的"))) } Button(action: {}) { Image(systemName: "trash") .frame(width:12,height:12) .padding(.all) } .background(Color("RejectButtonBackground")) .cornerRadius(20) }.offset(x:0,y:0) } } } }
// // UnboxSpeedTests.swift // SwiftJSONSpeed // // Created by Miquel, Aram on 28/04/2016. // Copyright © 2016 Ryanair. All rights reserved. // import XCTest import Unbox class UnboxSpeedTests: XCTestCase { func testOneSimpleUnboxer() { func test(data: Data) { do { let _: Person = try unbox(data: data) } catch { } } let data = loadTestData("SimpleJSON")! self.measure { test(data: data) } } func testManySimpleUnboxer() { func test(data: Data) { do { let _: Person = try unbox(data: data) } catch { } } let data = loadTestData("SimpleJSON")! self.measure { for _ in 0...1000 { test(data: data) } } } // Unboxer can't unbox a double array!! https://github.com/JohnSundell/Unbox/issues/34 func testComplexUnboxer() { func test(data: Data) { do { let _: PersonList = try unbox(data: data) } catch { } } let data = loadTestData("ComplexJSON")! // We have to add a key so we can parse the JSON: Arrays without keys are not supported let stringWithPeopleKey = "{\"people\":\n\(String(data: data, encoding: String.Encoding.utf8)!)}" let dataWithPeopleKey = stringWithPeopleKey.data(using: String.Encoding.utf8)! self.measure { test(data: dataWithPeopleKey) } } }
// // CityList.swift // Carousel // // Created by Andrey on 26.04.17. // Copyright © 2017 Quest. All rights reserved. // import Foundation enum CityList: Int { case YoshkarOla case Kazan case Moscow case Count func toStringValue() -> String { switch self { case .YoshkarOla: return "Йошкар-Ола" case .Kazan: return "Казань" case .Moscow: return "Москва" default: return "" } } func toImageValue() -> String { switch self { case .YoshkarOla: return "cityYoshkarOla" case .Kazan: return "cityKazan" case .Moscow: return "cityMoscow" default: return "" } } }
// // RelatedResultCell.swift // appstoreSearch // // Created by Elon on 18/03/2019. // Copyright © 2019 Elon. All rights reserved. // import UIKit final class RelatedResultCell: UITableViewCell { @IBOutlet weak var searchIconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var lineView: UIView! static let identifier = "RelatedResultCell" override func awakeFromNib() { super.awakeFromNib() titleLabel.text = "" } override func prepareForReuse() { super.prepareForReuse() titleLabel.text = "" } } extension RelatedResultCell { func setTitle(text: String, with searchText: String) { let whiteColor = UIColor(white: 0.56, alpha: 1.0) let attributedString = text.attribute(size: 14, weight: .regular, color: whiteColor) let nsString = NSString(string: text) let range = nsString.range(of: searchText) attributedString.addAttribute(.foregroundColor, value: UIColor.black, range: range) titleLabel.attributedText = attributedString } }
// // DateExtensions.swift // MVVM_Demo // // Created by Hoang Lam on 22/09/2021. // import Foundation import UIKit extension Date { func convertDateToString() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" return dateFormatter.string(from: self) } }
// // SCTiledImageContainerView.swift // SCTiledImage // // Created by Yan Smaliak on 05/07/2023. // import UIKit // MARK: - SCTiledImageContainerView final class SCTiledImageContainerView: UIView { // MARK: - Internal Properties var contentView: SCTiledImageContentView? var dataSource: SCTiledImageViewDataSource? // MARK: - Internal Methods func setup(dataSource: SCTiledImageViewDataSource) { self.dataSource = dataSource contentView = SCTiledImageContentView(dataSource: dataSource) frame = contentView!.frame if let contentView { if !subviews.contains(contentView) { addSubview(contentView) } contentView.center = CGPoint(x: bounds.midX, y: bounds.midY) } } }