text
stringlengths
8
1.32M
// // ReceiveContainerViewController.swift // WavesWallet-iOS // // Created by Pavel Gubin on 10/2/18. // Copyright © 2018 Waves Platform. All rights reserved. // import UIKit import DomainLayer private enum Constants { static let minScrollOffsetOnKeyboardDismiss: CGFloat = -0.3 } final class ReceiveContainerViewController: UIViewController { private var viewControllers: [UIViewController] = [] private var states: [Receive.ViewModel.State] = [] private var selectedState: Receive.ViewModel.State! @IBOutlet private weak var segmentedControl: SegmentedControl! @IBOutlet private weak var scrollViewContainer: UIScrollView! @IBOutlet private weak var scrollView: UIScrollView! var asset: DomainLayer.DTO.SmartAssetBalance? override func viewDidLoad() { super.viewDidLoad() title = Localizable.Waves.Receive.Label.receive createBackButton() setupControllers() setupSegmentedControl() setupSwipeGestures() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc private func keyboardWillHide() { //TODO: - Need to find good solution to show big nav bar when it small on dismissKeyboard if isShowNotFullBigNavigationBar { scrollView.setContentOffset(CGPoint(x: 0, y: Constants.minScrollOffsetOnKeyboardDismiss), animated: true) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupBigNavigationBar() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() for view in scrollViewContainer.subviews { view.frame.size.width = scrollViewContainer.frame.size.width view.frame.size.height = scrollViewContainer.frame.size.height } } } //MARK: - Actions private extension ReceiveContainerViewController { func scrollToPage(_ page: Int) { view.endEditing(true) let offset = CGPoint(x: CGFloat(page) * scrollViewContainer.frame.size.width, y: 0) scrollViewContainer.setContentOffset(offset, animated: true) } @IBAction func segmentedDidChange(_ sender: Any) { guard let state = Receive.ViewModel.State(rawValue: segmentedControl.selectedIndex) else { return } selectedState = state scrollToPage(selectedState.rawValue) } @objc func handleGesture(_ gesture: UISwipeGestureRecognizer) { if gesture.direction == .left { let index = segmentedControl.selectedIndex + 1 if index < viewControllers.count { guard let state = Receive.ViewModel.State(rawValue: index) else { return } selectedState = state segmentedControl.setSelectedIndex(state.rawValue, animation: true) scrollToPage(state.rawValue) } } else if gesture.direction == .right { let index = selectedState.rawValue - 1 if index >= 0 { guard let state = Receive.ViewModel.State(rawValue: index) else { return } selectedState = state segmentedControl.setSelectedIndex(state.rawValue, animation: true) scrollToPage(state.rawValue) } } } } //MARK: - SetupUI private extension ReceiveContainerViewController { func setupControllers() { let scrollWidth = UIScreen.main.bounds.size.width for (index, viewController) in viewControllers.enumerated() { scrollViewContainer.addSubview(viewController.view) viewController.view.frame.origin.x = CGFloat(index) * scrollWidth addChild(viewController) viewController.didMove(toParent: self) } scrollViewContainer.contentSize = CGSize(width: CGFloat(viewControllers.count) * scrollWidth, height: scrollViewContainer.contentSize.height) } func setupSwipeGestures() { let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture(_:))) scrollViewContainer.addGestureRecognizer(swipeRight) let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture(_:))) swipeLeft.direction = .left scrollViewContainer.addGestureRecognizer(swipeLeft) } func setupSegmentedControl() { var buttons: [SegmentedControl.Button] = [] for state in states { if state == .cryptoCurrency { buttons.append(.init(name: Localizable.Waves.Receive.Button.cryptocurrency, icon: .init(normal: Images.rGateway14Basic500.image, selected: Images.rGateway14White.image))) } else if state == .invoice { buttons.append(.init(name: Localizable.Waves.Receive.Button.invoice, icon: .init(normal: Images.rInwaves14Basic500.image, selected: Images.rInwaves14White.image))) } else if state == .card { buttons.append(.init(name: Localizable.Waves.Receive.Button.card, icon: .init(normal: Images.rCard14Basic500.image, selected: Images.rCard14White.image))) } } segmentedControl.update(with: buttons) } } //MARK: UIScrollViewDelegate extension ReceiveContainerViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { setupTopBarLine() } } //MARK: - Methods extension ReceiveContainerViewController { func add(_ viewController: UIViewController, state: Receive.ViewModel.State) { viewControllers.append(viewController) states.append(state) selectedState = states[0] } }
// // config.swift // gjs_user // // Created by 大杉网络 on 2019/8/22. // Copyright © 2019 大杉网络. All rights reserved. // import Foundation let netmanager: SessionManager = { let configuration = URLSessionConfiguration.default let reachability = NetworkReachabilityManager() if (reachability?.isReachable)! { configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData }else { configuration.requestCachePolicy = .returnCacheDataElseLoad } return Alamofire.SessionManager(configuration: configuration) }()
import UIKit extension HomeController { func localizationButtonsImLearn(_ Learn: String) { print(Learn) } }
// // UIImageExtension.swift // PassportOCR // // Created by Михаил on 11.09.16. // Copyright © 2016 empatika. All rights reserved. // import Foundation import UIKit import GPUImage extension UIImage { func croppedImageWithSize(rect: CGRect) -> UIImage { let imageRef: CGImageRef! = CGImageCreateWithImageInRect(self.CGImage!, rect) let croppedImage: UIImage = UIImage(CGImage: imageRef, scale: self.scale, orientation: self.imageOrientation) let selectedFilter = GPUImageTransformFilter() selectedFilter.setInputRotation(kGPUImageNoRotation, atIndex: 0) let image: UIImage = selectedFilter.imageByFilteringImage(croppedImage) return image } func save(path: String) { let png = UIImagePNGRepresentation(self) png?.writeToFile(path, atomically: true) } }
// // Int+Helpers.swift // MMWallet // // Created by Dmitry Muravev on 14.07.2018. // Copyright © 2018 micromoney. All rights reserved. // import Foundation extension Int { mutating func increment() -> Int { self += 1 return self } func convertToMinutes() -> (Int, Int) { return (self / 60, self % 60) } }
// // DateExtensions+.swift // GitStars // // Created by Edson iMAC on 25/01/2019. // Copyright © 2019 Edson Moura. All rights reserved. // import Foundation extension Date { static func fromString(_ stringDate: String) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SSSZ" guard let date = dateFormatter.date(from: stringDate) else { fatalError("Couldn't parse date") } return date } //Example: 16/Out var abbreviatedDayAndMonth: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MMM" return dateFormatter.string(from: self) } //Example: 10h34 var commercialTime: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH'h'mm" return dateFormatter.string(from: self) } //Example: 10H34 var abbreviatedYearMonthDay: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: self) } //Example: 06/Jun, 20:30 var dayMonthAndTime: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MMM, hh'H" return dateFormatter.string(from: self) } //Qui, 13 jun var dayWeekDayAndMonth: String { let locale = Locale(identifier: "pt_BR") let dateFormatter = DateFormatter() dateFormatter.locale = locale dateFormatter.dateFormat = "EE, dd MMM" return dateFormatter.string(from: self) } var dayMonthAndWeekDay: String { let locale = Locale(identifier: "pt_BR") let dateFormatter = DateFormatter() dateFormatter.locale = locale dateFormatter.dateFormat = "dd MMM, EEEE" return dateFormatter.string(from: self) } var weekdayDayAndMonth: String { let locale = Locale(identifier: "pt_BR") let dateFormatter = DateFormatter() dateFormatter.locale = locale dateFormatter.dateFormat = "EEEE, dd 'de' MMMM 'de' YYYY" return dateFormatter.string(from: self) } }
// // ViewController.swift // HellaCollectionCells // // Created by Flatiron School on 10/6/16. // Copyright © 2016 Flatiron School. All rights reserved. // import UIKit class HellaViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! // var fibonnaciNumbersArray: [Int] = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987] func fiboArray () -> [Int] { var array = [0,1] for i in 0...15 { let fiboNumber = array[array.count - 2] + array[array.count - 1] array.append(fiboNumber) } return array } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Collection View DataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) var number = indexPath.item if fiboArray().contains(indexPath.item) { cell.backgroundColor = UIColor.purple } else { cell.backgroundColor = UIColor.yellow } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueDetailView" { print(1) if let dest = segue.destination as? HellaDetailViewController, let arrayIndex = collectionView.indexPathsForSelectedItems { print(2) dest.numbersText = String(arrayIndex[0].item) } } } }
// // User.swift // NeCTARClient // // Created by Ding Wang on 16/8/4. // Copyright © 2016年 Ding Wang. All rights reserved. // import Foundation import SwiftyJSON struct User { var tokenID: String var tenantID: String var tenantDescription: String var tenantName: String var dnsServiceURL: String var computeServiceURL: String var networkServiceURL: String var volumnV2ServiceURL: String var S3ServiceURL: String var alarmingServiceURL: String var imageServiceURL: String var meteringServiceURL: String var cloudformationServiceURL: String var applicationCatalogURL: String var volumnV1ServiceURL: String var EC2ServiceURL: String var orchestrationServiceURL: String var username: String var userId: Int var owner: String var volumeV3ServiceURL: String init?(json:JSON) { let accessInfo = json["access"] let token = accessInfo["token"] let serviceCatalog = accessInfo["serviceCatalog"].arrayValue let userInfo = accessInfo["user"] self.tokenID = token["id"].stringValue self.tenantName = token["tenant"]["name"].stringValue self.tenantID = token["tenant"]["id"].stringValue self.tenantDescription = token["tenant"]["description"].stringValue self.dnsServiceURL = serviceCatalog[0]["endpoints"][0]["publicURL"].stringValue self.computeServiceURL = serviceCatalog[1]["endpoints"][0]["publicURL"].stringValue self.networkServiceURL = serviceCatalog[2]["endpoints"][0]["publicURL"].stringValue self.volumnV2ServiceURL = serviceCatalog[3]["endpoints"][0]["publicURL"].stringValue self.S3ServiceURL = serviceCatalog[4]["endpoints"][0]["publicURL"].stringValue self.alarmingServiceURL = serviceCatalog[5]["endpoints"][0]["publicURL"].stringValue self.imageServiceURL = serviceCatalog[6]["endpoints"][0]["publicURL"].stringValue self.meteringServiceURL = serviceCatalog[7]["endpoints"][0]["publicURL"].stringValue self.cloudformationServiceURL = serviceCatalog[8]["endpoints"][0]["publicURL"].stringValue self.applicationCatalogURL = serviceCatalog[9]["endpoints"][0]["publicURL"].stringValue self.volumnV1ServiceURL = serviceCatalog[10]["endpoints"][0]["publicURL"].stringValue self.EC2ServiceURL = serviceCatalog[11]["endpoints"][0]["publicURL"].stringValue self.orchestrationServiceURL = serviceCatalog[12]["endpoints"][0]["publicURL"].stringValue self.username = userInfo["username"].stringValue self.userId = userInfo["id"].intValue self.owner = orchestrationServiceURL.componentsSeparatedByString("/")[4] self.volumeV3ServiceURL = "https://cinder.rc.nectar.org.au:8776/" } }
// Copyright 2017 IBM RESEARCH. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= import Foundation /** Qubit reset */ public final class Reset: Instruction { public init(_ qreg: QuantumRegister, _ circuit: QuantumCircuit? = nil) { super.init("reset", [], [qreg], circuit) } public init(_ qubit: QuantumRegisterTuple, _ circuit: QuantumCircuit? = nil) { super.init("reset", [], [qubit], circuit) } public override var description: String { return "\(name) \(self.args[0].identifier)" } /** Reapply this gate to corresponding qubits in circ. */ public func reapply(circ: QuantumCircuit) { // self._modifiers(circ.reset(self.arg[0])) } }
// // AddShopListViewController.swift // Galven // // Created by Dennis Galvén on 2019-06-05. // Copyright © 2019 GalvenD. All rights reserved. // import UIKit class AddShopListViewController: ThemedViewController, UITextFieldDelegate { fileprivate var tableView: ShoplistTableView! fileprivate var shoplistTableviewDelegateDatasource: ShoplistTableviewDatasourceDelegate? fileprivate var currentContent: [ShopItemModel]? fileprivate var items = [ShopItemModel]() { didSet { shoplistTableviewDelegateDatasource?.items = items.sorted { $0.date > $1.date } tableView.reloadData() shopItemTextField.text = "" amountItemTextField.text = "" } } fileprivate lazy var shopItemTextField: UITextField = { let textField = UITextField() textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) textField.placeholder = "shop_item".localizedCapitalizedFirstLetter textField.borderStyle = .roundedRect textField.delegate = self textField.autocorrectionType = UITextAutocorrectionType.yes textField.clearButtonMode = .always return textField }() fileprivate lazy var amountItemTextField: UITextField = { let textField = UITextField() textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) textField.placeholder = "\("amount".localizedCapitalizedFirstLetter) (\("optional".localized))" textField.borderStyle = .roundedRect textField.delegate = self textField.clearButtonMode = .always return textField }() fileprivate lazy var addMoreButton: UIButton = { let button = buttonWith( title: "add_more".localizedCapitalizedFirstLetter, color: UserTheme.shared.primaryColorScheme.color, tag: 0) return button }() fileprivate lazy var addQuitButton: UIButton = { let button = buttonWith( title: "add_and_quit".localizedCapitalizedFirstLetter, color: UserTheme.shared.darkColorScheme.color, tag: 1) return button }() //MARK: Lifecycle init(items: [ShopItemModel]? = nil) { self.currentContent = items super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "\("add".localized) \("shop_item".localized)" let stackView = UIStackView(arrangedSubviews: [shopItemTextField, amountItemTextField, addMoreButton, addQuitButton]) let viewHeight: CGFloat = 40 let spacing: CGFloat = 8 let stackViewSubViewsCount = CGFloat(stackView.subviews.count) let stackViewHeight = (viewHeight*stackViewSubViewsCount) + (spacing * (stackViewSubViewsCount-1)) stackView.alignment = .fill stackView.axis = .vertical stackView.distribution = .fillEqually stackView.spacing = spacing view.addSubview(stackView) stackView.constraintTo( top: view.safeTopAnchor, leading: view.safeLeadingAnchor, trailing: view.safeTrailingAnchor, padding: .init(top: 8, left: 16, bottom: 0, right: 16), size: .init(width: 0, height: stackViewHeight)) tableView = ShoplistTableView(cellClass: ShoplistCell.self) shoplistTableviewDelegateDatasource = ShoplistTableviewDatasourceDelegate() tableView.delegate = shoplistTableviewDelegateDatasource tableView.dataSource = shoplistTableviewDelegateDatasource view.addSubview(tableView) tableView.constraintTo( top: stackView.bottomAnchor, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor, padding: .init(top: 8, left: 0, bottom: 0, right: 0)) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) guard let items = shoplistTableviewDelegateDatasource?.items else { return } if items.isEmpty { return } ShopListHandler.shared.firebaseAdd(items: items) } deinit { debugPrint("AddShopListViewController deinit") } fileprivate func buttonWith(title: String, color: UIColor, tag: Int) -> UIButton { let button = UIButton(type: .system) button.layer.cornerRadius = 10 button.setTitle(title, for: .normal) button.tag = tag button.tintColor = color button.layer.borderColor = color.cgColor button.titleLabel?.textColor = color button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18) button.layer.borderWidth = 2 button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) return button } //MARK: Actions @objc fileprivate func textFieldDidChange(_ sender: UITextField) {} @objc fileprivate func buttonPressed(_ sender: UIButton) { let quit = sender.tag == 1 addItem(quit: quit) } override func closeButtonAction() { shopItemTextField.resignFirstResponder() super.closeButtonAction() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.text = "" addItem(quit: false) return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } fileprivate func addItem(quit: Bool) { guard let item = shopItemTextField.text else { return } if item.isEmpty { return } let newItem = ShopItemModel(title: item, amount: amountItemTextField.text, isDone: false) checkForDuplicate(item: newItem) { [weak self] (add) in if add { self?.items.append(newItem) } if quit { self?.view.endEditing(true) self?.dismiss(animated: true, completion: nil) } } } fileprivate func checkForDuplicate(item: ShopItemModel, completion: @escaping (Bool) -> ()) { let stringToCheck = item.title.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() let itemInAddController = items.first { $0.title.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == stringToCheck } let itemInMainController = currentContent?.first { $0.title.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == stringToCheck } let exists = itemInAddController != nil || itemInMainController != nil if !exists { completion(true) return } let bothAction = UIAlertAction(title: "keep_both".localizedCapitalizedFirstLetter, style: .default) { (_) in completion(true) } let keepNewAction = UIAlertAction(title: "keep_this_delete_old".localizedCapitalizedFirstLetter, style: .default) { [weak self] (_) in self?.removeItem(mainItem: itemInMainController, addItem: itemInAddController) completion(true) } let keepOldAction = UIAlertAction(title: "keep_old_delete_this".localizedCapitalizedFirstLetter, style: .default) { (_) in completion(false) } let actions = [bothAction, keepNewAction, keepOldAction] showAlertSheet( title: "notice".localizedCapitalizedFirstLetter, message: "duplicate_item".localizedCapitalizedFirstLetter, actions: actions) } fileprivate func removeItem(mainItem: ShopItemModel?, addItem: ShopItemModel?) { if let mainItem = mainItem { ShopListHandler.shared.firebaseRemove(item: mainItem) { error in if let error = error { debugPrint(error.localizedDescription) } } } if let addItem = addItem { let newItems = items.drop { $0 === addItem } items.removeAll() items.append(contentsOf: newItems) } } }
// // ProductSerialization.swift // Store // // Created by Vladimir on 21/08/2019. // Copyright © 2019 VladimirYakutin. All rights reserved. // import Foundation protocol ProductSerialization { func serialize(_ product: Product) -> ProductEntity? } protocol ProductDeserialization { func deserialize(_ productEntity: ProductEntity) -> Product }
// // Scene.swift // PaperjamRemove // // Created by Sébastien Crettaz on 04.12.17. // Copyright © 2017 Human Tech. All rights reserved. // import SpriteKit import ARKit import Vision class Scene: SKScene { var latestPrediction : String = "…" // variable containing the latest CoreML prediction var objectName:String = "…" // variable containing the value of the current object found by CoreML static var displayName:String = "..." // variable containing the text to display on the screen var oldAnchor : ARAnchor? = nil // variable containing the actual node displayed on the screen. Used to remove it when // the app goes to the next state static var state : Int = 0 // variable containing the actual state of the fixing var timeStart : Double = 0.0 // time when the app begins var time : Double = 0.0 // actual time var initialize : Bool = true // variable containing if the app is in init state //let debugLabel = SKLabelNode(text: "State") // Label to show informations for debugging override func didMove(to view: SKView) { //debugLabel.position = CGPoint(x:450,y:480) //debugLabel.fontSize = 20 //debugLabel.fontName = "DevanagariSangamMN-Bold" //debugLabel.fontColor = UIColor.green //addChild(debugLabel) // Setup your scene here } override func update(_ currentTime: TimeInterval) { time = currentTime // Get the time where the app started if(initialize){ timeStart = currentTime initialize = false } guard let sceneView = self.view as? ARSKView else { return } var predictionFloat : Double = 0.0 // variable to cast the prediction var if let currentFrame = sceneView.session.currentFrame { DispatchQueue.global(qos: .background).async { do { let model = try VNCoreMLModel(for:MyModel().model) let request = VNCoreMLRequest(model: model, completionHandler: { (request, error) in // Jump onto the main thread DispatchQueue.main.async { var prediction:String = "…" // variable containing the level of prediction // Access the first result in the array after casting the array as a VNClassificationObservation array guard let results = request.results as? [VNClassificationObservation] else { print ("No results?") return } // Get Classifications let classifications = results[0...1] // top 2 results .flatMap({ $0 }) .map({ "\($0.identifier) \(String(format:"- %.2f", $0.confidence))" }) .joined(separator: "\n") // Store the latest prediction prediction = classifications.components(separatedBy: "- ")[1] self.objectName = classifications.components(separatedBy: "-")[0] self.objectName = self.objectName.components(separatedBy: ",")[0] predictionFloat = (prediction as NSString).doubleValue //self.debugLabel.text = String(format:"%d",Scene.state) //self.debugLabel.text = self.debugLabel.text! + self.objectName //self.debugLabel.text = self.debugLabel.text! + String(format:"%f",predictionFloat) //print(result.identifier) } }) let handler = VNImageRequestHandler(cvPixelBuffer: currentFrame.capturedImage, options: [:]) try handler.perform([request]) } catch {} //Add anchor if prediction is bigger than 0.5 if(predictionFloat > 0.75 && self.latestPrediction != self.objectName){ // true if the object is detected in the right state let removeAnchor = self.stateText() // remove the old anchor if self.oldAnchor != nil && removeAnchor{ sceneView.session.remove(anchor: self.oldAnchor!) } // If the object isn't found on the screen, we won't add an anchor if(!removeAnchor){ return } // Create a transform with a translation of 0.4 meters in front of the camera var translation = matrix_identity_float4x4 translation.columns.3.z = -0.4 let transform = simd_mul(currentFrame.camera.transform, translation) // Add a new anchor to the session let anchor = ARAnchor(transform: transform) // Set the identifier self.oldAnchor = anchor sceneView.session.add(anchor: anchor) } } } } // Function stateText // Choose text to display from the states // Return : true if object found and can go to next step func stateText() -> Bool{ // Update last object found self.latestPrediction = self.objectName // Remove space character in the prediction self.latestPrediction = self.latestPrediction.trimmingCharacters(in: .whitespaces) // Change image to help user DispatchQueue.main.async { ViewController.imageView.image = UIImage(named:"ImageViewer/\(Scene.state).JPG") } // Choice of text to display from the states switch Scene.state { case 0 : if(time > timeStart + 2.0){ Scene.state = 1 } return false case 1 : if(self.latestPrediction == "CurveClosed"){ Scene.displayName = "Open it" Scene.state = Scene.state+1 }else if(self.latestPrediction == "CurveOpen"){ Scene.state = Scene.state+1 return false }else{ return false } break case 2 : if(self.latestPrediction == "CurveOpen"){ Scene.displayName = "Go right 👉🏻" Scene.state = Scene.state+1 }else{ return false } break case 3 : if(self.latestPrediction == "ChargerClosed"){ Scene.displayName = "Rise up" Scene.state = Scene.state+1 }else if(self.latestPrediction == "ChargerOpen"){ Scene.state = Scene.state+1 return false }else{ return false } break case 4 : if(self.latestPrediction == "ChargerOpen"){ Scene.displayName = "Open the scanner" Scene.state = Scene.state+1 }else{ return false } break case 5 : if(self.latestPrediction == "ADFOpen"){ Scene.displayName = "Find DF1 (green)" Scene.state = Scene.state+1 }else{ return false } break case 6 : if(self.latestPrediction == "DF1Closed"){ Scene.displayName = "Pull DF1" Scene.state = Scene.state+1 }else{ return false } break case 7 : if(self.latestPrediction == "DF1Open"){ Scene.displayName = "Close DF1 (Show DF1 button)" Scene.state = Scene.state+1 }else{ return false } break case 8 : if(self.latestPrediction == "DF1Closed"){ Scene.displayName = "Close Scanner" Scene.state = Scene.state+1 }else{ return false } break case 9 : if(self.latestPrediction == "ChargerOpen"){ Scene.displayName = "Close charger" Scene.state = Scene.state+1 }else if(self.latestPrediction == "ChargerClosed"){ Scene.state = Scene.state+1 return false }else{ return false } break case 10 : if(self.latestPrediction == "ChargerClosed"){ Scene.displayName = "👈🏻 Go left" Scene.state = Scene.state+1 }else{ return false } break case 11 : if(self.latestPrediction == "CurveOpen"){ Scene.displayName = "Close curve" Scene.state = Scene.state+1 }else if(self.latestPrediction == "CurveClosed"){ Scene.state = Scene.state+1 return false }else{ return false } break case 12 : if(self.latestPrediction == "CurveClosed"){ Scene.displayName = "END FIXING PRINTER !" Scene.state = Scene.state+1 }else{ return false } break case 13 : return false default: Scene.state = 0; return false } return true } // Function touchesBegan // Used if the user want to restart the debugging of the printer when the debugging is done override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if(Scene.state == 13){ Scene.state = 0 } } }
// // NewsFeed.swift // SOSVietnam // // Created by Ecko Huynh on 24/04/2020. // Copyright © 2020 admin. All rights reserved. // import Foundation struct NewsFeed: Codable { let id: Int let title: String let description: String let image : String let url: String }
// // NetworkError.swift // PruebaCeibaiOS // // Created by Usser on 25/09/21. // import Foundation enum NetworkError: String, Error { case parsingData = "Error al parsear json." case genericError = "Error en lectura de datos" }
// // ResultsViewController.swift // UNSW // // Created by Florian Fahrenholz on 22.09.18. // Copyright © 2018 Florian Fahrenholz. All rights reserved. // import UIKit var myIndex = 0 class ResultsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var NamesOfCourses:[String] = ["Algorithms&Prog_Tech","Software_Eng_Fundamentals","Comp_Sys_Fundamentals","Computing_1A","Foundations_of_Concurrency","Software_Construction","Web_Spreadsheets&Databases","Soft_Sys","Prog_For_Designers","System_Modelling&Design","Prog_Lang&Compil","Microprocessors&Interfacing","Prog_Fundamental","O-O_Design","DSA"] //var RatingsShowed:[String] = ["Great", "Boring", "Me neither"] @IBOutlet weak var NameOfCourse: UITableView! @IBOutlet weak var RatingOfCourse: UITableView! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return NamesOfCourses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "SearchCell") var cellLabel = "" if let tempLabel = NamesOfCourses[indexPath.row] as? String{ cellLabel = tempLabel } cell.textLabel?.text = cellLabel return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { myIndex = indexPath.row // performSegue(withIdentifier: "goToRatings", sender: self) performSegue(withIdentifier: "goToRatings2", sender: self) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // ShareHomeViewController.swift // Grubbie // // Created by JABE on 12/10/15. // Copyright © 2015 JABELabs. All rights reserved. // class SharedToYouDataSource : NSObject, UITableViewDataSource { var shareNotifications : [ShareNotification] var shareNotifViewModels = [String : ShareNotificationViewModel]() var sharedHomeViewController : ShareHomeViewController! var dateFormatter : NSDateFormatter! var audioPlayer : JLAudioPlayer! init(shareNotifications: [ShareNotification], shareHomeVc: ShareHomeViewController){ self.shareNotifications = shareNotifications self.dateFormatter = shareHomeVc.dateFormatter self.audioPlayer = shareHomeVc.audioPlayer self.sharedHomeViewController = shareHomeVc } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.shareNotifications.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let shareNotif = self.shareNotifications[indexPath.row] let shareNotifViewModel = self.shareNotifViewModels[shareNotif.id] let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! SharedToYouTableViewCell cell.configure(indexPath, shareNotif: shareNotif, shareNotifViewModel: shareNotifViewModel, dateFormatter: self.dateFormatter, audioPlayer: self.audioPlayer, delegate: self.sharedHomeViewController) { (shareNotif, shareNotifViewModel) -> Void in self.shareNotifViewModels[shareNotif.id] = shareNotifViewModel } return cell } } extension ShareHomeViewController : SharedToYouTableViewCellDelegate { func didPressMoreDetailsButton(indexPath: NSIndexPath) { let shareNotif = self.sharedToYouDataSource.shareNotifications[indexPath.row] let shareNotifViewModel = self.sharedToYouDataSource.shareNotifViewModels[shareNotif.id] UIFactory.showStoryboard(self, storyboardId: StoryboardId.ShareAcceptRejectViewController) { (uiViewController) -> Void in if let view = uiViewController as? ShareAcceptRejectViewController { view.shareNotification = shareNotif view.shareNotificationViewModel = shareNotifViewModel } } } } extension ShareHomeViewController : UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sharedByYouSummaries.count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let shareSummary = sharedByYouSummaries[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("cell")! cell.textLabel?.text = "\(self.dateFormatter.stringFromDate(shareSummary.startProcessDate!))" let photoText = shareSummary.photoCount > 1 ? "s" : "" let personText = shareSummary.recipientCount > 1 ? "s" : "" cell.detailTextLabel?.text = "You shared \(shareSummary.photoCount) photo\(photoText) to \(shareSummary.recipientCount) person\(personText)" return cell } } extension ShareHomeViewController : AppEventSubscriber { func onEvent(eventType: AppEventType, eventTimeStamp: NSDate, userData: AnyObject?) { switch eventType { case .ShareSummaryAdded, .ShareNotificationAccepted, .ShareNotificationRejected, .ShareNotificationNotFound: self.onSharedToByChanged() break; default: // Ignore. break; } } } class ShareHomeViewController: UIViewController { @IBOutlet var sharedToBy: UISegmentedControl! @IBOutlet var sharedToYouContainer: UIView! @IBOutlet var sharedByYouContainer: UIView! @IBOutlet var sharedByYouTableView: UITableView! @IBOutlet var youHaveNotSharedAnyLabel: UILabel! @IBOutlet var youHaveNoItemsSharedToYouLabel: UILabel! @IBOutlet var sharedToYouTableView: UITableView! var sharedByYouSummaries = [ShareSummary]() var activityIndicator : JLActivityIndicator! var sharedToYouDataSource : SharedToYouDataSource! var audioPlayer = JLAudioPlayer() var dateFormatter = Factory.createDateFormatterWithTime() override func viewDidLoad() { EventPublisher.sharedAppEventPublisher().addSubscriber(self, eventTypes: .ShareSummaryAdded, .ShareNotificationAccepted, .ShareNotificationRejected, .ShareNotificationNotFound) activityIndicator = JLActivityIndicator(parentView: self.view, onTopOfView: self.view, startAnimating: false) sharedToBy.selectedSegmentIndex = 0 sharedByYouTableView.dataSource = self sharedByYouTableView.hidden = true youHaveNotSharedAnyLabel.hidden = true self.sharedToYouTableView.hidden = true self.youHaveNoItemsSharedToYouLabel.hidden = true onSharedToByChanged() } func onSharedToByChanged(){ sharedToYouContainer.hidden = sharedToBy.selectedSegmentIndex != 0 sharedByYouContainer.hidden = sharedToBy.selectedSegmentIndex != 1 if sharedByYouContainer.hidden == false { activityIndicator.startAnimation() ShareSummary.getShareSummariesOfUser(Util.getCurrentUserId()) { (shareSummaries, error) -> Void in if let summaries = shareSummaries { self.sharedByYouSummaries = summaries self.sharedByYouTableView.hidden = summaries.count == 0 } else { self.sharedByYouTableView.hidden = true } self.youHaveNotSharedAnyLabel.hidden = !self.sharedByYouTableView.hidden self.sharedByYouTableView.reloadData() self.activityIndicator.stopAnimation() self.sharedToBy.setTitle("Shared by you (\(self.sharedByYouSummaries.count))", forSegmentAtIndex: 1) } } else if sharedToYouContainer.hidden == false { activityIndicator.startAnimation() ShareNotification.getShareNotificationsForUser(Util.getCurrentUserId()) { (notifications, error) -> Void in self.sharedToYouTableView.hidden = notifications.count == 0 self.youHaveNoItemsSharedToYouLabel.hidden = !self.sharedToYouTableView.hidden self.sharedToYouDataSource = SharedToYouDataSource(shareNotifications: notifications, shareHomeVc: self) self.sharedToYouTableView.dataSource = self.sharedToYouDataSource self.sharedToYouTableView.reloadData() self.sharedToBy.setTitle("Shared to you (\(notifications.count))", forSegmentAtIndex: 0) self.activityIndicator.stopAnimation() } } } @IBAction func sharedToByValueChanged(sender: AnyObject) { onSharedToByChanged() } }
import Foundation import MetalKit import simd struct VertexUniforms { var viewProjectionMatrix: float4x4 var modelMatrix: float4x4 var normalMatrix: float3x3 } struct FragmentUniforms { var cameraWorldPosition = float3(0, 0, 0) var ambientLightColor = float3(0, 0, 0) var specularColor = float3(1, 1, 1) var specularPower = Float(1) var light0 = Light() var light1 = Light() var light2 = Light() } class Renderer: NSObject, MTKViewDelegate { let device: MTLDevice let commandQueue: MTLCommandQueue var renderPipeline: MTLRenderPipelineState let depthStencilState: MTLDepthStencilState let samplerState: MTLSamplerState let vertexDescriptor: MDLVertexDescriptor let scene: Scene var time: Float = 0 var cameraWorldPosition = float3(0, 0, 2) var viewMatrix = matrix_identity_float4x4 var projectionMatrix = matrix_identity_float4x4 static let fishCount = 12 init(view: MTKView, device: MTLDevice) { self.device = device commandQueue = device.makeCommandQueue()! vertexDescriptor = Renderer.buildVertexDescriptor() renderPipeline = Renderer.makeRenderPipelineState(device: device, view: view, vertexDescriptor: vertexDescriptor) samplerState = Renderer.buildSamplerState(device: device) depthStencilState = Renderer.buildDepthStencilState(device: device) scene = Renderer.buildScene(device: device, vertexDescriptor: vertexDescriptor) super.init() } static func buildScene(device: MTLDevice, vertexDescriptor: MDLVertexDescriptor) -> Scene { let bufferAllocator = MTKMeshBufferAllocator(device: device) let textureLoader = MTKTextureLoader(device: device) let options: [MTKTextureLoader.Option : Any] = [.generateMipmaps : true, .SRGB : true] let scene = Scene() scene.ambientLightColor = float3(0.1, 0.1, 0.1) let light0 = Light(worldPosition: float3( 5, 5, 0), color: float3(0.3, 0.3, 0.3)) let light1 = Light(worldPosition: float3(-5, 5, 0), color: float3(0.3, 0.3, 0.3)) let light2 = Light(worldPosition: float3( 0, -5, 0), color: float3(0.3, 0.3, 0.3)) scene.lights = [ light0, light1, light2 ] let bob = Node(name: "Bob") let bobMaterial = Material() let bobBaseColorTexture = try? textureLoader.newTexture(name: "bob_baseColor", scaleFactor: 1.0, bundle: nil, options: options) bobMaterial.baseColorTexture = bobBaseColorTexture bobMaterial.specularPower = 100 bobMaterial.specularColor = float3(0.8, 0.8, 0.8) bob.material = bobMaterial let bobURL = Bundle.main.url(forResource: "bob", withExtension: "obj")! let bobAsset = MDLAsset(url: bobURL, vertexDescriptor: vertexDescriptor, bufferAllocator: bufferAllocator) bob.mesh = try! MTKMesh.newMeshes(asset: bobAsset, device: device).metalKitMeshes.first! scene.rootNode.children.append(bob) let blubMaterial = Material() let blubBaseColorTexture = try? textureLoader.newTexture(name: "blub_baseColor", scaleFactor: 1.0, bundle: nil, options: options) blubMaterial.baseColorTexture = blubBaseColorTexture blubMaterial.specularPower = 40 blubMaterial.specularColor = float3(0.8, 0.8, 0.8) let blubURL = Bundle.main.url(forResource: "blub", withExtension: "obj")! let blubAsset = MDLAsset(url: blubURL, vertexDescriptor: vertexDescriptor, bufferAllocator: bufferAllocator) let blubMesh = try! MTKMesh.newMeshes(asset: blubAsset, device: device).metalKitMeshes.first! for i in 1...fishCount { let blub = Node(name: "Blub \(i)") blub.material = blubMaterial blub.mesh = blubMesh bob.children.append(blub) } return scene } static func buildVertexDescriptor() -> MDLVertexDescriptor { let vertexDescriptor = MDLVertexDescriptor() vertexDescriptor.attributes[0] = MDLVertexAttribute(name: MDLVertexAttributePosition, format: .float3, offset: 0, bufferIndex: 0) vertexDescriptor.attributes[1] = MDLVertexAttribute(name: MDLVertexAttributeNormal, format: .float3, offset: MemoryLayout<Float>.size * 3, bufferIndex: 0) vertexDescriptor.attributes[2] = MDLVertexAttribute(name: MDLVertexAttributeTextureCoordinate, format: .float2, offset: MemoryLayout<Float>.size * 6, bufferIndex: 0) vertexDescriptor.layouts[0] = MDLVertexBufferLayout(stride: MemoryLayout<Float>.size * 8) return vertexDescriptor } static func buildSamplerState(device: MTLDevice) -> MTLSamplerState { let samplerDescriptor = MTLSamplerDescriptor() samplerDescriptor.normalizedCoordinates = true samplerDescriptor.minFilter = .linear samplerDescriptor.magFilter = .linear samplerDescriptor.mipFilter = .linear return device.makeSamplerState(descriptor: samplerDescriptor)! } static func buildDepthStencilState(device: MTLDevice) -> MTLDepthStencilState { let depthStencilDescriptor = MTLDepthStencilDescriptor() depthStencilDescriptor.depthCompareFunction = .less depthStencilDescriptor.isDepthWriteEnabled = true return device.makeDepthStencilState(descriptor: depthStencilDescriptor)! } /// Make the RenderPipelineState based on DefaultLibrary, shader programs, RenderPipelineDescriptor and MetalVertexDescriptorFromModelIO /// /// - Parameters: /// - device: MTLDevice /// - view: MTKView /// - vertexDescriptor: vertexDescriptor /// - Returns: MTLRenderPipelineState static func makeRenderPipelineState(device: MTLDevice, view: MTKView, vertexDescriptor: MDLVertexDescriptor) -> MTLRenderPipelineState { guard let library = device.makeDefaultLibrary() else { fatalError("Could not load default library from main bundle") } let vertexFunction = library.makeFunction(name: "vertex_main") let fragmentFunction = library.makeFunction(name: "fragment_main") let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.vertexFunction = vertexFunction pipelineDescriptor.fragmentFunction = fragmentFunction pipelineDescriptor.colorAttachments[0].pixelFormat = view.colorPixelFormat pipelineDescriptor.depthAttachmentPixelFormat = view.depthStencilPixelFormat let mtlVertexDescriptor = MTKMetalVertexDescriptorFromModelIO(vertexDescriptor) pipelineDescriptor.vertexDescriptor = mtlVertexDescriptor do { return try device.makeRenderPipelineState(descriptor: pipelineDescriptor) } catch { fatalError("Could not create render pipeline state object: \(error)") } } func update(_ view: MTKView) { time += 1 / Float(view.preferredFramesPerSecond) cameraWorldPosition = float3(0, 0, 2) viewMatrix = float4x4(translationBy: -cameraWorldPosition) * float4x4(rotationAbout: float3(1, 0, 0), by: .pi / 6) let aspectRatio = Float(view.drawableSize.width / view.drawableSize.height) projectionMatrix = float4x4(perspectiveProjectionFov: Float.pi / 6, aspectRatio: aspectRatio, nearZ: 0.1, farZ: 100) let angle = -time scene.rootNode.modelMatrix = float4x4(rotationAbout: float3(0, 1, 0), by: angle) if let bob = scene.nodeNamed("Bob") { bob.modelMatrix = float4x4(translationBy: float3(0, 0.015 * sin(time * 5), 0)) } let blubBaseTransform = float4x4(rotationAbout: float3(0, 0, 1), by: -.pi / 2) * float4x4(scaleBy: 0.25) * float4x4(rotationAbout: float3(0, 1, 0), by: -.pi / 2) let fishCount = Renderer.fishCount for i in 1...fishCount { if let blub = scene.nodeNamed("Blub \(i)") { let pivotPosition = float3(0.4, 0, 0) let rotationOffset = float3(0.4, 0, 0) let rotationSpeed = Float(0.3) let rotationAngle = 2 * Float.pi * Float(rotationSpeed * time) + (2 * Float.pi / Float(fishCount) * Float(i - 1)) let horizontalAngle = 2 * .pi / Float(fishCount) * Float(i - 1) blub.modelMatrix = float4x4(rotationAbout: float3(0, 1, 0), by: horizontalAngle) * float4x4(translationBy: rotationOffset) * float4x4(rotationAbout: float3(0, 0, 1), by: rotationAngle) * float4x4(translationBy: pivotPosition) * blubBaseTransform } } } func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { } func draw(in view: MTKView) { // printClassAndFunc() update(view) let commandBuffer = commandQueue.makeCommandBuffer()! if let renderPassDescriptor = view.currentRenderPassDescriptor, let drawable = view.currentDrawable { renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.63, 0.81, 1.0, 1.0) let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)! commandEncoder.setFrontFacing(.counterClockwise) commandEncoder.setCullMode(.back) commandEncoder.setDepthStencilState(depthStencilState) commandEncoder.setRenderPipelineState(renderPipeline) commandEncoder.setFragmentSamplerState(samplerState, index: 0) drawNodeRecursive(scene.rootNode, parentTransform: matrix_identity_float4x4, commandEncoder: commandEncoder) commandEncoder.endEncoding() commandBuffer.present(drawable) commandBuffer.commit() } } func drawNodeRecursive(_ node: Node, parentTransform: float4x4, commandEncoder: MTLRenderCommandEncoder) { let modelMatrix = parentTransform * node.modelMatrix if let mesh = node.mesh, let baseColorTexture = node.material.baseColorTexture { let viewProjectionMatrix = projectionMatrix * viewMatrix var vertexUniforms = VertexUniforms(viewProjectionMatrix: viewProjectionMatrix, modelMatrix: modelMatrix, normalMatrix: modelMatrix.normalMatrix) commandEncoder.setVertexBytes(&vertexUniforms, length: MemoryLayout<VertexUniforms>.size, index: 1) var fragmentUniforms = FragmentUniforms(cameraWorldPosition: cameraWorldPosition, ambientLightColor: scene.ambientLightColor, specularColor: node.material.specularColor, specularPower: node.material.specularPower, light0: scene.lights[0], light1: scene.lights[1], light2: scene.lights[2]) commandEncoder.setFragmentBytes(&fragmentUniforms, length: MemoryLayout<FragmentUniforms>.size, index: 0) commandEncoder.setFragmentTexture(baseColorTexture, index: 0) let vertexBuffer = mesh.vertexBuffers.first! commandEncoder.setVertexBuffer(vertexBuffer.buffer, offset: vertexBuffer.offset, index: 0) for submesh in mesh.submeshes { let indexBuffer = submesh.indexBuffer commandEncoder.drawIndexedPrimitives(type: submesh.primitiveType, indexCount: submesh.indexCount, indexType: submesh.indexType, indexBuffer: indexBuffer.buffer, indexBufferOffset: indexBuffer.offset) } } for child in node.children { drawNodeRecursive(child, parentTransform: modelMatrix, commandEncoder: commandEncoder) } } }
/* Copyright Airship and Contributors */ import Foundation #if canImport(AirshipCore) import AirshipCore #endif /** * Resources for AirshipChat. */ @available(iOS 13.0, *) @objc(UAChatResources) public class ChatResources : NSObject { /** * Resource bundle for AirshipChat. * @return The chat bundle. */ @objc public static func bundle() -> Bundle? { let mainBundle = Bundle.main let sourceBundle = Bundle(for: Self.self) let path = mainBundle.path(forResource: "Airship_AirshipChat", ofType: "bundle") ?? mainBundle.path(forResource: "AirshipChatResources", ofType: "bundle") ?? sourceBundle.path(forResource: "AirshipChatResources", ofType: "bundle") ?? "" return Bundle(path: path) ?? sourceBundle } public static func localizedString(key: String) -> String? { return LocalizationUtils.localizedString(key, withTable:"UrbanAirship", moduleBundle:bundle()) } }
// // constants.swift // Departure Board // // Created by Cat Jia on 16/11/2018. // Copyright © 2018 Cat Jia. All rights reserved. // import UIKit struct AppConstant { private init() {} static let maxDisplayCount: Int = 3 }
// // NotificacionesViewController.swift // INSSAFI // // Created by Novacomp on 8/3/18. // Copyright © 2018 Novacomp. All rights reserved. // import UIKit class NotificacionesViewController: UIViewController { @IBOutlet weak var swNotifications: UISwitch! override func viewDidLoad() { super.viewDidLoad() swNotifications.setOn(OneSignal.getPermissionSubscriptionState().subscriptionStatus.subscribed, animated: true) } @IBAction func swNotifications(_ sender: UISwitch) { OneSignal.setSubscription(sender.isOn) } }
import UIKit import GoogleMobileAds class LogInViewController: UIViewController, UITextFieldDelegate, GADBannerViewDelegate { //Mark: Properties @IBOutlet weak var sendPassword: UIButton! @IBOutlet weak var forgetPasswordUserName: UITextField! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var forgetPasswordButton: UIButton! @IBOutlet weak var userNameTxtField: UITextField! @IBOutlet weak var passwordTxtField: UITextField! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var popUpForgetPasswordView: UIView! @IBOutlet weak var backgroundView: UIImageView! @IBOutlet weak var scrollViewOutlet: UIScrollView! var URLforSignIn = "http://192.168.1.222/mobil_app/user_login_api.php" var params = "" var valueOfUserNameTextfield = "" var valueOfPasswordTextfield = "" var valueOfforgetPasswordUserName = "" override func viewDidLoad() { super.viewDidLoad() userNameTxtField.delegate = self passwordTxtField.delegate = self forgetPasswordUserName.delegate = self //for border signUpButton.layer.borderColor = UIColor.white.cgColor signUpButton.layer.borderWidth = 1.0 forgetPasswordButton.layer.borderColor = UIColor.white.cgColor forgetPasswordButton.layer.borderWidth = 1.0 //for tap gesture let tap = UITapGestureRecognizer(target: self, action:#selector(DismissForgetPasswordView(sender:)) ) tap.delegate = self as? UIGestureRecognizerDelegate backgroundView.addGestureRecognizer(tap) } //delegate for textfields func textFieldDidEndEditing(_ textField: UITextField) { valueOfUserNameTextfield = userNameTxtField.text! valueOfPasswordTextfield = passwordTxtField.text! valueOfforgetPasswordUserName = forgetPasswordUserName.text! scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidBeginEditing(_ textField: UITextField) { if textField == forgetPasswordUserName { scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true) }else{ scrollView.setContentOffset(CGPoint(x: 0, y: 250), animated: true) } } //mark: Action @IBAction func forgetPasswordButton(_ sender: Any) { popUpForgetPasswordView.isHidden = false } func DismissForgetPasswordView(sender: UITapGestureRecognizer){ popUpForgetPasswordView.isHidden = true } @IBAction func signinbuttonTapped(_ sender: Any) { UserDefaults.standard.set(userNameTxtField.text, forKey: "userName") UserDefaults.standard.set(passwordTxtField.text, forKey: "password") valueOfUserNameTextfield = userNameTxtField.text! valueOfPasswordTextfield = passwordTxtField.text! self.params = "username=\(valueOfUserNameTextfield)&password=\(valueOfPasswordTextfield)" print(URLforSignIn) let jsonCall = APlCall() jsonCall.getDataFromJson(url: URLforSignIn, parameter: params, completion: { response in print(response) let status = response["success"] as! String if status == "true" { print("log in successful") } else { print("sorry") } }) } @IBAction func ContinueGuestButton(_ sender: Any) { UserDefaults.standard.set(userNameTxtField.text, forKey: "userName") UserDefaults.standard.set(passwordTxtField.text, forKey: "password") print("guest btn action") } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SignInSegue" { if let destinationVC = segue.destination as? DashboardViewController { destinationVC.userNameString = self.valueOfUserNameTextfield self.present(destinationVC, animated: true, completion: nil) } } if segue.identifier == "ContinueAsGuest" { if let dashVC = segue.destination as? DashboardViewController { self.present(dashVC, animated: true, completion: nil) print("guest prepare") } } } // storing session data override func viewDidAppear(_ animated: Bool) { if let name = UserDefaults.standard.object(forKey: "userName") as? String { userNameTxtField.text = name } if let password1 = UserDefaults.standard.object(forKey: "password") as? String { passwordTxtField.text = password1 } } }
enum A { case a, b, c } var cc = A.a switch cc { case .a: print("haha") case .b: print("hehe") default: print("hoho") }
// // SDKTestRouter.swift // HotBoxKit // // Created by Mark Evans on 6/21/19. // Copyright © 2019 3Advance LLC. All rights reserved. // import Foundation import UIKit public class SDKTestRouter: SDKTestWireframe { public var viewController: UIViewController? public static func assembleModule(userId: String?) -> SDKTestViewController { let view = SDKTestViewController() view.userId = userId let presenter = SDKTestPresenter() let interactor = SDKTestInteractor() let router = SDKTestRouter() view.presenter = presenter presenter.view = view presenter.interactor = interactor presenter.router = router interactor.output = presenter router.viewController = view return view } }
// // GradientMaker.swift // Continuous // // Created by Chloe on 2016-02-24. // Copyright © 2016 Chloe Horgan. All rights reserved. // import UIKit struct GradientMaker { static func gradientBackground(view: UIView) { let topColor = UIColor(red: 73.0/255.0, green: 10.0/255.0, blue: 61.0/255.0, alpha: 1.0) let bottomColor = UIColor(red: 189.0/255.0, green: 21.0/255.0, blue: 80.0/255.0, alpha: 1.0) let viewGradient = CAGradientLayer() viewGradient.colors = [topColor.CGColor, bottomColor.CGColor] viewGradient.frame = view.bounds view.layer.insertSublayer(viewGradient, atIndex: 0) } static func gradientYellow(view: UIView) { let topColor = UIColor(red: 233.0/255.0, green: 127.0/255.0, blue: 2.0/255.0, alpha: 1.0) let bottomColor = UIColor(red: 248.0/255.0, green: 202.0/255.0, blue: 0.0/255.0, alpha: 1.0) let viewGradient = CAGradientLayer() viewGradient.colors = [topColor.CGColor, bottomColor.CGColor] viewGradient.frame = view.bounds view.layer.insertSublayer(viewGradient, atIndex: 0) } }
// // AppDelegate.swift // UnitTestWithPodAPP // // Created by SergeyBrazhnik on 19.11.2020. // import UIKit import UnitTestWithPodSpm @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. application.registerForRemoteNotifications() HelloLib.shared.helloWorld() print("\(HelloLib.shared.md5())") // configure SIC firebase //HelloLib.shared.configure(application: application) return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } // MARK: Push notifications // notification received func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { print("didReceiveRemoteNotification") switch UIApplication.shared.applicationState { case .active, .inactive: print("Active state") case .background: print("Background state") default: print("the default state") break } completionHandler(.newData) } }
// // ViewController.swift // EUpdates // // Created by Artsiom Dolia on 11/17/14. // Copyright (c) 2014 Artsiom Dolia. All rights reserved. // import UIKit class ViewController: UIViewController { //properties for the ui elements from storyboard @IBOutlet weak var userNameField: UITextField! @IBOutlet weak var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() } //MARK: buttons actions @IBAction func resetButtonAction(sender: UIButton) { self.clearFields() } @IBAction func loginButtonAction(sender: UIButton) { //hardcoded strings to recognize parent or teacher if self.userNameField.text == "parent" { self.performSegueWithIdentifier("loginToTabParent", sender: self) }else if self.userNameField.text == "teacher" { self.performSegueWithIdentifier("loginToTabTeacher", sender: self) } self.clearFields() } func clearFields(){ self.userNameField.text = "" self.passwordField.text = "" } }
// // MyFeedsViewController.swift // bikes_search // // Created by Przemysław Kalawski on 11/12/2019. // Copyright © 2019 Przemysław Kalawski. All rights reserved. // import UIKit import CoreLocation class MyFeedsViewController: UITableViewController { static let path: String = Source.URL.path private var locations: [Location] = [] private let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() fetchData() setTableViewConfig() } private func fetchData() { DataService.fetchData(from: URL(string: MyFeedsViewController.path)!, type: Items.self) {[weak self] (items) in guard let self = self else { return } self.locations = items.locations for index in 0..<self.locations.count { let center = CLLocation(latitude: self.locations[index].geometry.coordinates[1], longitude: self.locations[index].geometry.coordinates[0]) let geoCoder = CLGeocoder() geoCoder.reverseGeocodeLocation(center) { [weak self] (placemarks, error) in guard let self = self else { return } guard let placemark = placemarks?.first else { return } let streetName: String = placemark.thoroughfare ?? "" let city: String = placemark.subLocality ?? "" self.locations[index].address = "\(streetName), \(city)" } } self.locationManager.delegate = self self.checkLocationServices() } } private func setTableViewConfig() { self.tableView.rowHeight = UITableView.automaticDimension self.tableView.estimatedRowHeight = 300 } public func checkLocationServices() { if CLLocationManager.locationServicesEnabled() { setupLocationManager() checkLocationAuthorization() } else { // Show an alert } } private func setupLocationManager() { locationManager.desiredAccuracy = kCLLocationAccuracyBest } public func checkLocationAuthorization() { switch CLLocationManager.authorizationStatus() { case .authorizedWhenInUse: locationManager.startUpdatingLocation() case .notDetermined: locationManager.requestWhenInUseAuthorization() case .restricted: // Show an alert letting them know break case .denied: // Show alert instructing them how to turn on permissions break case .authorizedAlways: break @unknown default: break } } } extension MyFeedsViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: FeedCell.className, for: indexPath) as? FeedCell else { return UITableViewCell() } cell.location = locations[indexPath.row] return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return locations.count } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: DetailsViewController.className) as? DetailsViewController else { return } vc.location = self.locations[indexPath.row] self.present(vc, animated: true, completion: nil) } } extension MyFeedsViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let clLocation = locations.last else { return } for index in 0..<self.locations.count { self.locations[index].distance = clLocation.distance(from: CLLocation(latitude: self.locations[index].geometry.coordinates[1], longitude: self.locations[index].geometry.coordinates[0])) } self.locations.sort { (location1, location2) -> Bool in location1.distance ?? 0 < location2.distance ?? 0 } updateUI { [weak self] in self?.tableView.reloadData() } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { self.checkLocationAuthorization() } }
// // Approach.swift // Intimacy-Semantics // // Created by Zhou Wei Ran on 2020/9/30. // Copyright © 2020 Paper Scratch. All rights reserved. // import Elo_Itself extension Coding_Principle { enum Intimacy { case Feeling_Oriented_HumanInteraction } } struct Involve_in_Social_Situation: Task, Has_AfterTasks, Can_Manifest { var canManifest: To_Manifest = Behavior_and_Cognitive_Pattern() var afterTasks: [Task] = { var tmp = [Task]() tmp.append(Replay()) tmp.append(Brain_Simulation()) tmp.append(Semantic_Discrimination()) return tmp }() } struct Behavior_and_Cognitive_Pattern: To_Manifest {} protocol To_Manifest {} protocol Can_Manifest { var canManifest: To_Manifest { get } } struct Replay: Task {} struct Brain_Simulation: Task {} extension Semantic_Discrimination: Task {}
import Foundation struct Formatters { let dateFormatter = DateFormatter() let currencyFormatter = NumberFormatter() let numberFormatter = NumberFormatter() init() { dateFormatter.dateStyle = DateFormatter.Style.long currencyFormatter.numberStyle = .currency numberFormatter.numberStyle = .decimal } } let formatters = Formatters()
// // QuestManager.swift // Carousel // // Created by Andrey on 12.05.17. // Copyright © 2017 Quest. All rights reserved. // import Foundation import SwiftyJSON import MagicalRecord class QuestManager : BaseManager { static let sharedInstance = QuestManager() private override init() { super.init() } func updateQuestListWithСityAndLanguage(city: String, language: String, completion: @escaping QuestsResponseWithErrorBlock) { APIQuest.sharedInstance.questListWithCityAndLanguage(uid: city, language: language) { (json, error) in if error != nil { completion([], error) return } guard let jsonQuest = json else { completion([], AppError.errorWithCode(code: .AppErrorEmptyJSON)) return } self.saveQuestFromJson(jsonQuest: jsonQuest, completion: completion) } } func saveQuestFromJson(jsonQuest: JSON, completion: @escaping QuestsResponseWithErrorBlock) { CoreDataSaver.sharedInstance.saveData(savingBlock: { (localContext, cancelSaving) in let jsonObjects: [JSON] do { let entityFinderAndCreator = EntityFinderAndCreator(localContext!) // let city = entityFinderAndCreator.findOrCreateEntityOfType(type: BDCity.self, withId: "") jsonObjects = jsonQuest.arrayValue for jsonObject in jsonObjects { if let object = try? QuestConverter.jsonToQuests(json: jsonObject, entityFinderAndCreator: entityFinderAndCreator) { // city.addToQuests(object) } } } catch { DispatchQueue.main.async(execute: { completion([], AppError.errorWithCode(code: .AppErrorInvalidJSON)) }) } }) { DispatchQueue.main.async(execute: { let questArray = self.getQuestArray() if questArray.count > 0 { completion(questArray, nil) } else { completion([], AppError.errorWithCode(code: .AppErrorCoreDataFetch)) } }) } } func getQuestArray() -> [BDQuests] { let entityFinderAndCreator = EntityFinderAndCreator(self.defaultContext) if let questsArray = entityFinderAndCreator.findAllEntityOfType(type: BDQuests.self) { return questsArray } return [] } func getCityQuestArray(uid: ObjectIdType) -> [BDQuests]? { let entityFinderAndCreator = EntityFinderAndCreator(self.defaultContext) if let cityArray = entityFinderAndCreator.findEntityOfType(type: BDCity.self, withId: uid) { if let quests = cityArray.quests { return quests.array as? [BDQuests] } else { return [] } } return [] } func questWithId(uid: ObjectIdType) -> BDQuests? { let entityFinderAndCreator = EntityFinderAndCreator(self.defaultContext) if let quest = entityFinderAndCreator.findEntityOfType(type: BDQuests.self, withId: uid) { return quest } else { return nil } } }
// // Extensión.swift // OtherSpriteKitGame // // Created by Juan Morillo on 10/12/17. // Copyright © 2017 Juan Morillo. All rights reserved. // import UIKit enum UIUserInterfaceIdiom: Int { case undefined case phone case pad } struct ScreenSize { static let width = UIScreen.main.bounds.size.width static let heigth = UIScreen.main.bounds.size.height static let maxHeigth = max(ScreenSize.width, ScreenSize.heigth) static let minHeigth = min(ScreenSize.width, ScreenSize.heigth) } struct DeviceType { static let isiPhone4OrLess = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxHeigth < 568.0 static let isIphone5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxHeigth >= 568.0 static let isiPhone6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxHeigth == 667.0 static let isiPhone6Plus = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxHeigth == 736.0 static let isiPhoneX = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxHeigth == 812.0 static let isiPad = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.maxHeigth == 1024.0 static let isiPadPro = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.maxHeigth == 1366.0 }
// // UIImageView+extension.swift // WorldDevEvent // // Created by Bogdan Sasko on 5/29/19. // Copyright © 2019 vinso. All rights reserved. // import UIKit extension UIImageView { func load(withURL url: String?) { guard let url = url, let imageURL = URL(string: url) else { self.image = nil return } let task = URLSession.shared.dataTask(with: imageURL, completionHandler: { data, response, error in guard let imgData = data else { return } let loadedImage = UIImage(data: imgData) DispatchQueue.main.async { self.image = loadedImage } }) task.resume() } }
// // ExploreInfoViewController.swift // Travel Companion // // Created by Stefan Jaindl on 09.07.19. // Copyright © 2019 Stefan Jaindl. All rights reserved. // import UIKit import shared import WebKit class ExploreInfoViewController: UIViewController, WKUIDelegate { @IBOutlet weak var wikipediaButton: UIButton! @IBOutlet weak var wikivoyageButton: UIButton! @IBOutlet weak var googleButton: UIButton! @IBOutlet weak var lonelyplanetButton: UIButton! @IBOutlet weak var infoStack: UIStackView! var webView: WKWebView! var pin: Pin! var placeName: String = "" override public func viewDidLoad() { super.viewDidLoad() guard let name = pin.name else { UiUtils.showError("noPage".localized(), controller: self) return } placeName = name self.tabBarController?.navigationItem.title = name openWikipedia(self) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationController?.hidesBarsOnSwipe = true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.hidesBarsOnSwipe = false navigationController?.isNavigationBarHidden = false } override func loadView() { super.loadView() let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = self webView.navigationDelegate = self webView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(webView) if #available(iOS 11, *) { let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ webView.leadingAnchor.constraint(equalTo: guide.leadingAnchor), webView.trailingAnchor.constraint(equalTo: guide.trailingAnchor), webView.topAnchor.constraint(equalTo: guide.topAnchor, constant: 5), webView.bottomAnchor.constraint(equalTo: infoStack.topAnchor) ]) } else { let standardSpacing: CGFloat = 8.0 let margins = view.layoutMarginsGuide NSLayoutConstraint.activate([ webView.leadingAnchor.constraint(equalTo: margins.leadingAnchor), webView.trailingAnchor.constraint(equalTo: margins.trailingAnchor), webView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing), webView.bottomAnchor.constraint(equalTo: infoStack.topAnchor, constant: standardSpacing), webView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), webView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor) ]) } } @IBAction func openWikipedia(_ sender: Any) { openWikiLink(for: WikiConstants.UrlComponents.domainWikipedia) } @IBAction func openWikiVoyage(_ sender: Any) { openWikiLink(for: WikiConstants.UrlComponents.domainWikiVoyage) } func openWikiLink(for domain: String) { WikiClient.sharedInstance.fetchWikiLink(country: placeName, domain: domain) { (error, wikiLink) in if let error = error { UiUtils.showError(error, controller: self) } else { let url = URL(string: wikiLink!) let request = URLRequest(url:url!) DispatchQueue.main.async { self.webView!.load(request) } } } } @IBAction func openGoogle(_ sender: Any) { let urlComponents = GoogleConstants.UrlComponents() let domain = urlComponents.domainSearch let queryItems: [String: String] = [GoogleConstants.ParameterKeys().searchQuery: placeName] let url = WebClient.sharedInstance.createUrl( forScheme: urlComponents.urlProtocol, forHost: domain, forMethod: urlComponents.pathSearch, withQueryItems: queryItems ) loadUrl(url, queryItems: queryItems) } @IBAction func openLonelyPlanet(_ sender: Any) { let domain = LonelyPlanetConstants.UrlComponents.domain let queryItems: [String: String] = [LonelyPlanetConstants.ParameterKeys.searchQuery: placeName] let url = WebClient.sharedInstance.createUrl(forScheme: LonelyPlanetConstants.UrlComponents.urlProtocol, forHost: domain, forMethod: LonelyPlanetConstants.UrlComponents.pathSearch, withQueryItems: queryItems) loadUrl(url, queryItems: queryItems) } func loadUrl(_ url: URL, queryItems: [String: String]) { let request = URLRequest(url:url) DispatchQueue.main.async { self.webView!.load(request) } } } extension ExploreInfoViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { debugPrint("finish navigation to \(String(describing: webView.url))") } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { UiUtils.showToast(message: error.localizedDescription, view: self.view) } }
// // CodeNativeLayoutViewController.swift // AutoLayoutDemo // // Created by 董知樾 on 2017/3/27. // Copyright © 2017年 董知樾. All rights reserved. // import UIKit class CodeNativeLayoutViewController: UIViewController { var layoutWays : [Dictionary<String, String>]! var tableView = UITableView() let identifier = "CodeNativeLayoutViewController" override func viewDidLoad() { super.viewDidLoad() title = "原生代码布局" view.backgroundColor = .white layoutWays = [ ["title":"常规布局","className":"CNGeneralViewController"], ["title":"动画","className":"CNAnimationViewController"], ["title":"NSLayoutAnchor","className":"CNLayoutAnchorViewController"], ["title":"UILayoutGuide","className":"CNLayoutGuideViewController"] ] view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false let topAnchor = tableView.topAnchor.constraint(equalTo: view.topAnchor) let bottomAnchor = tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) let leadingAnchor = tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor) let trailingAnchor = tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor) NSLayoutConstraint.activate([topAnchor,bottomAnchor,leadingAnchor,trailingAnchor]) tableView.separatorInset = .zero tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: identifier) } } extension CodeNativeLayoutViewController : UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return layoutWays.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) cell.selectionStyle = .none cell.textLabel?.text = layoutWays[indexPath.row]["title"] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let vClass = layoutWays[indexPath.row]["className"] { let vc = NSClassFromString("AutoLayoutDemo."+vClass) as! UIViewController.Type navigationController?.pushViewController(vc.init(), animated: true) } } }
// // test.swift // oneone // // Created by levi.luo on 2017/8/13. // Copyright © 2017年 levi.luo. All rights reserved. // import Foundation
// // ViewController.swift // iOS_SwiftTestApp // // Created by 松下将俊 on 2019/08/12. // Copyright © 2019 松下将俊. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
import SwiftUI import SortKit public struct SortAnimationContentView<Element: SortableElement>: View { private let initialElement: [Element] public let sortAlgorithm: SortAlgorithm public init(sortAlgorithm: SortAlgorithm, initialElement: [Element]) { self.sortAlgorithm = sortAlgorithm self.initialElement = initialElement } public var body: some View { HStack { SortAnimationView(SortAnimation(initialElement, sortAlgorithm: sortAlgorithm)) } } }
// // LiveViewController.swift // MyDYZB // // Created by 王武 on 2020/10/25. // import UIKit class LiveViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
// // ASHSearchBar.swift // SHSearchedViewController // // Created by Shkil Artur on 1/18/19. // Copyright © 2019 Shkil Artur. All rights reserved. // import UIKit class ASHSearchBar: UISearchBar { init() { super.init(frame: CGRect()) showsCancelButton = true } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
// // FbAccountViewModel.swift // Grubbie // // Created by JABE on 12/9/15. // Copyright © 2015 JABELabs. All rights reserved. // struct FBAccountViewModel { var fbAccount : AppUser var isSelected: Bool = false init(fbAccount: AppUser){ self.fbAccount = fbAccount } } enum ShareType : Int { case Unknown = -1 case GrubbieShare = 1 case AdhocShare } class ShareSessionInfo { var sharedBy : String var fbRecipients : [AppUser] var grubbieRecipients : [AppUser] // var photos : [PhotoSource] var photos: [SharePhoto] var shareType : ShareType init(){ sharedBy = Util.getCurrentUserId() fbRecipients = [AppUser]() grubbieRecipients = [AppUser]() // photos = [PhotoSource]() photos = [SharePhoto]() shareType = .Unknown } }
import Foundation import TMDb extension MediaPageableList { static func mock( page: Int = Int.random(in: 1...5), results: [Media] = .mocks, totalResults: Int? = Int.random(in: 1...100), totalPages: Int? = Int.random(in: 1...5) ) -> Self { .init( page: page, results: results, totalResults: totalResults, totalPages: totalPages ) } }
// // MovieController.swift // MyMovies // // Created by Spencer Curtis on 8/17/18. // Copyright © 2018 Lambda School. All rights reserved. // import Foundation import CoreData class MovieController { static let shared = MovieController() private let apiKey = "4cc920dab8b729a619647ccc4d191d5e" private let baseURL = URL(string: "https://api.themoviedb.org/3/search/movie")! func searchForMovie(with searchTerm: String, completion: @escaping (Error?) -> Void) { var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true) let queryParameters = ["query": searchTerm, "api_key": apiKey] components?.queryItems = queryParameters.map({URLQueryItem(name: $0.key, value: $0.value)}) guard let requestURL = components?.url else { completion(NSError()) return } URLSession.shared.dataTask(with: requestURL) { (data, _, error) in if let error = error { NSLog("Error searching for movie with search term \(searchTerm): \(error)") completion(error) return } guard let data = data else { NSLog("No data returned from data task") completion(NSError()) return } do { let movieRepresentations = try JSONDecoder().decode(MovieRepresentations.self, from: data).results self.searchedMovies = movieRepresentations completion(nil) } catch { NSLog("Error decoding JSON data: \(error)") completion(error) } }.resume() } func createFromSearch(indexPath: IndexPath){ guard let movie = Movie(movieRepresentation: searchedMovies[indexPath.row], creationFromList: true) else { return } create(movie: movie) } // MARK: - Properties var searchedMovies: [MovieRepresentation] = [] //MARK: - CoreData & Firebase let firebaseURL = URL(string: "https://movies-84b85.firebaseio.com/")! typealias CompletionHandler = (Error?) -> Void init() { read() } func create(movie: Movie, completion: @escaping CompletionHandler = { _ in }) { let uuid = movie.identifier ?? UUID() var request = URLRequest(url: firebaseURL.appendingPathComponent(uuid.uuidString).appendingPathExtension("json")) request.httpMethod = "PUT" do { guard var representation = movie.movieRepresentation else { completion(NSError()); return } representation.identifier = uuid.uuidString movie.identifier = uuid try CoreDataStack.shared.save() request.httpBody = try JSONEncoder().encode(representation) } catch { print("Error encoding movie \(movie): \(error)") DispatchQueue.main.async { completion(error) } return } URLSession.shared.dataTask(with: request) { _, _, error in if let error = error { print("Error PUTting movie to server: \(error)") DispatchQueue.main.async { completion(error) } return } DispatchQueue.main.async { completion(nil) } }.resume() } func read(completion: @escaping CompletionHandler = { _ in }) { let requestURL = firebaseURL.appendingPathExtension("json") URLSession.shared.dataTask(with: requestURL) { data, _, error in if let error = error { print("Error fetching movies: \(error)") DispatchQueue.main.async { completion(error) } return } guard let data = data else { print("No data return by data entry") DispatchQueue.main.async { completion(NSError()) } return } do { let movieRepresentations = Array(try JSONDecoder().decode([String : MovieRepresentation].self, from: data).values) try self.update(with: movieRepresentations) DispatchQueue.main.async { completion(nil) } } catch { print("Error decoding or storing movie representations: \(error)") DispatchQueue.main.async { completion(error) } } }.resume() } func update(_ movie: Movie, hasWatched: Bool) { guard let title = movie.title, let identifier = movie.identifier else { return } let overview = movie.overview ?? "" delete(movie) CoreDataStack.shared.mainContext.delete(movie) do { try CoreDataStack.shared.mainContext.save() } catch { CoreDataStack.shared.mainContext.reset() NSLog("Error saving managed object context: \(error)") } create(movie: Movie(title: title, identifier: identifier, hasWatched: hasWatched, overview: overview)) } func delete(_ movie: Movie, completion: @escaping CompletionHandler = { _ in }) { guard let uuid = movie.identifier else { completion(NSError()); return } let requestURL = firebaseURL.appendingPathComponent(uuid.uuidString).appendingPathExtension("json") var request = URLRequest(url: requestURL) request.httpMethod = "DELETE" URLSession.shared.dataTask(with: request) { _, response, error in print(response!) DispatchQueue.main.async { completion(error) } }.resume() } // MARK: - Internal methods private func update(with representations: [MovieRepresentation]) throws { guard representations.isEmpty == false else { return } let moviesWithID = representations.filter { $0.identifier != nil } let identifiersToFetch = moviesWithID.compactMap { UUID(uuidString: $0.identifier!) } let representationsByID = Dictionary(uniqueKeysWithValues: zip(identifiersToFetch, moviesWithID)) var moviesToCreate = representationsByID let fetchRequest: NSFetchRequest<Movie> = Movie.fetchRequest() fetchRequest.predicate = NSPredicate(format: "identifier IN %@", identifiersToFetch) let context = CoreDataStack.shared.container.newBackgroundContext() context.perform { do { let existingMovies = try context.fetch(fetchRequest) for movie in existingMovies { guard let id = movie.identifier, let representation = representationsByID[id] else { continue } self.updateData(movie: movie, with: representation) moviesToCreate.removeValue(forKey: id) } for representation in moviesToCreate.values { Movie(movieRepresentation: representation, context: context) } } catch { print("Error fetching movies for UUIDs: \(error)") } } try CoreDataStack.shared.save(context: context) } private func updateData(movie: Movie, with representation: MovieRepresentation) { movie.title = representation.title movie.hasWatched = representation.hasWatched ?? false movie.overview = representation.overview ?? "" } }
// // MenuGroupingTests.swift // MenuGroupingTests // // Created by 이동건 on 2021/09/14. // import XCTest @testable import XCTestDemo class MenuGroupingTests: XCTestCase { func testMenuWithManyCategoriesReturnsAsManySectionsInReverseAlphabeticalOrder() { let menu: [MenuItem] = [ .fixture(category: "pastas", name: "a pasta"), .fixture(category: "drinks", name: "a drink"), .fixture(category: "pastas", name: "another pasta"), .fixture(category: "desserts", name: "a dessert"), ] let sections = groupMenuByCategory(menu) XCTAssertEqual(sections.count, 3) XCTAssertEqual(sections[safe: 0]?.category, "pastas") XCTAssertEqual(sections[safe: 1]?.category, "drinks") XCTAssertEqual(sections[safe: 2]?.category, "desserts") } func testMenuWithOneCategoryReturnsOneSection() { let menu = [ MenuItem.fixture(category: "pastas", name: "name"), MenuItem.fixture(category: "pastas", name: "other name") ] let sections = groupMenuByCategory(menu) XCTAssertEqual(sections.count, 1) let section = try! XCTUnwrap(sections.first) XCTAssertEqual(section.items.count, 2) XCTAssertEqual(section.items.first?.name, "name") XCTAssertEqual(section.items.last?.name, "other name") } func testEmptyMenuReturnsEmptySections() { // Arrange the input: an empty menu let menu = [MenuItem]() // Act on the SUT to get the output: the sections array let sections = groupMenuByCategory(menu) // Assert XCTAssertTrue(sections.isEmpty) } }
// // PropertyImageViewCell.swift // SweepBright Beta // // Created by Kaio Henrique on 11/25/15. // Copyright © 2015 madewithlove. All rights reserved. // import UIKit class PropertyImageViewCell: UICollectionViewCell { @IBOutlet weak var imageview: UIImageView! @IBOutlet weak var checkLabel: UILabel! var image: SWBPropertyImage! { didSet { if let propertyImage = image.image { self.imageview.image = propertyImage self.imageview.hidden = false } else { self.imageview.hidden = true } } } }
// // UnsplashService.swift // OneSplash // // Created by Rustam-Deniz on 8/4/20. // Copyright © 2020 Terns. All rights reserved. // import Foundation import Alamofire class UnsplashService { func getSamplePhotos() { let params: Parameters = [ "client_id": UnsplashAPI.token ] AF.request(UnsplashAPI.baseURL + UnsplashAPI.photosPostfix, method: .get, parameters: params).response { (response) in switch response.result { case .success(let data): if data != nil { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase do { let photos = try decoder.decode([Photo].self, from: data!) print(photos) } catch { debugPrint(error) } } case .failure(let error): debugPrint(error) } } } func getCollections(page: Int, success: @escaping ([Collection]) -> Void, failure: @escaping (AFError) -> Void) { let params: Parameters = [ "client_id": UnsplashAPI.token, "page": page ] AF.request(UnsplashAPI.baseURL + UnsplashAPI.collectionsPostfix, method: .get, parameters: params).response { (response) in switch response.result { case .success(let data): if data != nil { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase do { let collection = try decoder.decode([Collection].self, from: data!) print(collection) success(collection) } catch { debugPrint(error) } } case .failure(let error): debugPrint(error) } } } }
// // TopicCellViewModel.swift // DiscourseClient // // Created by Roberto Garrido on 08/02/2020. // Copyright © 2020 Roberto Garrido. All rights reserved. // import UIKit protocol TopicCellViewModelDelegate: class { func imageFetched() } class TopicCellViewModel: CellViewModel { weak var delegate: TopicCellViewModelDelegate? var topicTitle: String? var postsCount: Int? var postersCount: Int? var lastPostedAt: String? var dateFormatted: String? var topicImage: UIImage? init(topic: Topic, user: User) { super.init(topic: topic) topicTitle = topic.title postsCount = topic.postsCount postersCount = topic.posters.count lastPostedAt = topic.lastPostedAt insertImage(user: user) } func insertImage(user: User) { var imageStringURL = "https://mdiscourse.keepcoding.io" imageStringURL.append(user.avatarTemplate.replacingOccurrences(of: "{size}", with: "64")) DispatchQueue.global(qos: .userInitiated).async { [weak self] in if let url = URL(string: imageStringURL), let data = try? Data(contentsOf: url) { self?.topicImage = UIImage(data: data) DispatchQueue.main.async { self?.delegate?.imageFetched() } } } } func dateFormatter(date: String) -> String { let inputFormat = "YYYY-MM-dd'T'HH:mm:ss.SSSZ" let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "es_ES") dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) dateFormatter.dateFormat = inputFormat let dates = dateFormatter.date(from: date) let outputFormat = "MMM dd" dateFormatter.dateFormat = outputFormat let outputStringDate = dateFormatter.string(from: dates!) return outputStringDate } }
// // FizzBuzzUITests.swift // FizzBuzzUITests // // Created by Thinh Luong on 3/19/17. // Copyright © 2017 Thinh Luong. All rights reserved. // import XCTest class FizzBuzzUITests: XCTestCase { let app = XCUIApplication() override func setUp() { super.setUp() continueAfterFailure = false app.launch() } override func tearDown() { super.tearDown() } func testIncrementButton() { app.buttons["Increment"].tap() XCTAssert(app.staticTexts["1"].exists) } }
// // GService+GetMapData.swift // GMapService // // Created by Jose Zarzuela on 24/12/2014. // Copyright (c) 2014 Jose Zarzuela. All rights reserved. // import Foundation import JZBUtils //============================================================================================================================ public extension GService { //------------------------------------------------------------------------------------------------------------------------ public func createFeatures(features:[GFeature], inout error:NSError?) -> Bool { return _commonCode(features, strRequestFunc:_strRequestCreate, error: &error) } //------------------------------------------------------------------------------------------------------------------------ public func updateFeatures(features:[GFeature], inout error:NSError?) -> Bool { return _commonCode(features, strRequestFunc:_strRequestUpdate, error: &error) } //------------------------------------------------------------------------------------------------------------------------ public func deleteFeatures(features:[GFeature], inout error:NSError?) -> Bool { return _commonCode(features, strRequestFunc:_strRequestDelete, error: &error) } //======================================================================================================================== // MARK: Private support methods //------------------------------------------------------------------------------------------------------------------------ private func _commonCode(features:[GFeature], strRequestFunc:(features:[GFeature])->String, inout error:NSError?) -> Bool { // Comprueba si hay algo que hacer if features.count == 0 { return true } // Comprueba que todas son del mismo mapa let ownerMap = features[0].table.layer.map for feature in features { if !(ownerMap === feature.table.layer.map) { error = _error("Al features must belong to the same map") return false } } // Se debe estar logado para poder pedir informacion al servicio remoto if let error = _checkIfLoggedIn() { return false } // Necesita un xsrfToken para la peticion if let xsrfToken = getXsrfToken(&error) { // Realiza la peticion de creacion let strReq = strRequestFunc(features: features) return _requestAssetCRUD(xsrfToken, crudStr:strReq , error: &error) } // Algo ha salido mal return false } //------------------------------------------------------------------------------------------------------------------------ private func _strRequestCreate(features:[GFeature]) -> String { let map_id = features[0].table.layer.map.gid let table_id = features[0].table.gid var reqStr = "[\"\(map_id)\",[\"\(table_id)\",[" for (index,feature) in enumerate(features) { if index>0 { reqStr += "," } reqStr += "[\"\(feature.gid)\"," reqStr += "null,null,null,null,null,null,null,null,null,null,[" var firstItem = true for (name,(type, userProp)) in feature.table.schema { if firstItem { firstItem = false } else { reqStr += "," } reqStr += _propertyRender(name, propType: type, propValue: feature.allProperties[name]) } reqStr += "]]" } reqStr += "]],null,null,null,null,null,null,null,null,null,null,null,null,null,null,[[]]]" return reqStr } //------------------------------------------------------------------------------------------------------------------------ private func _strRequestUpdate(features:[GFeature]) -> String { let map_id = features[0].table.layer.map.gid let table_id = features[0].table.gid var reqStr = "[\"\(map_id)\",null,null,null,[\"\(table_id)\",[" for (index,feature) in enumerate(features) { if index>0 { reqStr += "," } reqStr += "[\"\(feature.gid)\"," reqStr += "null,null,null,null,null,null,null,null,null,null,[" var firstItem = true for (name,(type,userProp)) in feature.table.schema { if firstItem { firstItem = false } else { reqStr += "," } reqStr += _propertyRender(name, propType: type, propValue: feature.allProperties[name]) } reqStr += "]]" } reqStr += "]],null,null,null,null,null,null,null,null,null,null,null,[[]]]" return reqStr } //------------------------------------------------------------------------------------------------------------------------ private func _strRequestDelete(features:[GFeature]) -> String { let map_id = features[0].table.layer.map.gid let table_id = features[0].table.gid var reqStr = "[\"\(map_id)\", null,[\"\(table_id)\",[" for (index,feature) in enumerate(features) { if index>0 { reqStr += "," } reqStr += "\"\(feature.gid)\"" } reqStr += "]],null,null,null,null,null,null,null,null,null,null,null,null,null,[[]]]" return reqStr } //------------------------------------------------------------------------------------------------------------------------ private func _propertyRender(propName:String, propType:GESchemaType, propValue:GPropertyType?) -> String { var strValue = "[\"\(propName)\"" if let value = propValue { switch propType { case .ST_DIRECTIONS: // TODO: COMO SE HACE ESTO? break case .ST_BOOL: strValue += ", null, \"\(value)\", null, null, null, null, true" //2 case .ST_NUMERIC: strValue += ", null, null, \"\(value)\", null, null, null, true" // 3 case .ST_STRING: strValue += ", null, null, null, \"\(value)\", null, null, true" // 4 case .ST_DATE: strValue += ", null, null, null, null, \"\(value)\", null, true" // 5 case .ST_GEOMETRY: strValue += ", null, null, null, null, null, [\(_geometryRender(value))], true" case .ST_GX_METADATA: // TODO: COMO SE HACE ESTO? break } } strValue += "]" return strValue } //------------------------------------------------------------------------------------------------------------------------ private func _geometryRender(value:GPropertyType) -> String { switch value { case let point as GGeometryPoint: return "[\(_geoPointRender(point))], [], []" case let line as GGeometryLine: var strValue = "[], [[[" for (index, point) in enumerate(line.points) { let comma = index>0 ? "x" : "u" strValue += "\(comma)\(_geoPointRender(point))" } strValue += "]]], []" return strValue case let polygon as GGeometryPolygon: var strValue = "[], [], [[[[[" for (index, point) in enumerate(polygon.points) { let comma = index>0 ? "x" : "u" strValue += "\(comma)\(_geoPointRender(point))" } strValue += "]]]]]" return strValue default: // TODO: Aqui no deberia llegar return "null" } } //------------------------------------------------------------------------------------------------------------------------ private func _geoPointRender(point:GGeometryPoint) -> String { return "[\(point.lat),\(point.lng)]" } }
// // MostCommonCharacter.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func mostCommonCharacter(inventory: [UDItem]) -> Character? { if inventory.count == 0{ return nil }else{ var characters = [Character:Int]() //iterate through inventory items and get characters from names for item in inventory{ let lowercaseName = item.name.lowercaseString for letter in lowercaseName.characters { if let _ = characters[letter] { characters[letter]! += 1 }else{ characters[letter] = 1 } } } print (characters) // Find most common character var mostCommon: Character? var occurances: Int = 0 for (char, number) in characters { if number > occurances { mostCommon = char occurances = number } } return mostCommon } } }
import Vapor public func configure(_ app: Application) throws { app.botService = .init(pravdaService: app.pravdaService) }
// // QuizLabel.swift // Quiz // // Created by NIKOLAI BORISOV on 08.08.2021. // import UIKit final class QuizLabel: UILabel { init() { super.init(frame: .zero) self.configureSelf() } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureSelf() { self.numberOfLines = 0 self.textAlignment = .center self.font = UIFont.labelFont20 self.layer.cornerRadius = 10 self.layer.borderWidth = 2 self.layer.borderColor = UIColor.white.cgColor self.textColor = .white self.adjustsFontSizeToFitWidth = true self.layer.masksToBounds = true } }
import Foundation //3. Dijkstra for the Data Structures Representation class Node { var value: Int var visited: Bool var pathValue: Int = Int.max var links: [Link] = [] init(value: Int) { self.value = value self.visited = false } } class Link { var to: Node var weight: Int init(to: Node, weight: Int) { self.to = to self.weight = weight } } class GraphData { var arrNodes = [Node]() func add(value: Int) -> Node { let newNode = Node(value: value) arrNodes.append(newNode) return newNode } func addLink(from: Node, to: Node, weight: Int, weightBack: Int?) { from.links.append(Link(to: to, weight: weight)) if let weightBack = weightBack { to.links.append(Link(to: from, weight: weightBack)) } } func Dijkstra() { arrNodes[0].pathValue = 0 while arrNodes.filter({ !$0.visited }).count > 0 { var minNodes: Node? for i in 0..<arrNodes.count { if arrNodes[i].pathValue < (minNodes?.pathValue ?? Int.max) && !arrNodes[i].visited { minNodes = arrNodes[i] } } guard let minNode = minNodes else { fatalError() } minNode.visited = true for i in minNode.links { if (i.to.pathValue > minNode.pathValue + i.weight) && !i.to.visited { i.to.pathValue = minNode.pathValue + i.weight } } } } } /* var test = GraphData() var head = test.add(value: 1) var sN = test.add(value: 2) var tN = test.add(value: 3) var zN = test.add(value: 4) var xN = test.add(value: 5) var yN = test.add(value: 6) test.addLink(from: head, to: sN, weight: 10, weightBack: 10) test.addLink(from: head, to: tN, weight: 7, weightBack: 7) test.addLink(from: sN, to: zN, weight: 1, weightBack: 5) test.addLink(from: sN, to: xN, weight: 5, weightBack: 5) test.addLink(from: tN, to: yN, weight: 3, weightBack: 7) test.addLink(from: tN, to: xN, weight: 13, weightBack: 13) test.addLink(from: xN, to: yN, weight: 2, weightBack: nil) test.Dijkstra() head.pathValue sN.pathValue tN.pathValue zN.pathValue xN.pathValue yN.pathValue test.Dijkstra() head.pathValue sN.pathValue tN.pathValue zN.pathValue xN.pathValue yN.pathValue */
// // BasicTableCell.swift // NeoMusic-SwiftUI // // Created by Jordan Christensen on 11/19/20. // import SwiftUI struct BasicTableCell: View { private let labelText: String private let image: Image? private let detailText: String? var text: String { labelText } init(label: String, detail: String?, image: Image? = nil) { self.labelText = label self.detailText = detail self.image = image } var body: some View { HStack(spacing: 7) { if let image = image { image .resizable() .scaledToFit() .frame(width: Self.rowHeight - 5, height: Self.rowHeight - 5) } VStack(alignment: .leading) { Text(labelText) .font(.body) if let detail = detailText { Text(detail) .font(.caption) } } .spacing(.vertical) Spacer() } .frame(height: Self.rowHeight) } static let rowHeight: CGFloat = 30 } struct UpNextRow_Previews: PreviewProvider { @State static var selected: AMSong = .noSong static var previews: some View { BasicTableCell(label: "Hello, World!", detail: "Hi, Universe!") } } @_functionBuilder struct BasicCellBuilder { static func buildBlock(_ children: BasicTableCell...) -> [BasicTableCell] { children } }
// // LayoutNode+AddingNodes.swift // LayoutTools // // Created by James Bean on 7/23/16. // // import TreeTools import QuartzCore extension LayoutNode { // MARK: - Add nodes /** Append child node. */ public func addChild(_ node: LayoutNode) { children.append(node) node.parent = self commitLayer(for: node) } /** Insert the given `node` at the given `index`. - throws: `NodeError.insertionError` if the given `index` is out-of-bounds. */ public func insertChild(_ node: LayoutNode, at index: Int) throws { guard index >= children.startIndex && index <= children.endIndex else { throw NodeError.insertionError } if index == children.endIndex { children.append(node) } else { children.insert(node, at: index) } node.parent = self commitLayer(for: node) } /** Insert the given `node` before another `node`. - throws: `NodeError.insertionError` if the other `node` is not contained herein. */ public func insertChild(_ node: LayoutNode, before other: LayoutNode) throws { guard let index = children.index(of: other) else { throw NodeError.insertionError } try insertChild(node, at: index) } /** Insert the given `node` after another `node`. - throws: `NodeError.insertionError` if the other `node` is not contained herein. */ public func insertChild(_ node: LayoutNode, after other: LayoutNode) throws { guard let index = children.index(of: other) else { throw NodeError.insertionError } try insertChild(node, at: index + 1) } fileprivate func commitLayer(for node: LayoutNode) { CATransaction.setDisableActions(true) node.layer.removeFromSuperlayer() layer.addSublayer(node.layer) CATransaction.setDisableActions(false) } }
// // BrowsingSession.swift // Orion // // Created by Eduard Shahnazaryan on 3/12/21. // import Foundation import RealmSwift class URLModel: Object { @objc dynamic var urlString = "" @objc dynamic var pageTitle = "" } class BrowsingSession: Object { let tabs = List<URLModel>() @objc dynamic var selectedTabIndex = 0 }
// // PlayListFilter.swift // MyLeaderboard // // Created by Joseph Roque on 2020-03-15. // Copyright © 2020 Joseph Roque. All rights reserved. // import myLeaderboardApi struct PlayListFilter { let gameID: GraphID? let playerIDs: [GraphID] init(gameID: GraphID? = nil, playerIDs: [GraphID] = []) { self.gameID = gameID self.playerIDs = playerIDs } }
// // HomeAssembly.swift // iOSBoilerplate // // Created by sadman samee on 9/18/19. // Copyright © 2019 sadman samee. All rights reserved. // import Foundation import Moya import Swinject import SwinjectAutoregistration final class HomeAssembly: Assembly { func assemble(container: Container) { let userService = UserService() let authPlugin = AccessTokenPlugin { _ in userService.loadToken() ?? "" } container.register(UserService.self, factory: { _ in userService }).inObjectScope(ObjectScope.container) container.register(MoyaProvider<BooksService>.self, factory: { _ in MoyaProvider<BooksService>(plugins: [authPlugin, NetworkLoggerPlugin(configuration: .init(formatter: .init(responseData: JSONResponseDataFormatter), logOptions: .verbose))]) }).inObjectScope(ObjectScope.container) container.register(HomeViewModel.self, factory: { container in HomeViewModel(service: container.resolve(MoyaProvider<BooksService>.self)!, userService: userService) }).inObjectScope(ObjectScope.container) // view controllers container.storyboardInitCompleted(HomeVC.self) { r, c in c.homeViewModel = r.resolve(HomeViewModel.self) } container.storyboardInitCompleted(BookDetailVC.self) { _, _ in } } }
// // AppState.swift // EhPanda // // Created by 荒木辰造 on R 2/12/26. // import SwiftUI import Foundation struct AppState { var environment = Environment() var settings = Settings() var homeInfo = HomeInfo() var detailInfo = DetailInfo() var contentInfo = ContentInfo() } extension AppState { // MARK: Environment struct Environment { var isPreview = false var isAppUnlocked = true var blurRadius: CGFloat = 0 var viewControllersCount = 1 var isSlideMenuClosed = true var navBarHidden = false var favoritesIndex = -1 var toplistsType: ToplistsType = .allTime var homeListType: HomeListType = .frontpage var homeViewSheetState: HomeViewSheetState? var settingViewSheetState: SettingViewSheetState? var settingViewActionSheetState: SettingViewActionSheetState? var filterViewActionSheetState: FilterViewActionSheetState? var detailViewSheetState: DetailViewSheetState? var commentViewSheetState: CommentViewSheetState? var galleryItemReverseID: String? var galleryItemReverseLoading = false var galleryItemReverseLoadFailed = false } // MARK: Settings struct Settings { var userInfoLoading = false var favoriteNamesLoading = false var greetingLoading = false var appEnv: AppEnv { PersistenceController.fetchAppEnvNonNil() } @AppEnvStorage(type: User.self) var user: User @AppEnvStorage(type: Filter.self) var filter: Filter @AppEnvStorage(type: Setting.self) var setting: Setting @AppEnvStorage(type: TagTranslator.self, key: "tagTranslator") var tagTranslator: TagTranslator mutating func update(user: User) { if let displayName = user.displayName { self.user.displayName = displayName } if let avatarURL = user.avatarURL { self.user.avatarURL = avatarURL } if let currentGP = user.currentGP, let currentCredits = user.currentCredits { self.user.currentGP = currentGP self.user.currentCredits = currentCredits } } mutating func insert(greeting: Greeting) { guard let currDate = greeting.updateTime else { return } if let prevGreeting = user.greeting, let prevDate = prevGreeting.updateTime, prevDate < currDate { user.greeting = greeting } else if user.greeting == nil { user.greeting = greeting } } } } extension AppState { // MARK: HomeInfo struct HomeInfo { var searchKeyword = "" var searchItems: [Gallery]? var searchLoading = false var searchNotFound = false var searchLoadFailed = false var searchCurrentPageNum = 0 var searchPageNumMaximum = 1 var moreSearchLoading = false var moreSearchLoadFailed = false var frontpageItems: [Gallery]? var frontpageLoading = false var frontpageNotFound = false var frontpageLoadFailed = false var frontpageCurrentPageNum = 0 var frontpagePageNumMaximum = 1 var moreFrontpageLoading = false var moreFrontpageLoadFailed = false var popularItems: [Gallery]? var popularLoading = false var popularNotFound = false var popularLoadFailed = false var watchedItems: [Gallery]? var watchedLoading = false var watchedNotFound = false var watchedLoadFailed = false var watchedCurrentPageNum = 0 var watchedPageNumMaximum = 1 var moreWatchedLoading = false var moreWatchedLoadFailed = false var favoritesItems = [Int: [Gallery]]() var favoritesLoading = generateBoolDict(range: -1..<10) var favoritesNotFound = generateBoolDict(range: -1..<10) var favoritesLoadFailed = generateBoolDict(range: -1..<10) var favoritesCurrentPageNum = generateIntDict(range: -1..<10) var favoritesPageNumMaximum = generateIntDict(defaultValue: 1, range: -1..<10) var moreFavoritesLoading = generateBoolDict(range: -1..<10) var moreFavoritesLoadFailed = generateBoolDict(range: -1..<10) var toplistsItems = [Int: [Gallery]]() var toplistsLoading = generateBoolDict(range: 0..<4) var toplistsNotFound = generateBoolDict(range: 0..<4) var toplistsLoadFailed = generateBoolDict(range: 0..<4) var toplistsCurrentPageNum = generateIntDict(range: 0..<4) var toplistsPageNumMaximum = generateIntDict(defaultValue: 1, range: 0..<4) var moreToplistsLoading = generateBoolDict(range: 0..<4) var moreToplistsLoadFailed = generateBoolDict(range: 0..<4) @AppEnvStorage(type: [String].self, key: "historyKeywords") var historyKeywords: [String] static func generateBoolDict(defaultValue: Bool = false, range: Range<Int>) -> [Int: Bool] { var tmp = [Int: Bool]() range.forEach { index in tmp[index] = defaultValue } return tmp } static func generateIntDict(defaultValue: Int = 0, range: Range<Int>) -> [Int: Int] { var tmp = [Int: Int]() range.forEach { index in tmp[index] = defaultValue } return tmp } mutating func insertSearchItems(galleries: [Gallery]) { galleries.forEach { gallery in if searchItems?.contains(gallery) == false { searchItems?.append(gallery) } } } mutating func insertFrontpageItems(galleries: [Gallery]) { galleries.forEach { gallery in if frontpageItems?.contains(gallery) == false { frontpageItems?.append(gallery) } } } mutating func insertWatchedItems(galleries: [Gallery]) { galleries.forEach { gallery in if watchedItems?.contains(gallery) == false { watchedItems?.append(gallery) } } } mutating func insertFavoritesItems(favIndex: Int, galleries: [Gallery]) { galleries.forEach { gallery in if favoritesItems[favIndex]?.contains(gallery) == false { favoritesItems[favIndex]?.append(gallery) } } } mutating func insertToplistsItems(topIndex: Int, galleries: [Gallery]) { galleries.forEach { gallery in if toplistsItems[topIndex]?.contains(gallery) == false { toplistsItems[topIndex]?.append(gallery) } } } mutating func insertHistoryKeyword(text: String) { guard !text.isEmpty else { return } if let index = historyKeywords.firstIndex(of: text) { if historyKeywords.last != text { historyKeywords.remove(at: index) historyKeywords.append(text) } } else { historyKeywords.append(text) let overflow = historyKeywords.count - 10 if overflow > 0 { historyKeywords = Array( historyKeywords.dropFirst(overflow) ) } } self.historyKeywords = historyKeywords } } // MARK: DetailInfo struct DetailInfo { var detailLoading = [String: Bool]() var detailLoadFailed = [String: Bool]() var archiveFundsLoading = false var previews = [String: [Int: String]]() var previewsLoading = [String: [Int: Bool]]() var previewConfig = PreviewConfig.normal(rows: 4) var pendingJumpPageIndices = [String: Int]() var pendingJumpCommentIDs = [String: String]() mutating func fulfillPreviews(gid: String) { let galleryState = PersistenceController .fetchGalleryStateNonNil(gid: gid) previews[gid] = galleryState.previews } mutating func update(gid: String, previews: [Int: String]) { guard !previews.isEmpty else { return } if self.previews[gid] == nil { self.previews[gid] = [:] } self.previews[gid] = self.previews[gid]?.merging( previews, uniquingKeysWith: { stored, _ in stored } ) } } struct ContentInfo { var mpvKeys = [String: String]() var mpvImageKeys = [String: [Int: String]]() var mpvImageLoading = [String: [Int: Bool]]() var contents = [String: [Int: String]]() var contentsLoading = [String: [Int: Bool]]() var contentsLoadFailed = [String: [Int: Bool]]() mutating func fulfillContents(gid: String) { let galleryState = PersistenceController .fetchGalleryStateNonNil(gid: gid) contents[gid] = galleryState.contents } mutating func update(gid: String, contents: [Int: String]) { guard !contents.isEmpty else { return } if self.contents[gid] == nil { self.contents[gid] = [:] } self.contents[gid] = self.contents[gid]?.merging( contents, uniquingKeysWith: { stored, _ in stored } ) } } }
// // SignUpPasswordViewController.swift // OSOM_app // // Created by Miłosz Bugla on 22.10.2017. // import Foundation import UIKit import SwiftValidator final class SignUpPasswordViewController: UIViewController { fileprivate let mainView: SignUpPasswordView fileprivate let viewModel: SignUpPasswordViewModel fileprivate var navigator: NavigationController? fileprivate let validator = Validator() init(mainView: SignUpPasswordView, viewModel: SignUpPasswordViewModel) { self.mainView = mainView self.viewModel = viewModel super.init(nibName: nil, bundle: nil) self.viewModel.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { setupView() setupNavigation() } override func viewDidAppear(_ animated: Bool) { DispatchQueue.main.async(execute: { self.mainView.fadeIn() }) } fileprivate func setupNavigation() { navigator = NavigationController(navigationView: mainView.navigation, navigationController: navigationController) navigator?.delegate = self } private func setupView() { view = mainView mainView.setupView() registerValidatableFields() } } extension SignUpPasswordViewController: NavigationControllerDelegate { func rightAction() { validator.validate(self) } func backAction() { mainView.animate(entry: false, completion: { self.navigationController?.popViewController(animated: false) }) } } extension SignUpPasswordViewController: ValidationDelegate { func validationSuccessful() { mainView.clearsErrorLabels() viewModel.register(password: mainView.passwordEditField.textField.text ?? "") } func validationFailed(_ errors: [(Validatable, ValidationError)]) { mainView.clearsErrorLabels() for (field, error) in errors { if let field = field as? UITextField { error.errorLabel?.text = error.errorMessage field.shake() } } } fileprivate func registerValidatableFields() { let repeatPasswordRule = RepeatPasswordRule(compareField: mainView.passwordEditField.textField) let minLenght = MinLengthRule(length: 6) validator.registerField(mainView.passwordEditField.textField, errorLabel: mainView.passwordEditField.errorLabel, rules: [RequiredRule(), minLenght]) validator.registerField(mainView.repeatPasswordEditField.textField, errorLabel: mainView.repeatPasswordEditField.errorLabel, rules: [RequiredRule(), repeatPasswordRule]) } } extension SignUpPasswordViewController: SignUpPasswordViewModelDelegate { func signUpSuccessed() { mainView.animate(entry: true, completion: { let vc = ViewControllerContainer.shared.getCreateAbout() self.navigationController?.pushViewController(vc, animated: false) }) } func signUpFailed() { print("SignUp f") } }
// // NSObjectProtocol.swift // DHBC // // Created by Kiều anh Đào on 9/14/20. // Copyright © 2020 Anhdk. All rights reserved. // import Foundation extension NSObjectProtocol { static var className: String { return String(describing: self) } }
// // DiscoverTableViewCell.swift // inke // // Created by bb on 2017/8/1. // Copyright © 2017年 bb. All rights reserved. // import UIKit import SnapKit class LiveNodeTableViewCell: UITableViewCell { var live_Nodes: Live_NodesModel = Live_NodesModel(){ didSet { updateUI() } } lazy var titleLabel: UILabel = { var titleLabel = UILabel() titleLabel.textColor = UIColor.init(r: 51, g: 51, b: 51) titleLabel.font = UIFont.systemFont(ofSize: 15) return titleLabel }() lazy var detailTitleLabel: UILabel = { var detailTitleLabel = UILabel() detailTitleLabel.textColor = UIColor.init(r: 170, g: 170, b: 170) detailTitleLabel.font = UIFont.systemFont(ofSize: 13) return detailTitleLabel }() lazy var arrowImageView: UIImageView = { var arrowImageView = UIImageView() arrowImageView.image = UIImage(named: "search_star_global_arrow_more") arrowImageView.sizeToFit() arrowImageView.contentMode = .scaleAspectFit return arrowImageView }() lazy var collectionView: LiveCollectionView = { var collectionView = LiveCollectionView() return collectionView }() lazy var splitView: UIView = { var spliteView = UIView() spliteView.backgroundColor = UIColor.init(r: 242, g: 242, b: 242) return spliteView }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) if !self.isEqual(nil) { setupUI() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension LiveNodeTableViewCell { fileprivate func setupUI() { for subview in self.contentView.subviews{ subview.removeFromSuperview() } self.addSubview(arrowImageView) self.addSubview(titleLabel) self.addSubview(detailTitleLabel) self.addSubview(collectionView) self.addSubview(splitView) self.contentView.snp.makeConstraints { (make) in make.left.equalTo(self) make.top.equalTo(self) make.right.equalTo(self) make.bottom.equalTo(self.collectionView) } arrowImageView.snp.makeConstraints { (make) in make.right.equalTo(self.contentView).offset(-10) make.top.equalTo(self.contentView).offset(15) make.width.lessThanOrEqualTo(15) make.height.equalTo(16) } titleLabel.snp.makeConstraints { (make) in make.left.equalTo(self.contentView).offset(15) make.centerY.equalTo(arrowImageView) make.right.equalTo(arrowImageView.snp.left) make.height.equalTo(arrowImageView.snp.height) } detailTitleLabel.snp.makeConstraints { (make) in make.left.equalTo(titleLabel) make.top.equalTo(titleLabel.snp.bottom).offset(6) make.right.equalTo(self.contentView) make.height.equalTo(18) } splitView.snp.makeConstraints { (make) in make.left.equalTo(self.contentView) make.height.equalTo(10) make.right.equalTo(self.contentView) make.bottom.equalTo(self) } collectionView.snp.makeConstraints { (make) in make.left.equalTo(self.contentView) make.top.equalTo(detailTitleLabel.snp.bottom).offset(15) make.right.equalTo(self.contentView) make.bottom.equalTo(splitView.snp.top) } } fileprivate func updateUI() { titleLabel.text = live_Nodes.title detailTitleLabel.text = live_Nodes.desc collectionView.lives = live_Nodes.livesArray } }
// // otus_news_swiftuiApp.swift // otus-news-swiftui // // Created by Anna Zharkova on 09.08.2021. // import SwiftUI import SwiftUINavigator @main struct otus_news_swiftuiApp: App { var body: some Scene { WindowGroup { NavigationContainerView(transition: .custom(.opacity), content: { NewsListView() }) } } }
// // MeetUsInteractor.swift // Figueres2018 // // Created by Javier Jara on 12/7/16. // Copyright (c) 2016 Data Center Consultores. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol MeetUsInteractorInput { func doSomething(request: MeetUs.Something.Request) } protocol MeetUsInteractorOutput { func presentSomething(response: MeetUs.Something.Response) } class MeetUsInteractor: MeetUsInteractorInput { var output: MeetUsInteractorOutput! var worker: MeetUsWorker! // MARK: - Business logic func doSomething(request: MeetUs.Something.Request) { // NOTE: Create some Worker to do the work worker = MeetUsWorker() worker.doSomeWork() // NOTE: Pass the result to the Presenter let response = MeetUs.Something.Response() output.presentSomething(response: response) } }
/** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import UIKit import Parse class ViewController: UIViewController { struct Alert{ var title: String var message: String } @IBOutlet weak var loginTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signupOrLoginButton: UIButton! @IBOutlet weak var changeSignModeButton: UIButton! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var isdriver: UISwitch! @IBOutlet weak var riderLabel: UILabel! @IBOutlet weak var driverLabel: UILabel! var signUpMode: Bool = true var errorMessage = "" var activityIndicator = UIActivityIndicatorView() var currentAlert: Alert = Alert(title: "",message: "") private func ManipulatedriverSwitch(){ if signUpMode{ isdriver.isHidden = true riderLabel.isHidden = true driverLabel.isHidden = true } else{ isdriver.isHidden = false riderLabel.isHidden = false driverLabel.isHidden = false } } public func createAlert(alerting: Alert){ let alert = UIAlertController(title: alerting.title,message: alerting.message,preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in self.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } private func showLoading(){ activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray self.view.addSubview(activityIndicator) activityIndicator.startAnimating() UIApplication.shared.beginIgnoringInteractionEvents() } private func stopLoadingView(){ activityIndicator.stopAnimating() UIApplication.shared.endIgnoringInteractionEvents() } private func sigUpUser(){ let user = PFUser() user.username = loginTextField.text user.password = passwordTextField.text user["isdriver"] = isdriver.isOn user.signUpInBackground(block: { (success,error) in self.stopLoadingView() if error != nil{ var displayErrorMessage = "Please try again" let parseError = error as NSError? self.errorMessage = parseError?.userInfo["error"] as! String displayErrorMessage = self.errorMessage self.currentAlert = Alert(title: "Sign Up error", message: displayErrorMessage) self.createAlert(alerting: self.currentAlert) } else{ print("user signed up") } }) } private func loginUser(){ PFUser.logInWithUsername(inBackground: loginTextField.text!, password: passwordTextField.text!, block: { (user,error) in self.stopLoadingView() if error != nil{ var displayErrorMessage = "Please try again" let parseError = error as NSError? self.errorMessage = parseError?.userInfo["error"] as! String displayErrorMessage = self.errorMessage self.currentAlert = Alert(title: "Log in error", message: displayErrorMessage) self.createAlert(alerting: self.currentAlert) } else{ print("Logged in") if let isdriverValue = PFUser.current()?["isdriver"] as? Bool{ if isdriverValue{ self.performSegue(withIdentifier: "showdriverViewcontroller", sender: self) } else{ self.performSegue(withIdentifier: "showriderViewcontroller", sender: self) } } } }) } @IBAction func signupOrlogin(_ sender: Any) { if loginTextField.text == "" || passwordTextField.text == ""{ currentAlert = Alert(title: "Fields Missing",message: "Please try again") createAlert(alerting: currentAlert) } else{ showLoading() if signUpMode{ self.sigUpUser() } else{ self.loginUser() } } } @IBAction func chageMode(_ sender: Any) { ManipulatedriverSwitch() if signUpMode{ signupOrLoginButton.setTitle("Log in", for: []) changeSignModeButton.setTitle("Sign Up?", for: []) messageLabel.text = "Are you new?" signUpMode = false } else{ signupOrLoginButton.setTitle("Sign up", for: []) changeSignModeButton.setTitle("Log in?", for: []) messageLabel.text = "Aren`t new?" signUpMode = true } } override func viewDidAppear(_ animated: Bool) { if let isdriverValue = PFUser.current()?["isdriver"] as? Bool{ if isdriverValue{ self.performSegue(withIdentifier: "showdriverViewcontroller", sender: self) } else{ self.performSegue(withIdentifier: "showriderViewcontroller", sender: self) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print("ViewDidLoaded") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
import XCTest @testable import Flickr class PhotoListViewModelTestCase: XCTestCase { private var session: MockURLSession! private var viewModel: PhotoListViewModel! override func setUp() { super.setUp() session = MockURLSession() viewModel = PhotoListViewModel(urlSession: session) } func testIfItFetchesPhotos() { let expect = expectation(description: #function) do { // Given let mockJSONString = PhotoCollection.mockJSONString let expectedCollection: PhotoCollection = try mockJSONString.decodedObject() session.requestInterceptor = { _ in return mockJSONString.data(using: .utf8) } // When viewModel.loadMore { error in // Then XCTAssertNil(error) XCTAssertEqual(self.viewModel.numberOfPhotos(), expectedCollection.photos.count) XCTAssertFalse(self.viewModel.hasMore) XCTAssertFalse(self.viewModel.isFetching) expect.fulfill() } } catch { XCTFail("\(error)") } waitForExpectations(timeout: 0.5) } func testIfItFetchesPhotosWithKeyowrds() { let expect = expectation(description: #function) do { // Given let keywords = ["barking", "DOG"] let mockJSONString = PhotoCollection.mockJSONString let expectedCollection: PhotoCollection = try mockJSONString.decodedObject() let expectedURL = try FlickrAPI.urlForSearch(keywords) session.requestInterceptor = { request in XCTAssertEqual(request.url, expectedURL) return mockJSONString.data(using: .utf8) } // When viewModel.setKeywords(keywords) viewModel.loadMore { error in // Then XCTAssertNil(error) XCTAssertEqual(self.viewModel.numberOfPhotos(), expectedCollection.photos.count) XCTAssertFalse(self.viewModel.hasMore) XCTAssertFalse(self.viewModel.isFetching) expect.fulfill() } } catch { XCTFail("\(error)") } waitForExpectations(timeout: 0.5) } } private extension PhotoCollection { static let mockJSONString = """ { "photos": { "page":1, "pages":1, "perpage":20, "total":"2", "photo":[ {"id":"49049991141","owner":"64588547@N00","secret":"279bba90d5","server":"65535","farm":66,"title":"untitled-8","ispublic":1,"isfriend":0,"isfamily":0}, {"id":"49049991142","owner":"64588547@N00","secret":"279bba90d5","server":"65535","farm":66,"title":"untitled-8","ispublic":1,"isfriend":0,"isfamily":0} ] }, "stat":"ok" } """ }
// // Day24MoreLinkedLists.swift // Datasnok // // Created by Vladimir Urbano on 7/21/16. // Copyright © 2016 Vladimir Urbano. All rights reserved. // class Day24MoreLinkedLists { init() { var head: Node? let linkedList = LinkedList() let t = Int(readLine()!)! for _ in 1 ... t { head = linkedList.insert(head, data: Int(readLine()!)!) } linkedList.display(linkedList.removeDuplicates(head)) } } // Start of class Node class Node { var data: Int var next: Node? init(d: Int) { data = d } } // End of class Node // Start of class LinkedList class LinkedList { func insert(head: Node?, data: Int) -> Node? { if head == nil { return Node(d: data) } head?.next = insert(head?.next, data: data) return head } func display(head: Node?) { if head != nil { print(head!.data, terminator: " ") display(head?.next) } } // Start of function removeDuplicates func removeDuplicates(head: Node?) -> Node? { if let _ = head { var q = Array<Int>() var parent = head var current = head?.next q.append(parent!.data) while current != nil { if q.contains(current!.data) { parent?.next = current?.next parent = head current = head?.next q.removeAll() q.append(parent!.data) } else { q.append(current!.data) parent = current current = current?.next } } } return head } // End of function removeDuplicates } // End of class LinkedList
// // Any+Equality.swift // // // Created by Ethan Uppal on 1/9/19. // import Foundation public func isEqual<T: Equatable>(_ lhs: Any, rhs: T) -> Bool { return (lhs as? T) == rhs }
public struct ReferencePath: Hashable { public let components: [ReferencePathComponent] public var count: Int { return self.components.count } public var description: String { return "(root)" + self.components .map { $0.description } .joined(separator: "") } public init(components: [ReferencePathComponent]) { self.components = components } public init(identifiablePath: IdentifiableReferencePath) { let hints = identifiablePath .idComponents .map { ReferencePathNormalization.Hint($0.noNormalizedComponent) } self.init(components: ReferencePathNormalization.normalize(hints: hints)) } public static let root = ReferencePath(components: []) } extension ReferencePath: Comparable { public static func <(lhs: ReferencePath, rhs: ReferencePath) -> Bool { return lhs.count < rhs.count } }
// // Credit+CoreDataClass.swift // Free Bank // // Created by Sasha Zontova on 4/6/21. // // import Foundation import CoreData public class Credit: NSManagedObject {}
// // CustomBinding.swift // project 13 // // Created by Anisha Lamichhane on 6/14/21. // import SwiftUI struct CustomBinding: View { @State private var blurAmount: CGFloat = 0 var body: some View { let blur = Binding<CGFloat>( get: { self.blurAmount }, set: { self.blurAmount = $0 print("New value is \(self.blurAmount)") } ) return VStack { Text("Hello, world!") .blur(radius: blurAmount) Slider(value: blur, in: 1...100) } } } struct CustomBinding_Previews: PreviewProvider { static var previews: some View { CustomBinding() } }
// // ParkingLot.swift // Lab3 // // Created by Jason Larsen on 9/30/15. // Copyright © 2015 Heartbit. All rights reserved. // class ParkingLot : ModelNode { init(shader: Shader) { super.init(name: "ParkingLot", shader: shader) loadTexture("ParkingLot.jpg") } }
// // SocialAppPushAnimator.swift // SocialApp // // Created by Дима Давыдов on 25.10.2020. // import UIKit class SocialAppPushAnimator: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let source = transitionContext.viewController(forKey: .from) else { return } guard let destination = transitionContext.viewController(forKey: .to) else { return } destination.view.frame = source.view.frame destination.view.setAnchorPoint(anchorPoint: CGPoint(x: 1, y: 0)) destination.view.transform = destination.view.transform.rotated(by: .pi / -2) transitionContext.containerView.addSubview(destination.view) UIView.animateKeyframes(withDuration: self.transitionDuration(using: transitionContext), delay: 0, options: .calculationModePaced, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations: { destination.view.transform = .identity }) }, completion: {(completed) in if completed && transitionContext.transitionWasCancelled { destination.view.transform = .identity } transitionContext.completeTransition(completed && !transitionContext.transitionWasCancelled) }) } }
// // QuizList.swift // QuizList // // Created by Alexander v. Below on 09.06.19. // Copyright © 2019 Alexander v. Below. All rights reserved. // import Foundation import UIKit struct QuizListElement: Equatable, Codable { var number: Int var text: String static func ==(lhs: QuizListElement, rhs: QuizListElement) -> Bool { return lhs.text == rhs.text } } struct QuizList : Codable { typealias Index = Int typealias Element = QuizListElement let items: [Element] let version: Double var winningPictures: [String]? init() { version = 2.0 items = [ Element(number: 1, text: "Surprise"), Element(number: 2, text: "Fear"), Element(number: 3, text: "Ruthless efficiency"), Element(number: 4, text: "Almost fanatical devotion to the Pope"), Element(number: 5, text: "Nice red uniforms"), ] winningPictures = [] } init?(contentsOf url: URL) { do { let data = try Data(contentsOf: url) let decoder = JSONDecoder() let list = try decoder.decode(QuizList.self, from: data) self = list } catch { return nil } } init?(firstAt url: URL) throws { let content = try FileManager.default.contentsOfDirectory( at: url, includingPropertiesForKeys: nil) if let url = content.first( where: { $0.pathExtension == Constants.FileExtenstion.rawValue }), let bundle = Bundle(url: url), let list = QuizList(contentsOf: bundle) { self = list return } else { return nil } } init?(contentsOf bundle: Bundle) { guard let dataFileUrl = bundle.url( forResource: "data", withExtension: "json") else { return nil } guard let list = QuizList(contentsOf: dataFileUrl) else { return nil } self = list if let imageURLs = bundle.urls( forResourcesWithExtension: nil, subdirectory: "images") { self.winningPictures = imageURLs.map({ url in url.absoluteString }) } } private func image(from path: String) -> UIImage? { guard let url = URL(string: path) else { return nil } do { let data = try Data(contentsOf: url) return UIImage(data: data) } catch { return nil } } var randomPicture: UIImage? { guard let picturePath = winningPictures?.randomElement() else { return nil } return self.image(from: picturePath) } var imagePaths: [URL] { guard let winningPictures = winningPictures else { return [URL]() } return winningPictures.compactMap { path in return URL(string: path) } } }
// // JoinRoomCell.swift // Seatmates // // Created by Jansen Ducusin on 4/21/21. // import UIKit class JoinRoomCell: UITableViewCell { // MARK: - Properties static let cellIdentifier = "JoinRoomCell" let roomLabel: UILabel = { let label = UILabel() label.textColor = .black label.font = .systemFont(ofSize: 14) return label }() let rssiLabel: UILabel = { let label = UILabel() label.textColor = .red label.font = .systemFont(ofSize: 14) return label }() // MARK: - Lifecycle override init(style: UITableViewCell.CellStyle, reuseIdentifier:String?){ super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Helpers private func setupUI(){ backgroundColor = .white setupStack() } private func setupStack(){ let stack = UIStackView(arrangedSubviews: [roomLabel, rssiLabel]) addSubview(stack) stack.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingLeft: 17, paddingRight: 17) } }
// // RemoteImage.swift // Appetizer // // Created by Paco Cardenal on 09/04/2021. // import SwiftUI final class ImageLoader: ObservableObject { @Published var image: Image? = nil func load(fromUrlString urlString: String) { NetworkManager.shared.downloadImage(fromUrlString: urlString) { (uiImage) in guard let uiImage = uiImage else { return } DispatchQueue.main.async { self.image = Image(uiImage: uiImage) } } } } struct RemoteImage: View { var image: Image? var body: some View { image?.resizable() ?? Image("food-placeholder").resizable() } } struct AppetizerRemoteImage: View { @StateObject var imageLoader = ImageLoader() let urlString: String var body: some View { RemoteImage(image: imageLoader.image) .onAppear { imageLoader.load(fromUrlString: urlString) } } } struct RemoteImage_Previews: PreviewProvider { static var previews: some View { RemoteImage() } }
// // SceneDelegate.swift // TODO-App // // Created by Ashis Laha on 23/05/20. // Copyright © 2020 Ashis Laha. All rights reserved. // import UIKit import TODOKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let _ = (scene as? UIWindowScene) else { return } } /// this method is getting called when we support multi-window feature func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard let windowScene = scene as? UIWindowScene, let navigationVC = windowScene.windows.first?.rootViewController as? UINavigationController, let historyVC = navigationVC.viewControllers.first as? HistoryViewController else { return } // intent if let intent = userActivity.interaction?.intent as? TODOIntent, let task = Task.createTask(from: intent) { TaskManager.shared.addTask(task: task) historyVC.showTask(task: task) } // useractivity if userActivity.activityType == Constants.UserActivity.createTaskByUserActivity { historyVC.gotoNewTaskPage() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
// // AppDelegate.swift // SweetDeal // // Created by Bharath Prabhu on 11/3/19. // import UIKit import CoreData import Firebase import GoogleSignIn @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate { var sr = StuResViewController() var window: UIWindow? var ref: DatabaseReference! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() GIDSignIn.sharedInstance().clientID = "318021857036-791l2cpodesfjkhlafejqq632vbrgol9.apps.googleusercontent.com" GIDSignIn.sharedInstance().delegate = self return true } @available(iOS 9.0, *) func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool { return GIDSignIn.sharedInstance().handle(url) } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if let error = error { if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue { print("The user has not signed in before or they have since signed out.") } else { print("\(error.localizedDescription)") } return } ref = Database.database().reference() //pulling information from Google Sign in let userID = user.userID! let idToken = user.authentication!.idToken let firstName = user.profile!.givenName! let lastName = user.profile!.familyName! let email = user.profile!.email! //Linking to the right page ref.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in //user exists already if snapshot.hasChild(userID) { //user is a student" let value = snapshot.value as? NSDictionary let content = value![userID] as? NSDictionary let type = content!["is_student"] as? NSValue if type != nil { let storyboard = UIStoryboard(name: "Main", bundle: nil) let sc = storyboard.instantiateViewController(withIdentifier: "StuMainViewController") as! StuMainViewController sc.currUserID = userID sc.currUserFN = firstName sc.currUserLN = lastName sc.currUserEmail = email self.window!.rootViewController = sc self.window!.makeKeyAndVisible() //is a res owner } else { let storyboard = UIStoryboard(name: "Main", bundle: nil) let sc = storyboard.instantiateViewController(withIdentifier: "ResMainViewController") as! ResMainViewController sc.currUserID = userID sc.currUserFN = firstName sc.currUserLN = lastName sc.currUserEmail = email let myres = content!["restaurant"] as? NSDictionary let myresobj:Restaurant if myres != nil { let resName = myres!["name"] as! NSString let resPhone = myres!["phone"] as! NSString let resImage = myres!["imageURL"] as! NSString let resID = myres!["id"] as! NSString myresobj = Restaurant(name: String(resName), phone: String(resPhone), imageURL: String(resImage), id: String(resID)) } else { let resName = "" let resPhone = "" let resImage = "" let resID = "" myresobj = Restaurant(name: String(resName), phone: String(resPhone), imageURL: String(resImage), id: String(resID)) } sc.myRes = myresobj self.window!.rootViewController = sc self.window!.makeKeyAndVisible() } //new user } else { let storyboard = UIStoryboard(name: "Main", bundle: nil) let sc = storyboard.instantiateViewController(withIdentifier: "StuResViewController") as! StuResViewController sc.currUserID = userID sc.currUserFN = firstName sc.currUserLN = lastName sc.currUserEmail = email self.window!.rootViewController = sc self.window!.makeKeyAndVisible() // Add new signed-in user to database self.ref.child("Users").child(userID).setValue(["idToken": idToken, "firstName": firstName, "lastName": lastName, "email": email]) } }) } func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) { // Perform any operations when the user disconnects from app here. } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "SweetDeal") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
// // IntermediateConsumptionNode.swift // EFI // // Created by LUIS ENRIQUE MEDINA GALVAN on 7/24/18. // Copyright © 2018 LUIS ENRIQUE MEDINA GALVAN. All rights reserved. // import Foundation import AsyncDisplayKit class IntermediateConsumptionNode:CCTNode { let kwTextNode:CTTTextNode! let titleTextNode:CTTTextNode! override init() { kwTextNode = CTTTextNode(withFontSize: 30, color: UIColor.lightGray, with: "82,263") titleTextNode = CTTTextNode(withFontSize: 15, color: UIColor.black, with: "Intermedia") super.init() style.preferredSize.height = 75 } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let vertical = ASStackLayoutSpec.vertical() vertical.children = [titleTextNode,kwTextNode] vertical.justifyContent = .spaceBetween vertical.alignItems = .end let insets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) let insetsSpec = ASInsetLayoutSpec(insets: insets, child: vertical) return insetsSpec } }
// // AppDelegate.swift // MessageMyFriends // // Created by Tyler Reinecke on 3/10/19. // Copyright © 2019 Tyler Reinecke. All rights reserved. // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() return true } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in if let link = dynamiclink?.url { debugPrint("received link: \(link)") } } return userActivity.webpageURL.flatMap(handlePasswordlessSignIn)! } /*func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool { return application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: "") }*/ /*func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) { // Handle the deep link. For example, show the deep-linked content or // apply a promotional offer to the user's account. // ... handlePasswordlessSignIn(withURL: url) return true } return false }*/ func handlePasswordlessSignIn(withURL url: URL) -> Bool { let link = url.absoluteString if Auth.auth().isSignIn(withEmailLink: link) { UserDefaults.standard.set(link, forKey: "Link") Auth.auth().signIn(withEmail: UserDefaults.standard.string(forKey: "Email")!, link: link) { (result, error) in if (error == nil && result != nil) { if (Auth.auth().currentUser?.isEmailVerified)! { print("User verified") //self.userSuccess(2) } else { print("Error sigining in") } } else { print(error?.localizedDescription) } (self.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: false) self.window?.rootViewController?.children[0].performSegue(withIdentifier: "passwordless", sender: nil) } return true } return false } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
// // Results.swift // MarvelMVVM // // Created by William Alvelos on 2/8/18. // Copyright © 2018 William Alvelos. All rights reserved. // import Foundation import SwiftyJSON class Parsable { required init(_ json: JSON) { } } class HeroModel: Parsable { let id: Int let name: String let description: String let modified: String let thumbnail: ThumbnailModel let resourceURI: String let comics: CollectionModel? let series: CollectionModel? let stories: CollectionModel? let events: CollectionModel? let urls: [UrlModel] required init(_ json: JSON) { id = json["id"].intValue name = json["name"].stringValue description = json["description"].stringValue modified = json["modified"].stringValue thumbnail = ThumbnailModel(json["thumbnail"]) resourceURI = json["resourceURI"].stringValue comics = CollectionModel(json["comics"]) series = CollectionModel(json["series"]) stories = CollectionModel(json["stories"]) events = CollectionModel(json["events"]) urls = json["urls"].arrayValue.map { UrlModel($0) } super.init(json) } }
// // ProfileViewController.swift // parsetagram // // Created by Elana Tee on 3/17/16. // Copyright © 2016 Elana Tee. All rights reserved. // import UIKit import Parse import ParseUI class ProfileViewController: UIViewController, UINavigationControllerDelegate, UITableViewDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var profilePhotoView: UIImageView! @IBOutlet weak var usernameLabel: UILabel! var pickedImage: UIImage! override func viewDidLoad() { super.viewDidLoad() usernameLabel.text = PFUser.currentUser()?.username } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* @IBAction func onAddProfPic(sender: AnyObject) { let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true vc.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(vc, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // get the image captured by the UIImagePickerController let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage // do something with the images picker.dismissViewControllerAnimated(true, completion: nil) let profileNavigationController = self.storyboard?.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController profileNavigationController.pickedImage = originalImage self.navigationController!.pushViewController(profileNavigationController, animated: true) }*/ @IBAction func onLogout(sender: AnyObject) { PFUser.logOut() self.performSegueWithIdentifier("logoutSegue", sender: nil) } @IBAction func onPost(sender: AnyObject) { let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true vc.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(vc, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // get the image captured by the UIImagePickerController let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage // do something with the images picker.dismissViewControllerAnimated(true, completion: nil) let postPhotoNavigationController = self.storyboard?.instantiateViewControllerWithIdentifier("PostPhotoViewController") as! PostPhotoViewController postPhotoNavigationController.pickedImage = originalImage self.navigationController!.pushViewController(postPhotoNavigationController, animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // CohortRequestTests.swift // DuckDuckGo // // Copyright © 2017 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest import OHHTTPStubs @testable import Core class CohortRequestTests: XCTestCase { let host = AppUrls().cohort.host! var testee = CohortRequest() override func tearDown() { OHHTTPStubs.removeAllStubs() super.tearDown() } func testWhenStatus200AndValidJsonThenRequestCompletestWithCohortWithPlatformSuffix() { stub(condition: isHost(host)) { _ in return fixture(filePath: self.validJson(), status: 200, headers: nil) } let expectation = XCTestExpectation(description: "Valid json") testee.execute { (result, error) in XCTAssertNotNil(result) XCTAssertEqual(result?.version, "v77-5mi") XCTAssertNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func testWhenInvalidJsonThenRequestCompletestWithInvalidJsonError() { stub(condition: isHost(host)) { _ in return fixture(filePath: self.invalidJson(), status: 200, headers: nil) } let expectation = XCTestExpectation(description: "Invalid Json") testee.execute { (result, error) in XCTAssertNil(result) XCTAssertNotNil(error) XCTAssertEqual(error?.localizedDescription, JsonError.invalidJson.localizedDescription) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func testWhenUnexpectationedJsonThenRequestCompletestWithTypeMismatchError() { stub(condition: isHost(host)) { _ in return fixture(filePath: self.mismatchedJson(), status: 200, headers: nil) } let expectation = XCTestExpectation(description: "Type mismatch") testee.execute { (result, error) in XCTAssertNil(result) XCTAssertNotNil(error) XCTAssertEqual(error?.localizedDescription, JsonError.typeMismatch.localizedDescription) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func testWhenStatusIsLessThan200ThenRequestCompletesWithError() { stub(condition: isHost(host)) { _ in return fixture(filePath: self.validJson(), status: 199, headers: nil) } let expectation = XCTestExpectation(description: "Status code 199") testee.execute { (result, error) in XCTAssertNil(result) XCTAssertNotNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func testWhenStatusCodeIs300ThenRequestCompletestWithError() { stub(condition: isHost(host)) { _ in return fixture(filePath: self.validJson(), status: 300, headers: nil) } let expectation = XCTestExpectation(description: "Status code 300") testee.execute { (result, error) in XCTAssertNil(result) XCTAssertNotNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func testWhenStatusCodeIsGreaterThan300ThenRequestCompletestWithError() { stub(condition: isHost(host)) { _ in return fixture(filePath: self.validJson(), status: 301, headers: nil) } let expectation = XCTestExpectation(description: "Status code 301") testee.execute { (result, error) in XCTAssertNil(result) XCTAssertNotNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func validJson() -> String { return OHPathForFile("MockResponse/cohort_atb.json", type(of: self))! } func mismatchedJson() -> String { return OHPathForFile("MockResponse/unexpected.json", type(of: self))! } func invalidJson() -> String { return OHPathForFile("MockResponse/invalid.json", type(of: self))! } }
// // shiftTableDelegate.swift // Tipper_iOS // // Created by גיל אושר on 27.12.2015. // Copyright © 2015 gil osher. All rights reserved. // import UIKit class ShiftTableDelegate: NSObject, UITableViewDelegate, UITableViewDataSource { var allShifts: [Shift]!; init(shifts: [Shift]) { super.init(); allShifts = shifts; } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allShifts.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("shift_table", forIndexPath: indexPath); cell.textLabel!.text = "\(allShifts[indexPath.row].id)"; cell.backgroundColor = UIColor(netHex: 0x0288D1); cell.textLabel!.textColor = UIColor.whiteColor(); return cell; } }
// // AlbumListViewController.swift // Nike100 // // Created by Jeffrey Haley on 9/19/19. // Copyright © 2019 Jeffrey Haley. All rights reserved. // import UIKit let albumImageCache = NSCache<AnyObject, AnyObject>() class AlbumListViewController: UIViewController { enum CellId: String { case album = "AlbumTableViewCell" } var albums: [Album]? { didSet { albumListTableView.reloadData() } } let activityIndicator = UIActivityIndicatorView(style: .gray) @IBOutlet weak var albumListTableView: UITableView! { didSet { albumListTableView.register(UINib(nibName: CellId.album.rawValue, bundle: nil), forCellReuseIdentifier: CellId.album.rawValue) } } override func viewDidLoad() { super.viewDidLoad() title = "Nike 100" getAlbums() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) activityIndicator.center = self.view.center self.view.addSubview(activityIndicator) } private func getAlbums() { activityIndicator.startAnimating() AlbumSearchModel().retrieveTopAlbums { [weak self] (result: ResponseBody?, error: Error?) in DispatchQueue.main.async { if let albums = result?.feed.albums { self?.activityIndicator.stopAnimating() self?.albums = albums } else { self?.displaySimpleAlert(message: error?.localizedDescription ?? "Unexpected response") } } } } } extension AlbumListViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albums?.count ?? 0 } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let albumCell = tableView.dequeueReusableCell(withIdentifier: CellId.album.rawValue) as? AlbumTableViewCell, let album = self.albums?[indexPath.row] else { return UITableViewCell() } albumCell.configureAlbumCell(album: album) return albumCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let selectedAlbum = albums?[indexPath.row] else { return } let albumDetailVC = AlbumDetailViewController() albumDetailVC.album = selectedAlbum self.navigationController?.pushViewController(albumDetailVC, animated: true) } }
// // MapViewController.swift // Weather // // Created by Алихан on 22/06/2020. // Copyright © 2020 Nexen Origin, LLC. All rights reserved. // import Foundation import UIKit import GoogleMaps import CoreLocation import Lottie class MapViewController: UIViewController { //MARK: - Properties private var output: MapViewOutput? private var locationManager: CLLocationManager? private var currentLocation: CLLocation? private var selectedPoint: GeoPoint? private var mapView: GMSMapView? private var needFocucCurrentOnLoad = true private var headerLoadedView: UIView? private var isHeaderExpanded = false //MARK: - Constants private let headerCollapsedHeight: CGFloat = 180 private let moscowPoint = GeoPoint(latitude: 39.907500, longitude: 116.397200) //MARK: - Outlets @IBOutlet weak var headerView: UIView! @IBOutlet weak var headerPullView: UIView! @IBOutlet weak var mapContainerView: UIView! @IBOutlet weak var currentLocationButton: UIButton! @IBOutlet weak var headerContentView: UIView! @IBOutlet weak var headerViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var animationView: UIView! //MARK: - Incapsulation func set(output: MapViewOutput) { self.output = output } //MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.output?.didTriggerViewReadyEvent() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.mapView?.frame = self.mapContainerView.bounds } //MARK: - Actions @IBAction func listButtonAction(_ sender: Any) { self.output?.didPressedListButton() } @IBAction func currentLocationButtonAction(_ sender: Any) { self.focusCurrentLocation() } //MARK: - Private func configureMap() { let mapView = GMSMapView(frame: self.mapContainerView.bounds) mapView.delegate = self self.mapView = mapView self.mapContainerView.addSubview(mapView) } private func configureLocationManager() { if (CLLocationManager.locationServicesEnabled()) { locationManager = CLLocationManager() locationManager?.delegate = self locationManager?.desiredAccuracy = kCLLocationAccuracyBest locationManager?.requestAlwaysAuthorization() locationManager?.startUpdatingLocation() } self.currentLocationButton.isHidden = !CLLocationManager.locationServicesEnabled() } private func focusCurrentLocation() { let location = self.currentLocation?.coordinate ?? CLLocationCoordinate2D(latitude: self.moscowPoint.latitude, longitude: self.moscowPoint.longitude) self.focus(location: location) self.output?.didSelect(point: GeoPoint(latitude: location.latitude, longitude: location.longitude), with: "You") } private func focus(location: CLLocationCoordinate2D) { self.mapView?.animate(toLocation: location) self.mapView?.animate(toZoom: 15) self.mapView?.clear() let marker = GMSMarker() marker.position = location marker.map = self.mapView } private func configureGestures() { let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:))) swipeUp.direction = .up self.headerPullView.addGestureRecognizer(swipeUp) let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:))) swipeDown.direction = .down self.headerPullView.addGestureRecognizer(swipeDown) self.headerView.clipsToBounds = true } private func updateHeader() { self.view.bringSubviewToFront(self.headerView) let height = !self.isHeaderExpanded ? self.headerCollapsedHeight + 320 : self.headerCollapsedHeight UIView.animate(withDuration: 0.3) { self.headerViewHeightConstraint.constant = height self.view.layoutSubviews() self.headerView.layoutSubviews() } } private func configureAnimationView() { let path = Bundle.main.path(forResource: "loader", ofType: "json") ?? String.empty let animation = AnimationView(filePath: path) animation.loopMode = .loop animation.play() animation.frame = self.animationView.bounds self.animationView.addSubview(animation) } //MARK: - Objc @objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void { if gesture.direction == .up { if self.isHeaderExpanded { self.updateHeader() self.isHeaderExpanded.toggle() } } else if gesture.direction == .down { if !self.isHeaderExpanded { self.updateHeader() self.isHeaderExpanded.toggle() } } } } //MARK: - ViewInput extension MapViewController: MapViewInput { func configureView() { self.configureMap() self.configureLocationManager() self.focusCurrentLocation() self.configureGestures() self.configureAnimationView() self.output?.didSelect(point: self.moscowPoint, with: "Moscow") } func updateHeaderWith(headerView: UIViewController) { for view in self.headerContentView.subviews { view.removeFromSuperview() } self.headerLoadedView = headerView.view self.headerContentView.addSubview(headerView.view) headerView.didMove(toParent: self) } func startHeaderAnimating() { self.animationView.isHidden = false self.headerContentView.isHidden = true } func stopHeaderAnimating() { self.animationView.isHidden = true self.headerContentView.isHidden = false } } //MARK: - Location Manager extension MapViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { self.currentLocation = location if self.needFocucCurrentOnLoad { self.focusCurrentLocation() self.needFocucCurrentOnLoad = false } } } } //MARK: - GoogleMapsDelegate extension MapViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, didTapPOIWithPlaceID placeID: String, name: String, location: CLLocationCoordinate2D) { self.output?.didSelect(point: GeoPoint(latitude: location.latitude, longitude: location.longitude), with: name) self.focus(location: location) } }
import Foundation extension DateFormatter { static var theMovieDatabase: DateFormatter { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter } }
// // Player.swift // concrete-swift // // Created by Renan Kosicki on 9/30/15. // Copyright © 2015 Renan Kosicki | K-Mobi. All rights reserved. // import Foundation final class Player: ResponseObjectSerializable { var id: Int var name: String var avatarUrl: String required init?(response: NSHTTPURLResponse, representation: AnyObject) { id = representation.valueForKeyPath("id") as! Int name = representation.valueForKeyPath("name") as! String avatarUrl = representation.valueForKeyPath("avatar_url") as! String } }
// // BinaryTree.swift // TreeSwift // // Created by sunil.kumar1 on 6/24/19. // Copyright © 2019 sunil.kumar1. All rights reserved. // import UIKit class BinaryTree: NSObject { let nodeArray = [50,10,5,15,13,19,20,25,14,18,22,34,35]; var rootNode : TreeNode? var stack = [TreeNode]() var queue = [TreeNode]() func createBinaryTree() -> TreeNode? { self.rootNode = TreeNode(value: 50) self.rootNode?.leftNode = TreeNode(value: 10) self.rootNode?.rightNode = TreeNode(value: 5) self.rootNode?.leftNode?.leftNode = TreeNode(value: 15) self.rootNode?.leftNode?.rightNode = TreeNode(value: 13) self.rootNode?.rightNode?.leftNode = TreeNode(value: 19) self.rootNode?.rightNode?.rightNode = TreeNode(value: 20) self.rootNode?.leftNode?.leftNode?.leftNode = TreeNode(value: 25) self.rootNode?.leftNode?.leftNode?.rightNode = TreeNode(value: 14) self.rootNode?.leftNode?.leftNode?.rightNode?.leftNode = TreeNode(value: 34) self.rootNode?.rightNode?.rightNode?.leftNode = TreeNode(value: 18) self.rootNode?.rightNode?.rightNode?.leftNode?.rightNode = TreeNode(value: 35) self.rootNode?.rightNode?.rightNode?.rightNode = TreeNode(value: 22) return self.rootNode } func printTree() { // print("======Inorder======") // self.printInorderBinaryTree(rootNode: self.rootNode) // print("=====Iterative Inorder======") // self.printIterativeInorderBinaryTree(rootNode: self.rootNode) // print("======Preorder======") // self.printPreorderBinaryTree(rootNode: self.rootNode) // print("=====Iterative Preorder======") // self.printIterativePreorderBinaryTree(rootNode: self.rootNode) // print("======Postorder======") // self.printPostorderBinaryTree(rootNode: self.rootNode); // print("======Iterative Postorder======") // self.printIterativePostorderBinaryTree(rootNode: self.rootNode) print("======Iterative Level Order======") self.levelOrderTraversal(rootNode: self.rootNode) } func printInorderBinaryTree(rootNode: TreeNode?) { if rootNode != nil { printInorderBinaryTree(rootNode: rootNode?.leftNode) print(" ==> ", rootNode!.value) printInorderBinaryTree(rootNode: rootNode?.rightNode) } } func printPreorderBinaryTree(rootNode: TreeNode?) { if rootNode != nil { print(" ==> ", rootNode!.value) printPreorderBinaryTree(rootNode: rootNode?.leftNode) printPreorderBinaryTree(rootNode: rootNode?.rightNode) } } func printPostorderBinaryTree(rootNode: TreeNode?) { if rootNode != nil { printPostorderBinaryTree(rootNode: rootNode?.leftNode) printPostorderBinaryTree(rootNode: rootNode?.rightNode) print(" ==> ", rootNode!.value) } } func printIterativeInorderBinaryTree(rootNode: TreeNode?) { var node = rootNode while true { while node != nil { self.stack.append(node!) node = node!.leftNode } if self.stack.isEmpty { break } if let popNode = stack.last { stack.removeLast() print("==>", popNode.value) node = popNode.rightNode } } } func printIterativePreorderBinaryTree(rootNode: TreeNode?) { var node = rootNode while true { while node != nil { print("==>", node!.value) self.stack.append(node!) node = node!.leftNode } if self.stack.isEmpty { break } if let popNode = stack.last { stack.removeLast() node = popNode.rightNode } } } func printIterativePostorderBinaryTree(rootNode: TreeNode?) { var node = rootNode var rightNode : TreeNode? while true { while node != nil { self.stack.append(node!) node = node!.leftNode } if self.stack.isEmpty { break } if let popNode = stack.last { if popNode.rightNode == nil { rightNode = popNode print("==>", popNode.value) stack.removeLast() } else { if popNode.rightNode?.value == rightNode?.value { rightNode = popNode print("==>", popNode.value) stack.removeLast() } else { node = popNode.rightNode } } } } } func levelOrderTraversal(rootNode: TreeNode?){ let node = rootNode if node != nil { self.queue.append(node!) while !self.queue.isEmpty { if let dequedNode = self.queue.first { print(dequedNode.value, terminator: " ") self.queue.removeFirst() if dequedNode.leftNode != nil { self.queue.append(dequedNode.leftNode!) } if dequedNode.rightNode != nil { self.queue.append(dequedNode.rightNode!) } } } } } }
// // AppDelegate.swift // SwiftCoreDataSimpleDemo // // Created by CHENHAO on 14-6-7. // Copyright (c) 2014 CHENHAO. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // // // Override point for customization after application launch. // self.window!.backgroundColor = UIColor.whiteColor() // self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. self.cdh.saveContext() } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. self.demoFamily() self.demoMember() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.cdh.saveContext() } // #pragma mark - Core Data Helper lazy var cdstore: CoreDataStore = { let cdstore = CoreDataStore() return cdstore }() lazy var cdh: CoreDataHelper = { let cdh = CoreDataHelper() return cdh }() // #pragma mark - Demo func demoFamily(){ NSLog(" ======================== ") NSLog(" ======== Family ======== ") let newItemNames = ["Apples", "Milk", "Bread", "Cheese", "Sausages", "Butter", "Orange Juice", "Cereal", "Coffee", "Eggs", "Tomatoes", "Fish"] // add families NSLog(" ======== Insert ======== ") for newItemName in newItemNames { let newItem: Family = NSEntityDescription.insertNewObjectForEntityForName("Family", inManagedObjectContext: self.cdh.backgroundContext!) as! Family newItem.name = newItemName NSLog("Inserted New Family for \(newItemName) ") } self.cdh.saveContext(self.cdh.backgroundContext!) //fetch families NSLog(" ======== Fetch ======== ") var error: NSError? = nil var fReq: NSFetchRequest = NSFetchRequest(entityName: "Family") fReq.predicate = NSPredicate(format:"name CONTAINS 'B' ") let sorter: NSSortDescriptor = NSSortDescriptor(key: "name" , ascending: false) fReq.sortDescriptors = [sorter] fReq.returnsObjectsAsFaults = false var result: [AnyObject]? do { result = try self.cdh.managedObjectContext.executeFetchRequest(fReq) } catch let nserror1 as NSError{ error = nserror1 result = nil } for resultItem in result! { let familyItem = resultItem as! Family NSLog("Fetched Family for \(familyItem.name) ") } //delete families NSLog(" ======== Delete ======== ") fReq = NSFetchRequest(entityName: "Family") do { result = try self.cdh.backgroundContext!.executeFetchRequest(fReq) } catch let nserror1 as NSError{ error = nserror1 result = nil } for resultItem in result! { let familyItem = resultItem as! Family NSLog("Deleted Family for \(familyItem.name) ") self.cdh.backgroundContext!.deleteObject(familyItem) } self.cdh.saveContext(self.cdh.backgroundContext!) NSLog(" ======== Check Delete ======== ") do { result = try self.cdh.managedObjectContext.executeFetchRequest(fReq) } catch let nserror1 as NSError{ error = nserror1 result = nil } if result!.isEmpty { NSLog("Deleted All Families") } else{ for resultItem in result! { let familyItem = resultItem as! Family NSLog("Fetched Error Family for \(familyItem.name) ") } } } func demoMember(){ NSLog(" ======================== ") NSLog(" ======== Member ======== ") let family: Family = NSEntityDescription.insertNewObjectForEntityForName("Family", inManagedObjectContext: self.cdh.backgroundContext!) as! Family family.name = "Fruits" // add Members let newItemNames = ["Apples", "Milk", "Bread", "Cheese", "Sausages", "Butter", "Orange Juice", "Cereal", "Coffee", "Eggs", "Tomatoes", "Fish"] NSLog(" ======== Insert Member with family attribute ======== ") var error: NSError? = nil for newItemName in newItemNames { let newItem: Member = NSEntityDescription.insertNewObjectForEntityForName("Member", inManagedObjectContext: self.cdh.backgroundContext!) as! Member newItem.name = newItemName newItem.family = family NSLog("Inserted New Member for \(family.name) , \(newItem.name) ") } self.cdh.saveContext(self.cdh.backgroundContext!) //fetch Member NSLog(" ======== Fetch Members ======== ") var fReq: NSFetchRequest = NSFetchRequest(entityName: "Member") fReq.predicate = NSPredicate(format:"name CONTAINS 'B' ") let sorter: NSSortDescriptor = NSSortDescriptor(key: "name" , ascending: false) fReq.sortDescriptors = [sorter] var result: [AnyObject]? do { result = try self.cdh.managedObjectContext.executeFetchRequest(fReq) } catch let nserror1 as NSError{ error = nserror1 result = nil } for resultItem in result! { let memberItem = resultItem as! Member NSLog("Fetched Member for \(memberItem.family.name) , \(memberItem.name) ") } NSLog(" ======== Fetch Family and all Members can be found======== ") fReq = NSFetchRequest(entityName: "Family") fReq.predicate = NSPredicate(format:"name == 'Fruits' ") do { result = try self.cdh.managedObjectContext.executeFetchRequest(fReq) } catch let nserror1 as NSError{ error = nserror1 result = nil } for resultItem in result! { let familyItem = resultItem as! Family NSLog("Fetched Family for \(familyItem.name) ") for memberItem in familyItem.members { NSLog("Fetched Family Member for \(memberItem.name) ") } } //delete family NSLog(" ======== Delete Family with cascade delete Members ======== ") let familyItem = result![0] as! Family self.cdh.managedObjectContext.deleteObject(familyItem) self.cdh.saveContext(self.cdh.managedObjectContext) NSLog(" ======== Confirm Members Deleted======== ") fReq = NSFetchRequest(entityName: "Member") do { result = try self.cdh.backgroundContext!.executeFetchRequest(fReq) } catch let nserror1 as NSError{ error = nserror1 result = nil } if result!.isEmpty { NSLog("Delete Successed") } else{ for resultItem in result! { let memberItem = resultItem as! Member NSLog("Delete Failed, \(memberItem.name)") } } } }
// // Bird.swift // Birds // // Created by yaron mordechai on 06/04/2020. // Copyright © 2020 yaron mordechai. All rights reserved. // import SpriteKit // Bird Type retuen string of the name cases enum BirdType: String{ case red,blue,yellow,gray } //Bird - create SKSpriteNode object with color, size and texture class Bird: SKSpriteNode { let birdType : BirdType var flying = false{ didSet{ if flying{ physicsBody?.isDynamic = true animateFlight(active: true) } else{ animateFlight(active: false) } } } let flyingFrames : [SKTexture] var grabbed = false init(type:BirdType){ self.birdType = type flyingFrames = AnamationHelper.loadTexture(from: SKTextureAtlas(named: type.rawValue), withName: type.rawValue) let texture = SKTexture(imageNamed: type.rawValue + "1") super.init(texture:texture, color: UIColor.clear, size: texture.size()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func animateFlight(active:Bool){ if active{ run(SKAction.repeatForever(SKAction.animate(with: flyingFrames, timePerFrame: 0.1, resize: true, restore: true))) } else{ removeAllActions() } } } //extension Bird
// // EditVC.swift // government_park // // Created by YiGan on 19/09/2017. // Copyright © 2017 YiGan. All rights reserved. // import UIKit import gov_sdk class EditVC: UIViewController { @IBOutlet weak var topView: UIView! @IBOutlet weak var requireLabel: UILabel! @IBOutlet weak var optionLabel: UILabel! @IBOutlet weak var infoLabel: UILabel! @IBOutlet weak var applyButton: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint! var isRootEdit = true var policyId = 0 var policy: Policy? //政策详情 var applyId = 0 var apply: Apply? //申请目录内容 var item: Item? //组或组件内容 var componentId: Int? //组件id var groupId: Int? //组id var instanceId: Int? //条目id //MARK:- init------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() config() } override func viewWillAppear(_ animated: Bool) { createContents() } private func config(){ infoLabel.font = .small infoLabel.textColor = .gray applyButton.isHidden = true topView.layer.cornerRadius = .cornerRadius } fileprivate func createContents() { if isRootEdit{ topView.isHidden = false //tableView.frame = CGRect(x: 0, y: 144, width: view_size.width, height: view_size.height - 116) tableViewTopConstraint.constant = .edge8 //如果apply的编辑数据为空则通过applyId重新拉取 NetworkHandler.share().status.getApply(withApplyId: applyId, closure: { (resultCode, message, apply) in DispatchQueue.main.async { guard resultCode == .success else{ self.notif(withTitle: message, closure: nil) return } self.apply = apply //设置topView字段 self.requireLabel.text = apply?.statusHint self.optionLabel.text = apply?.dateHint if let apl = apply{ if apl.finished == 100{ self.applyButton.layer.cornerRadius = .cornerRadius self.applyButton.isHidden = false self.infoLabel.text = "必填项目已完成,请在核实资料无误、全面后,正式将申请提交给政府。" }else{ self.applyButton.isHidden = true self.infoLabel.text = "" } } //刷新 self.tableView.reloadData() } }) //如果policy为空则通过policyId重新拉取 if policy == nil{ NetworkHandler.share().policy.getPolicy(withPolicyId: policyId, closure: { (resultCode, message, policy) in DispatchQueue.main.async { guard resultCode == .success else{ self.notif(withTitle: message, closure: nil) return } self.policy = policy } }) } }else{ topView.isHidden = true //tableView.frame = CGRect(x: 0, y: 0, width: view_size.width, height: view_size.height) tableViewTopConstraint.constant = -116 - .edge8 //清空右侧按钮 navigationItem.rightBarButtonItems = [] //刷新获取组结构 let itemsParams = ItemsParams() itemsParams.applyId = applyId itemsParams.componentId = componentId! itemsParams.groupId = groupId itemsParams.instanceId = instanceId itemsParams.isInstance = instanceId == nil ? false : instanceId != 0 //判断是否为条目 NetworkHandler.share().editor.getItems(withParams: itemsParams, closure: { (resultCode, message, item) in DispatchQueue.main.async { guard resultCode == .success else{ self.notif(withTitle: message, closure: nil) return } if let itm = item{ self.item = itm self.componentId = itm.isRoot ? itm.id : itm.componentId self.instanceId = itm.instanceId if itm.isGroup{ self.groupId = itm.id } } self.tableView.reloadData() } }) } } //MARK:- 提交申请 @IBAction func apply(_ sender: Any) { NetworkHandler.share().rootEditor.submitApply(withApplyId: applyId) { (resultCode, message, data) in DispatchQueue.main.async { self.notif(withTitle: message, closure: nil) guard resultCode == .success else{ return } self.navigationController?.popViewController(animated: true) } } } //MARK:- 查看政策 @IBAction func checkPolicy(_ sender: Any) { if let policyCheckVC = storyboard?.instantiateViewController(withIdentifier: "policycheck") as? PolicyCheckVC{ policyCheckVC.policy = policy navigationController?.show(policyCheckVC, sender: nil) } } //MARK:- 其他操作 @IBAction func more(_ sender: Any) { let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "关闭", destructiveButtonTitle: "取消这个申请", otherButtonTitles: "登陆网页版") actionSheet.show(in: view) actionSheet.show(from: CGRect(x:0, y:12, width: 123, height: 323), in: view, animated: true) } //MARK: 点击header回调(用于展开与收起一级目录) @objc fileprivate func clickHeader(tap: UITapGestureRecognizer){ guard let header = tap.view else{ return } let tag = header.tag } } //MARK:- action sheet delegate extension EditVC: UIActionSheetDelegate{ func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) { switch buttonIndex { case 0: //取消这个申请 guard let apl = apply else { return } NetworkHandler.share().rootEditor.cancelApply(withApplyId: apl.id, closure: { (resultCode, message, data) in DispatchQueue.main.async { guard resultCode == .success else{ self.notif(withTitle: message, duration: 2, closure: nil) return } self.navigationController?.popViewController(animated: true) } }) case 1: print("关闭") case 2: print("登陆网页版") let scanVC = UIStoryboard(name: "Contents", bundle: Bundle.main).instantiateViewController(withIdentifier: "scan") as! ScanVC navigationController?.show(scanVC, sender: nil) default: print("other") } } } //MARK:- tableview delegate extension EditVC: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { if isRootEdit{ if let catalogList = apply?.catalogList{ return catalogList.count } return 0 } return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isRootEdit{ if let catalogList = apply?.catalogList{ let catalog = catalogList[section] let itemList = catalog.baseItemList return itemList.count } return 0 } if let baseItemList = item?.baseItemList{ return baseItemList.count } return 0 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return isRootEdit ? .labelHeight * 2 + .edge8 * 3 : 1 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerFrame = CGRect(x: 0, y: 0, width: view_size.width, height: .labelHeight * 2 + 8 * 3) let header = UIView(frame: headerFrame) header.tag = section if isRootEdit { let catalogList = apply?.catalogList let catalog = catalogList?[section] let title = catalog?.title let titleFrame = CGRect(x: .edge16, y: .edge8, width: headerFrame.width - .edge16 * 2, height: .labelHeight) let titleLabel = UILabel(frame: titleFrame) titleLabel.text = title titleLabel.font = .middle header.addSubview(titleLabel) let subTitleFrame = CGRect(x: .edge16, y: .edge8 * 2 + .labelHeight, width: headerFrame.width - .edge16, height: .labelHeight) let subTitleLabel = UILabel(frame: subTitleFrame) subTitleLabel.text = catalog?.detailTitle //"---" subTitleLabel.font = .small header.addSubview(subTitleLabel) //添加点击事件(在第一级页面有张开收起功能) let tap = UITapGestureRecognizer(target: self, action: #selector(clickHeader(tap:))) tap.numberOfTouchesRequired = 1 tap.numberOfTapsRequired = 1 header.addGestureRecognizer(tap) } return header } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if isRootEdit{ return ItemType.GroupType.normal.height() } if let baseItemList = item?.baseItemList{ let baseItem = baseItemList[indexPath.row] if baseItem.isGroup{ let base = (baseItem as? BaseItem)! let groupType = base.groupType //创建group cell switch groupType!{ case .multi: //添加条目按钮 return (baseItem.groupType?.height() ?? .cellHeight) + CGFloat(base.valueList.count) * (.buttonHeight + .edge8) // case .image: // let maxValueCount = base.maxValueCount // let curCount = base.valueList.count // let originHeight = baseItem.groupType?.height() ?? .cellHeight // let addHeight = CGFloat(ceil(Double(curCount) / Double(maxValueCount / 2))) // return originHeight + addHeight default: return baseItem.groupType?.height() ?? .cellHeight } } if let text = baseItem.hint{ //子标签内容 let size = CGSize(width: view_size.width, height: view_size.width) let rect = NSString(string: text).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont(name: UIFont.mainName, size: .labelHeight)!], context: nil) return .edge8 + .labelHeight + .edge8 + rect.height + .edge8 } return baseItem.fieldType?.height() ?? .cellHeight } return .cellHeight } //MARK: 点击组(按钮事件)回调 func clickGroup(withInstanceId instanceId: Int?, withComponentId componentId: Int, withGroupId groupId: Int?){ let groupEditor = UIStoryboard(name: "Edit", bundle: Bundle.main).instantiateViewController(withIdentifier: "edit") as! EditVC groupEditor.isRootEdit = false //获取组结构 let itemsParams = ItemsParams() itemsParams.applyId = applyId itemsParams.componentId = componentId itemsParams.groupId = groupId itemsParams.instanceId = instanceId itemsParams.isInstance = instanceId == nil ? false : instanceId != 0 //判断是否为条目 NetworkHandler.share().editor.getItems(withParams: itemsParams, closure: { (resultCode, message, item) in DispatchQueue.main.async { guard resultCode == .success else{ self.notif(withTitle: message, closure: nil) return } if let itm = item{ //groupEditor.item = itm groupEditor.componentId = itm.isRoot ? itm.id : itm.componentId groupEditor.instanceId = itm.instanceId groupEditor.applyId = self.applyId groupEditor.policyId = self.policyId if itm.isGroup{ groupEditor.groupId = itm.id } groupEditor.navigationItem.title = itm.title self.navigationController?.show(groupEditor, sender: nil) } } }) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = indexPath.section let row = indexPath.row var cell: UITableViewCell //获取具体数据(组)(字段) var base: BaseItem if isRootEdit{ let catalog = (apply?.catalogList)?[section] base = ((catalog?.baseItemList)?[row])! //如果为rootItem则必然为group let type = base.groupType! //创建group cell (组件为普通组,无需判断) let groupCell = tableView.dequeueReusableCell(withIdentifier: type.identifier()) as! Group0Cell groupCell.firstLabel.text = base.title if groupCell.secondLabel != nil{ groupCell.secondLabel.text = base.hint } groupCell.hintLabel.text = base.hint groupCell.closure = { instanceId in self.clickGroup(withInstanceId: instanceId == 0 ? self.instanceId : instanceId, withComponentId: self.apply!.catalogList[section].baseItemList[row].id, withGroupId: nil) } cell = groupCell }else{ let baseItem = ((item?.baseItemList)?[row])! base = (baseItem as? BaseItem)! if base.isGroup{ let groupType = base.groupType //创建group cell switch groupType!{ case .normal: //done let groupCell = tableView.dequeueReusableCell(withIdentifier: groupType!.identifier()) as! GroupCell groupCell.firstLabel.text = base.title if groupCell.secondLabel != nil{ groupCell.secondLabel.text = base.hint } if groupCell.hintLabel != nil{ groupCell.hintLabel.text = base.hint } groupCell.closure = { instanceId in self.clickGroup(withInstanceId: self.instanceId, withComponentId: self.componentId!, withGroupId: base.id) } cell = groupCell case .multi: //done let group2Cell = tableView.dequeueReusableCell(withIdentifier: groupType!.identifier()) as! Group2Cell group2Cell.firstLabel.text = base.title group2Cell.hintLabel.text = base.hint group2Cell.firstButton.tag = 0 //add按钮 group2Cell.firstButton.layer.cornerRadius = .cornerRadius //添加条目按钮 if !group2Cell.addedInstanceButtons{ group2Cell.addedInstanceButtons = true let x = CGFloat.edge16 + .edge8 var y = group2Cell.secondLabel.frame.origin.y let width = group2Cell.frame.width - x - .edge8 let height = CGFloat.buttonHeight for value in base.valueList{ y += (.buttonHeight + .edge8) let subviews = group2Cell.contentView.subviews let oldTagList = subviews.map({$0.tag}) if oldTagList.contains(value.id){ if let oldView = subviews.filter({$0.tag == value.id}).first{ if let oldButton = oldView as? UIButton{ oldButton.setTitle(value.title, for: .normal) } } }else{ let buttonFrame = CGRect(x: x, y: y, width: width, height: height) let button = UIButton(type: .custom) button.frame = buttonFrame button.layer.cornerRadius = .cornerRadius button.backgroundColor = .gray button.setTitle(value.title, for: .normal) button.tag = value.id button.addTarget(group2Cell, action: #selector(group2Cell.click(_:)), for: .touchUpInside) group2Cell.addSubview(button) } } } group2Cell.closure = { instanceId in if instanceId == 0{ //新建条目 guard let text = group2Cell.instanceTextfield.text else{ self.notif(withTitle: "条目名不能为空", closure: nil) return } let addInstanceParams = AddInstanceParams() addInstanceParams.applyId = self.applyId addInstanceParams.componentId = self.componentId! addInstanceParams.groupId = base.id addInstanceParams.instanceId = self.instanceId addInstanceParams.instanceTitle = text NetworkHandler.share().editor.addInstance(withAddInstanceParams: addInstanceParams, closure: { (resultCode, message, newInstance) in DispatchQueue.main.async { self.notif(withTitle: message, closure: nil) guard resultCode == .success else{ return } group2Cell.addedInstanceButtons = false self.createContents() } }) }else{ //获取条目内容 self.clickGroup(withInstanceId: instanceId == 0 ? self.instanceId : instanceId, withComponentId: self.componentId!, withGroupId: base.id) } } cell = group2Cell case .image: //done let group3Cell = tableView.dequeueReusableCell(withIdentifier: groupType!.identifier()) as! Group3Cell group3Cell.firstLabel.text = base.title let maxValueCount = base.maxValueCount //group3Cell.secondLabel.text = "限\(maxValueCount)张" if group3Cell.hintLabel != nil{ group3Cell.hintLabel.text = "限\(maxValueCount)张" } let curCount = base.valueList.count //创建图片列表 for (index, value) in base.valueList.enumerated(){ let subviews = group3Cell.imagesView.subviews let oldTagList = subviews.map({$0.tag}) if oldTagList.contains(value.id){ if let oldView = subviews.filter({$0.tag == value.id}).first{ if let oldImageView = oldView as? UIImageView{ if let imageStr = value.title{ if let imageURL = URL(string: imageStr){ DispatchQueue.global().async { if let imageData = try? Data(contentsOf: imageURL){ let image = UIImage(data: imageData) DispatchQueue.main.async { oldImageView.image = image } } } } } } } }else{ let x = CGFloat.edge8 + CGFloat(index) * ((group3Cell.frame.width - .imageHeight - .edge8 * 2) / CGFloat(curCount)) let y = CGFloat.edge8// + CGFloat(index / Int(maxValueCount / 2)) * (.imageHeight + .edge8) let width = CGFloat.imageHeight let imageFrame = CGRect(x: x , y: y, width: width, height: width) let imageView = UIImageView(frame: imageFrame) imageView.tag = value.id imageView.contentMode = .scaleToFill if let imageStr = value.title{ if let imageURL = URL(string: imageStr){ DispatchQueue.global().async { do{ if let imageData = try? Data(contentsOf: imageURL){ let image = UIImage(data: imageData) DispatchQueue.main.async { imageView.image = image } } }catch let error{ print("load image error: \(error)") } } } } //为单个图片添加点击事件 let tap = UITapGestureRecognizer(target: group3Cell, action: #selector(group3Cell.tap(_:))) tap.numberOfTapsRequired = 1 tap.numberOfTouchesRequired = 1 imageView.isUserInteractionEnabled = true imageView.addGestureRecognizer(tap) group3Cell.imagesView?.addSubview(imageView) } } group3Cell.closure = { imageViewTag in let group3Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: "group3") as! Group3Editor group3Editor.maxCount = maxValueCount group3Editor.instanceId = base.instanceId group3Editor.applyId = self.applyId group3Editor.componentId = self.componentId! group3Editor.groupId = base.id group3Editor.valueList = base.valueList group3Editor.navigationItem.title = base.title self.navigationController?.show(group3Editor, sender: nil) } cell = group3Cell case .time: //done let groupCell = tableView.dequeueReusableCell(withIdentifier: groupType!.identifier()) as! GroupCell groupCell.firstLabel.text = base.title if groupCell.secondLabel != nil{ groupCell.secondLabel.text = base.hint ?? "" } groupCell.hintLabel.text = base.hint let valueList = base.valueList groupCell.firstButton.isHidden = true groupCell.secondButton.isHidden = true for (index, value) in valueList.enumerated(){ if index == 0{ groupCell.firstButton.isHidden = false groupCell.firstButton.setTitle(value.title, for: .normal) groupCell.firstButton.tag = value.id }else{ groupCell.secondButton.isHidden = false groupCell.secondButton.setTitle(value.title, for: .normal) groupCell.secondButton.tag = value.id } } groupCell.closure = { instanceId in self.clickGroup(withInstanceId: instanceId, withComponentId: self.componentId!, withGroupId: base.id) } cell = groupCell default: //timepoint done let groupCell = tableView.dequeueReusableCell(withIdentifier: groupType!.identifier()) as! GroupCell groupCell.firstLabel.text = base.title groupCell.hintLabel.text = base.hint for (index, value) in base.valueList.enumerated(){ if index == 0{ groupCell.firstButton.tag = value.id groupCell.firstButton.setTitle(value.title, for: .normal) }else{ groupCell.secondButton.tag = value.id groupCell.secondButton.setTitle(value.title, for: .normal) } } groupCell.closure = { instanceId in self.clickGroup(withInstanceId: instanceId == 0 ? self.instanceId : instanceId, withComponentId: self.componentId!, withGroupId: base.id) } //设置文字颜色 if let baseStatus = base.status{ switch baseStatus{ case .finished: groupCell.hintLabel.textColor = UIColor(colorHex: 0xa8fe82) case .unfinished: groupCell.hintLabel.textColor = UIColor(colorHex: 0xfda8a8) case .each: groupCell.hintLabel.textColor = .gray } } cell = groupCell } }else{ let fieldType = base.fieldType //创建 field cell let assemblyCell = tableView.dequeueReusableCell(withIdentifier: fieldType!.identifier()) as! FieldCell assemblyCell.firstLabel.text = base.title assemblyCell.secondLabel.text = base.hint assemblyCell.secondLabel.sizeToFit() //设置文字颜色 if let baseStatus = base.status{ switch baseStatus{ case .finished: assemblyCell.secondLabel.textColor = UIColor(colorHex: 0xa8fe82) case .unfinished: assemblyCell.secondLabel.textColor = UIColor(colorHex: 0xfda8a8) case .each: assemblyCell.secondLabel.textColor = UIColor(colorHex: 0xe8e8de) } } cell = assemblyCell cell.sizeToFit() } } //通过颜色区分完成度 // if let baseStatus = base.status{ // switch baseStatus{ // case .finished: // cell.backgroundColor = UIColor(colorHex: 0xa8fe82) // case .unfinished: // cell.backgroundColor = UIColor(colorHex: 0xfda8a8) // case .each: // cell.backgroundColor = UIColor(colorHex: 0xe8e8de) // } // } return cell } //MARK: 点击选择,仅判断字段实例 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = indexPath.row let cell = tableView.cellForRow(at: indexPath) cell?.setSelected(false, animated: true) if isRootEdit{ }else{ let baseItem = (item?.baseItemList)?[row] let base = baseItem as! BaseItem let fieldType = base.fieldType guard !base.isGroup else{ return } /* case .enclosure: return "field3" case .single: return "field4" case .multi: return "field6" case .time: return "field7" default: return "field5" */ switch fieldType! { case .short: //短文本done let field0Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: fieldType!.identifier()) as! Field0Editor field0Editor.applyId = applyId field0Editor.componentId = componentId! field0Editor.instanceId = instanceId field0Editor.fieldId = base.id field0Editor.navigationItem.title = base.title field0Editor.prefix = base.prefix field0Editor.suffix = base.suffix field0Editor.maxLength = base.maxLength field0Editor.maxValue = base.maxValue navigationController?.show(field0Editor, sender: nil) case .long: //长文本done let field1Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: fieldType!.identifier()) as! Field1Editor field1Editor.applyId = applyId field1Editor.componentId = componentId! field1Editor.instanceId = instanceId field1Editor.fieldId = base.id field1Editor.navigationItem.title = base.title field1Editor.fieldTypeValue = base.fieldTypeValue field1Editor.text = base.hint field1Editor.maxLength = base.maxLength navigationController?.show(field1Editor, sender: nil) case .image: //图片 let field2Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: fieldType!.identifier()) as! Field2Editor field2Editor.applyId = applyId field2Editor.componentId = componentId! field2Editor.instanceId = instanceId field2Editor.fieldId = base.id field2Editor.navigationItem.title = base.title navigationController?.show(field2Editor, sender: nil) case .enclosure: //附件 let field3Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: fieldType!.identifier()) as! Field3Editor field3Editor.applyId = applyId field3Editor.componentId = componentId! field3Editor.instanceId = instanceId field3Editor.fieldId = base.id field3Editor.navigationItem.title = base.title navigationController?.show(field3Editor, sender: nil) case .single: //单选done let field4Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: fieldType!.identifier()) as! Field4Editor field4Editor.applyId = applyId field4Editor.componentId = componentId! field4Editor.instanceId = instanceId field4Editor.fieldId = base.id field4Editor.fieldTypeValue = base.fieldTypeValue field4Editor.navigationItem.title = base.title navigationController?.show(field4Editor, sender: nil) case .multi: //多选done let field6Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: fieldType!.identifier()) as! Field6Editor field6Editor.applyId = applyId field6Editor.componentId = componentId! field6Editor.instanceId = instanceId field6Editor.fieldId = base.id field6Editor.fieldTypeValue = base.fieldTypeValue if field6Editor.fieldTypeValue == 9390{ field6Editor.policyId = policyId } field6Editor.valueList = base.valueList field6Editor.navigationItem.title = base.title navigationController?.show(field6Editor, sender: nil) case .time: //时间done let field7Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: fieldType!.identifier()) as! Field7Editor field7Editor.applyId = applyId field7Editor.componentId = componentId! field7Editor.instanceId = instanceId field7Editor.fieldId = base.id field7Editor.fieldTypeValue = base.fieldTypeValue field7Editor.navigationItem.title = base.title navigationController?.show(field7Editor, sender: nil) default: //联动done let field5Editor = UIStoryboard(name: "Editor", bundle: Bundle.main).instantiateViewController(withIdentifier: fieldType!.identifier()) as! Field5Editor field5Editor.applyId = applyId field5Editor.componentId = componentId! field5Editor.instanceId = instanceId field5Editor.fieldId = base.id field5Editor.fieldTypeValue = base.fieldTypeValue field5Editor.navigationItem.title = base.title navigationController?.show(field5Editor, sender: nil) } } } }
import Foundation // via http://useyourloaf.com/blog/updating-strings-for-swift-3/ let message = String(repeating: "hello!", count: 10) let hello = "こんにちは" hello.characters hello.unicodeScalars hello.utf16 hello.utf8 message[message.startIndex] message[message.index(after: message.startIndex)] message[message.index(before: message.endIndex)] message[message.index(message.startIndex, offsetBy: 1)] message[message.index(message.endIndex, offsetBy: -2)] hello.index(hello.startIndex, offsetBy: 0, limitedBy: hello.endIndex) hello.index(hello.startIndex, offsetBy: 4, limitedBy: hello.endIndex) hello.index(hello.startIndex, offsetBy: 5, limitedBy: hello.endIndex) hello.index(hello.startIndex, offsetBy: 6, limitedBy: hello.endIndex) hello.characters.index(of: "に") message.characters.index(of: "o") if let indexOfChi = hello.characters.index(of: "ち") { hello.distance(from: hello.startIndex, to: indexOfChi) }
// // IGOps.swift // SocialMaxx // // Created by bill donner on 1/18/16. // Copyright © 2016 SocialMax. All rights reserved. // import Foundation struct IGOps { static func loadInstagramBackgroundData(targetID:String, completion:(status: Int, m:OU.BunchOfMedia,f:OU.BunchOfPeople)->()) throws { let startTime = NSDate() let startCount = Globals.shared.igApiCallCount // results will be built up here var oumediaBlocks:OU.BunchOfMedia = [] var oufollowerPeople:OU.BunchOfPeople = [] func phase2loadInstagramBackgroundData() { do { // catch any problems in here // 2A - get All the Media Posts try getmediaPosts(targetID, // run thru all the media posts each:{onepost in var likerPeopleForThisMediaBlock: BunchOfIGPeople = [] // 2B - get Everyone Who Liked this post try! getlikersNonUnique(targetID, //get likers for this bunch media: onepost, each:{ liker in likerPeopleForThisMediaBlock.append(liker) }) { errc in // getlikersNonUnique completed guard errc == 200 else { print("getlikersNonUnique failed \(errc)") completion(status:416,m: [], f: []) return } let tlikers : OU.BunchOfPeople = OU.convertPeopleFrom(likerPeopleForThisMediaBlock) // 2C - get Comments on this post var commentz: OU.BunchOfComments = [] try! getCommentersForMedia(targetID, mediablock:onepost, each: { commenter in commentz.append( OU.convertCommentsFrom( commenter)) }) { errc in // getlikersNonUnique completed guard errc == 200 else { print("getCommentersForMedia failed \(errc)") completion(status:426,m: [], f: []) return } // all comments in at this point, build the post we will store let reformattedPost = OU.convertPostFrom(onepost, likers: tlikers, comments:commentz) oumediaBlocks.append(reformattedPost) } // end closure for 2C }// end closure for 2B } // end closure for 2A )// getmediaPosts closure begins { err in guard err == 200 else { print ("getmediaPosts failed \(err)") completion(status:415,m: [], f: [])//, l: [], u: [], t: []) return } // sort all the new blocks by creation time and declare victory oumediaBlocks.sortInPlace { Double( $0.createdTime ) < Double( $1.createdTime ) } let since = "\(Int(NSDate().timeIntervalSinceDate(startTime)*1000.0))" let fresh = Globals.shared.igApiCallCount - startCount print ("-- \(oumediaBlocks.count) media posts finished in \(since) - \(fresh) api calls") completion(status:200,m: oumediaBlocks, f: oufollowerPeople) } }// do catch { print("Error in phase II Startup") } }// end of phase2 /// phase1 - loadInstagramBackgroundData - get followers var followerPeople : BunchOfIGPeople = [] do { try getAllFollowers(targetID,each:{ followers in followerPeople.append(followers) }){ errcode1 in guard errcode1 == 200 else { print("getAllFollowers failed \(errcode1)") completion(status:414,m: [], f: [])//, l: [], u: [], t: []) return} followerPeople.sortInPlace{ // sort by id order in case of subsequent merge ($0["id"] as! String) < ($1["id"] as! String) } oufollowerPeople = OU.convertPeopleFrom(followerPeople) let since = "\(Int(NSDate().timeIntervalSinceDate(startTime)*1000.0))" let fresh = Globals.shared.igApiCallCount - startCount let mess = ("-- \(followerPeople.count) followers finished in \(since) - \(fresh) api calls") print(mess) phase2loadInstagramBackgroundData() } }// do catch { print ("Caught eror from loadInstagram Background Data") } } static func getUserstuff (targetID:String,completion:IntPlusOptDictCompletionFunc) throws -> IGOps.Router { let request = IGOps.Router.UserInfo(targetID) try IGOps.plainCall(request.URLRequest.URL!,completion: completion) return request } static func getRelationshipstuff (targetID:String,completion:IntPlusOptDictCompletionFunc) throws -> IGOps.Router { let request = IGOps.Router.Relationship(targetID) try IGOps.plainCall(request.URLRequest.URL!,completion: completion) return request } static func getmediaPosts(targetID:String, each:BOMCompletionFunc, completion:IntCompletionFunc) throws -> IGOps.Router { let request = IGOps.Router.MediaRecent(targetID) try IGOps.paginatedCall(request.URLRequest.URL!,each: each,completion: completion) return request } static func getAllFollowers(targetID:String, each:BOPCompletionFunc, completion:IntCompletionFunc) throws -> IGOps.Router { let request = IGOps.Router.FollowedBy(targetID) try IGOps.paginatedCall(request.URLRequest.URL!,each: each,completion: completion) return request } static func getCommentersForMedia(targetID:String, mediablock:IGMediaBlock, each:BOMCompletionFunc, completion:IntCompletionFunc) throws -> IGOps.Router { let id = mediablock["id"] as? String let request = IGOps.Router.MediaComments(id!) try IGOps.paginatedCall(request.URLRequest.URL!,each: each,completion: completion) return request } static func getCommenters(targetID:String, batchsize:Int, media:BunchOfIGMedia, each: BOPCompletionFunc, completion:IntCompletionFunc) throws { let donow = min (media.count,batchsize) let inner = media[0..<donow].map{ $0 } let therest = media[donow+1..<media.count].map { $0 } var countdown = donow for s in inner { try self.getCommentersForMedia(targetID, mediablock: s,each:each) { success in countdown -= 1 if countdown == 0 { if success == 200 { try! getCommenters(targetID,batchsize: batchsize, media: therest,each: each,completion: completion) } completion(success) } }}} static func getLikersForMedia(targetID:String, mediablock:IGMediaBlock, each:BOMCompletionFunc, completion:IntCompletionFunc) throws -> IGOps.Router { let id = mediablock["id"] as? String let request = IGOps.Router.MediaLikes(id!) try IGOps.paginatedCall(request.URLRequest.URL!,each: each,completion: completion) return request } static func getlikers(targetID:String, batchsize:Int, media:BunchOfIGMedia, each: BOPCompletionFunc, completion:IntCompletionFunc) throws { let donow = min (media.count,batchsize) let inner = media[0..<donow].map{ $0 } let therest = media[donow+1..<media.count].map { $0 } var countdown = donow for s in inner { try self.getLikersForMedia(targetID, mediablock: s,each:each) { success in countdown -= 1 if countdown == 0 { if success == 200 { try! getlikers(targetID,batchsize: batchsize, media: therest,each: each,completion: completion) } completion(success) } }}} static func getlikersNonUnique(targetID:String, media:IGMediaBlock, each: BOPCompletionFunc, completion:IntCompletionFunc) throws { var countdown = 1 if countdown == 0 { completion(200) } //for s in media { // possibly too much parallelism try getLikersForMedia(targetID, mediablock: media,each:each) { success in countdown -= 1 if countdown == 0 { completion(success) } } } static func plainCall(url:NSURL, completion:IntPlusOptDictCompletionFunc) throws { try IGNetOps.nwGetJSON(url) { status, jsonObject in Globals.shared.igApiCallCount += 1 defer { } IGJSON.parseIgJSONDict(jsonObject!) { code,dict in completion(code,dict) } } } static func paginatedCall(url:NSURL, each:BOMCompletionFunc, completion:IntCompletionFunc) throws { try IGNetOps.nwGetJSON(url) { status, jsonObject in Globals.shared.igApiCallCount += 1 defer { } IGJSON.parseIgJSONIgMedia(jsonObject!) { url,resData in for every in resData { each(every) } if url != nil { let nextURL = url! // Request = NSURLRequest(URL: url!) // TODO: - put in a proper try someday try! paginatedCall(nextURL,each:each,completion:completion) } else { // no more so run completion completion(200) } } } } } // end of IGOps extension IGOps { // networking static func nwEncode(req:NSMutableURLRequest,parameters:[String:AnyObject]){ // extracted from Alamofire func escape(string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? "" } func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") } if let uRLComponents = NSURLComponents(URL: req.URL!, resolvingAgainstBaseURL: false){ let percentEncodedQuery = (uRLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) // print("percentEncodedQuery = \(percentEncodedQuery)") uRLComponents.percentEncodedQuery = percentEncodedQuery req.URL = uRLComponents.URL } // print("nwEncode returns with \(req)") return } typealias URLParamsToEncode = [String: AnyObject]? enum Router { static let baseURLString = "https://api.instagram.com" static let clientID = "cf97d864faf14f90a1557c4b972c990e" static let redirectURI = "http://www.example.com/" static let clientSecret = "7f1ce6147f924afc92dea31f5354ca06" case MediaLikes(String) case MediaComments(String) case UserInfo(String) case Relationship(String) case MediaRecent(String) case SelfMediaLiked( ) case SelfFollowing() case SelfFollowedBy() case Following(String) // deprecated by instagram ...soon case FollowedBy(String) // deprecated by instagram ... case PopularPhotos(String,String) // used by mainline for now case requestOauthCode static func getAccessTokenRequest (code:String)throws -> NSMutableURLRequest { let pathString = "/oauth/access_token" if let url = NSURL(string:IGOps.Router.baseURLString + pathString) { let params = ["client_id": Router.clientID, "client_secret": Router.clientSecret, "grant_type": "authorization_code", "redirect_uri": Router.redirectURI, "code": code] var paramString = "" for (key, value) in params { if let escapedKey = key.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()), let escapedValue = value.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()) { paramString += "\(escapedKey)=\(escapedValue)&" } } let request = NSMutableURLRequest(URL:url) request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding) return request } throw IGPersonDataErrors.Bad(arg: 402) } // if let url // let urlComponents = NSURLComponents(string:urlString)! // urlComponents.queryItems = [ // // NSURLQueryItem(name: "client_id", value: String(Router.clientID)), // // NSURLQueryItem(name: "client_secret", value: String(Router.clientSecret)), // // NSURLQueryItem(name: "grant_type", value: String("authorization_code")), // // NSURLQueryItem(name: "redirect_uri", value: String(Router.redirectURI)), // // NSURLQueryItem(name: "code", value: String(code)) // ] // // urlComponents.URL // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6 // let zz = urlComponents.percentEncodedQuery // print("-----",zz) // let surl = urlComponents.string! // shud now be percent encoded! // // let freshurl = NSURL(string:surl) // req.HTTPBody = surl.dataUsingEncoding(NSASCIIStringEncoding) // req.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") // // [request setHTTPMethod:@"POST"]; // [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; // [request setHTTPBody:[@"firID=800" dataUsingEncoding:NSUTF8StringEncoding]]; // let params = ["client_id": Router.clientID, "client_secret": Router.clientSecret, "grant_type": "authorization_code", "redirect_uri": Router.redirectURI, "code": code] // let pathString = "/oauth/access_token" // let urlString = IGOps.Router.baseURLString + pathString // let req = IGOps.encodedRequest(NSURL(string:urlString)!, params: params) // MARK: URLRequestConvertible var URLRequest: NSMutableURLRequest { let result: (path: String, parameters: URLParamsToEncode ) = { switch self { case .requestOauthCode: let pathString = "/oauth/authorize/?client_id=" + Router.clientID + "&redirect_uri=" + Router.redirectURI + "&response_type=code" return (pathString, [:]) case .PopularPhotos (let userID, let accessToken): let params = ["access_token": accessToken ] let pathString = "/v1/users/" + userID + "/media/recent" return (pathString, params) default : // these all take the access token let params = ["access_token": Globals.shared.igAccessToken ] switch self { // case .Relationship (let userID): let pathString = "/v1/users/" + userID + "/relationship" return (pathString, params) case .UserInfo (let userID): let pathString = "/v1/users/" + userID return (pathString, params) case .MediaLikes (let mediaID): let pathString = "/v1/media/" + mediaID + "/likes" return (pathString, params) case .MediaComments (let mediaID): let pathString = "/v1/media/" + mediaID + "/comments" return (pathString, params) case .MediaRecent (let userID ): let pathString = "/v1/users/" + userID + "/media/recent" return (pathString, params) case .SelfMediaLiked (): let pathString = "/v1/users/self/media/liked" return (pathString, params) case .Following (let userID ): let pathString = "/v1/users/" + userID + "/follows" return (pathString, params) case .FollowedBy (let userID ): let pathString = "/v1/users/" + userID + "/followed-by" return (pathString, params) case .SelfFollowing (): let pathString = "/v1/users/" + "self" + "/follows" return (pathString, params) case .SelfFollowedBy (): let pathString = "/v1/users/" + "self" + "/followed-by" return (pathString, params) default: return ("",nil) } } }() let baseurl = NSURL(string: Router.baseURLString)! let fullurl = baseurl.URLByAppendingPathComponent(result.path) return IGOps.encodedRequest(fullurl, params: result.parameters) } } static func encodedRequest(fullurl:NSURL, params:URLParamsToEncode?) -> NSMutableURLRequest { let parms = (params != nil) ? params! : [:] let encreq = NSMutableURLRequest(URL:fullurl) IGOps.nwEncode(encreq, parameters: parms!) return encreq } }
//Copyright (c) 2019 pikachu987 <pikachu77769@gmail.com> // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import UIKit public class CollectionViewReorder: Reorder { public weak var delegate: CollectionViewReorderDelegate? override var reorderDelegate: ReorderDelegate? { return self.delegate } public lazy var gestureRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGesture(_:))) }() public init(collectionView: UICollectionView) { super.init() self.gestureRecognizer.minimumPressDuration = self.minimumPressDuration collectionView.addGestureRecognizer(self.gestureRecognizer) self.scrollView = collectionView } override func updateIndexPath(at: IndexPath, to: IndexPath) { guard let collectionView = self.scrollView as? UICollectionView else { return } self.delegate?.collectionViewReorder(collectionView, moveItemAt: at, to: to) } override func canMove(indexPath: IndexPath) -> Bool { guard let collectionView = self.scrollView as? UICollectionView else { return true } return self.delegate?.collectionViewReorder(collectionView, canMoveItemAt: indexPath) ?? true } }
// // PPSettingsToast.swift // ProtoPipe // // Created by 吉乞悠 on 2020/7/12. // Copyright © 2020 吉乞悠. All rights reserved. // import UIKit import SnapKit class PPSettingsToast: PPToastViewController { override func viewDidLoad() { super.viewDidLoad() toastNavigationBar.title = "Settings" } }
// // ListCell.swift // MedicallYang0610 // // Created by HEE TAE YANG on 2020/06/12. // Copyright © 2020 yht. All rights reserved. // import SwiftUI struct ListCell: View { var body: some View { List { Text("약관 및 정책") Text("회사 소개") Text("자가 진단") Text("버전 정보") } } } struct ListCell_Previews: PreviewProvider { static var previews: some View { ListCell() } }
// // UniqueLink.swift // Bonfire // // Created by Keith Wang on 11/8/19. // Copyright © 2019 Bonfire. All rights reserved. // import Foundation struct UniqueLink { let scheme: String let host: String let path: String let prefix: String let myAppStoreID: String let title: String let descriptionText: String let imageURL: NSURL let promoText: String init() { self.scheme = "https" self.host = "bonfireapp.page.link" self.path = "/my" self.prefix = "https://bonfireapp.page.link" self.myAppStoreID = "1480186539" self.title = "Bonfire" self.descriptionText = "Collaborate with your tribe, improve your mental health" self.imageURL = NSURL(string: "https://imgur.com/9xOw4Tb")! self.promoText = "" } }
// // XCHangulSwiftTest.swift // HangulSwift // // Created by wookyoung on 4/3/16. // Copyright © 2016 factorcat. All rights reserved. // import XCTest class WHangulTestCase: XCTestCase { let a = JamoArea() func 초성(sound: String) -> YetJamo { return 옛초(a.compatibility_to_scalar(.초, sound: sound)!) } func 중성(sound: String) -> YetJamo { return 옛중(a.compatibility_to_scalar(.중, sound: sound)!) } func 종성(sound: String) -> YetJamo { return 옛종(a.compatibility_to_scalar(.종, sound: sound)!) } func 갈마들이(lhs: YetJamo, _ rhs: YetJamo) -> YetJamo { return YetJamo(type: .갈(lhs, rhs), scalar: 빈스칼라) } func 모음(sound: String) -> YetJamo { return YetJamo(type: .모, scalar: a.compatibility_to_scalar(.중, sound: sound)!) } func 기호(sound: String) -> YetJamo { return YetJamo(type: .Normal(string: sound), scalar: 빈스칼라) } } extension HangulInputSystem { func debug(s: String = "") { Log.info("hangul\(s)", hangul, "prevjamo", prevjamo, "last_backspace", last_backspace, "syllables", syllables) } }
// // HostDetailsViewController.swift // BikeApp // // Created by Lucas Azevedo Barruffe on 16/05/18. // Copyright © 2018 BikeApp. All rights reserved. // import UIKit class HostDetailsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet weak var profilePhoto: UIImageView! @IBOutlet weak var localPhotosCollection: UICollectionView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var ratingLabel: UILabel! @IBOutlet weak var rentLabel: UILabel! @IBOutlet weak var availableTimeLabel: UILabel! @IBOutlet weak var bikeCapacityLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var placeDescriptionLabel: UILabel! @IBOutlet weak var reviewFromOthersLabel: UILabel! var host: Hoster! let reuseIdentifier = "cell"; override func viewDidLoad() { super.viewDidLoad() if let layout = localPhotosCollection.collectionViewLayout as? UICollectionViewFlowLayout { layout.scrollDirection = .horizontal } //host = Hoster(name: "Paola Silva", email: "paola_silva@gmail.com", profilePhoto: #imageLiteral(resourceName: "detailsProfile"), description: "Um local ótimo e seguro para deixar sua bicicleta.", rating: 4.85, rentNumber: 549, horario: "08:00AM - 13:00PM", bikerEvaluations: ["Não gostei muito, achei longe.", "Lugar tri legal pra deixar sua bike.", "Tri massa!!!!", "Local muito bacana e próximo do meu trabalho."], address: "R. Cel. Fernando Machado, 1188 - Centro Histórico, Porto Alegre - RS", price: 8, localPhotos: #imageLiteral(resourceName: "detailsLivingRoom")) nameLabel.text = host.name profilePhoto.image = host.profilePhoto placeDescriptionLabel.text = host.description ratingLabel.text = String(host.rating) rentLabel.text = String(host.rentNumber) availableTimeLabel.text = host.horario reviewFromOthersLabel.text = host.bikerEvaluations.last addressLabel.text = host.address //self.localPhotosCollection.reloadSections(IndexSet(integer: 0)) } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! DetailsHostCollectionViewCell let image = host.localPhotos cell.displayContent(image: image) return cell } }
// // Card.swift // SetGame // // Created by Shimon Rothschild on 2-03-21. // import Foundation struct Card: Identifiable { var content: CardFace var isSelected: Bool = false var id: Int init(c: Int, f: Int, s: Int, q: Int, id: Int) { self.id = id content = CardFace(color: c, figure: f, shading: s, quantity: q) } }