text
stringlengths
8
1.32M
// // Shelf.swift // SkyTV // // Copyright © 2018 Mark Bourke. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE // import Foundation enum ShelfLayout: String, Codable { case carousel = "CAROUSEL" case rail = "RAIL" } enum RailTemplate: String, Codable { case background = "3COL" case poster = "5COL" case notARail = "" } struct Shelf: Node, Decodable { /// The title of the shelf. let name: String /// The shelf's id. let id: String /// The type of the shelf. let type: NodeType /// The layout of the shelf, giving information about how it should be displayed. It is not necessary to follow this layout. let layout: ShelfLayout /// The type of rail, if the shelf's layout is `rail`. let template: RailTemplate /// The items on the shelf. var items: [ShelfItem] = [] enum CodingKeys: String, CodingKey { case type = "nodetype" case name = "t" case id = "cmsid" case renderHints = "renderhints" } enum RenderHintsKeys: String, CodingKey { case layout = "layout" case template = "template" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) name = try values.decode(String.self, forKey: .name) type = try values.decode(NodeType.self, forKey: .type) if type != .heading { throw NodeError.invalidType } id = try values.decode(String.self, forKey: .id) let renderHints = try values.nestedContainer(keyedBy: RenderHintsKeys.self, forKey: .renderHints) layout = try renderHints.decode(ShelfLayout.self, forKey: .layout) template = (try? renderHints.decode(RailTemplate.self, forKey: .template)) ?? .notARail } }
// // ViewController.swift // First app // // Created by Rohit kadian on 27/05/17. // Copyright © 2017 rohit. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var thelabel: UILabel! var tap = 0 @IBAction func tap(_ sender: Any) { tap = tap + 1 if tap == 10 { thelabel.text = "10 times tapped" } if tap > 10 { thelabel.text = "keep going" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
import UIKit import SnapKit import ThemeKit import ScanQrKit class ScanQrViewController: ThemeViewController { private let delegate: IScanQrViewDelegate private let errorLabel = UILabel() private let cancelButton = ThemeButton() private let scanView = ScanQrView() init(delegate: IScanQrViewDelegate) { self.delegate = delegate super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(scanView) scanView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } scanView.delegate = self view.addSubview(errorLabel) errorLabel.snp.makeConstraints { maker in maker.leading.trailing.equalToSuperview().inset(CGFloat.margin6x) maker.centerY.equalToSuperview().dividedBy(3) } errorLabel.numberOfLines = 0 errorLabel.textAlignment = .center errorLabel.textColor = .themeLucian errorLabel.font = .subhead2 view.addSubview(cancelButton) cancelButton.snp.makeConstraints { maker in maker.leading.trailing.equalToSuperview().inset(CGFloat.margin6x) maker.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).inset(CGFloat.margin6x) maker.height.equalTo(CGFloat.heightButton) } cancelButton.apply(style: .primaryGray) cancelButton.setTitle("button.cancel".localized, for: .normal) cancelButton.addTarget(self, action: #selector(onCancel), for: .touchUpInside) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) scanView.start() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) scanView.stop() } @objc private func onCancel() { delegate.onCancel() } } extension ScanQrViewController: IScanQrView { func start() { scanView.start() } func stop() { scanView.stop() } func set(error: Error) { errorLabel.text = error.smartDescription } } extension ScanQrViewController: IScanQrCodeDelegate { func didScan(string: String) { delegate.didScan(string: string) } }
// // TweetContainerView.swift // Grasshopper // // Created by PATRICK PERINI on 8/25/15. // Copyright (c) 2015 AppCookbook. All rights reserved. // import UIKit class TweetContainerView: UIWebView { // MARK: Constants private static let embeddedTweetsContainerHTML: String = try! NSString(contentsOfFile: NSBundle.mainBundle().pathForResource("embedded_tweets_container", ofType: "html")!, encoding: NSUTF8StringEncoding) as String private static let embeddedTweetHTML: String = try! NSString(contentsOfFile: NSBundle.mainBundle().pathForResource("embedded_tweet", ofType: "html")!, encoding: NSUTF8StringEncoding) as String // MARK: Properties var tweets: [Tweet] = [] { didSet { self.reloadData() } } @IBOutlet var scrollViewDelegate: UIScrollViewDelegate? { didSet { self.scrollView.delegate = self.scrollViewDelegate } } // MARK: Lifecycle override func awakeFromNib() { super.awakeFromNib() self.reloadData() } // MARK: Data Handlers func reloadData() { var htmlStrings: [String] = [] for tweet in self.tweets { let htmlString = TweetContainerView.embeddedTweetHTML.stringByReplacingOccurrencesOfString("$TWEET_ID", withString: tweet.tweetID, options: [], range: nil) htmlStrings.append(htmlString) } let content = htmlStrings.joinWithSeparator("\n") let page = TweetContainerView.embeddedTweetsContainerHTML.stringByReplacingOccurrencesOfString("$TWEETS", withString: content, options: [], range: nil) self.loadHTMLString(page, baseURL: nil) } }
// // GameViewController.swift // Friendji // // Created by Kasra Abasi on 8/3/19. // Copyright © 2019 kasraabasi. All rights reserved. // import UIKit class GameViewController: UIViewController { // MARK: - Properties // switch between MockWebServiceNetworkController & WebServiceNetworkController private lazy var networkController = MockWebServiceNetworkController() private var stage = 0 private var emojiModel = EmojiModel(eyes: .close, eyeBrows: .normal, mouth: .neutral) { didSet { updateEmojiView() } } private let mouthCurvatures = [EmojiModel.Mouth.frown: -1.0, .neutral: 0.0, .smile: 1.0] private let eyeBrowTilts = [EmojiModel.Eyebrows.frown: -1.0, .normal: 0.0, .relax: 1.0] var game: GameViewModel? { didSet { updateUI() proceed() } } // MARK: - Outlets @IBOutlet weak var heartsLabel: UILabel! @IBOutlet weak var emojiView: EmojiView! // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() retriveGame(fileName: "stage0") } // MARK: - Actions @IBAction func submitEmojiButtonDidTapped(_ sender: Any) { // game senario from json stage files: match - not match - repeat - match - match - match stage += 1 retriveGame(fileName: "stage\(stage)") } @IBAction func eybrowSegmentedControlDidShange(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: emojiModel.eyeBrows = .normal case 1: emojiModel.eyeBrows = .relax case 2: emojiModel.eyeBrows = .frown default: break } } @IBAction func eyeSegmentedControlDidChange(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: emojiModel.eyes = .close case 1: emojiModel.eyes = .open default: break } } @IBAction func mouthSegmentedCOntrolDidChange(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: emojiModel.mouth = .neutral case 1: emojiModel.mouth = .smile case 2: emojiModel.mouth = .frown default: break } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Constant.String.SegueID.prize { if let destination = segue.destination as? PrizeViewController { if let game = game { destination.game = game } } } } } // MARK: - Private Extension private extension GameViewController { // MARK: - Methods func retriveGame(fileName: String) { networkController.retriveGame(requestBody: ["stage":fileName]) { (game, error) in if error != nil { print(error!.localizedDescription) } if let game = game { self.game = game } } } func updateUI() { if let game = game { heartsLabel.text = game.heartsString } } func updateEmojiView() { if emojiView != nil { switch emojiModel.eyes { case .open: emojiView.isEyesOpen = true case .close: emojiView.isEyesOpen = false } emojiView.mouthCurvature = mouthCurvatures[emojiModel.mouth] ?? 0.0 emojiView.eyeBrowTilt = eyeBrowTilts[emojiModel.eyeBrows] ?? 0.0 } } func proceed() { if let isMatch = game?.isMatch { if isMatch { let alert = UIAlertController(title: "Match", message: "Open your prize", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Open", style: .default, handler: { _ in self.performSegue(withIdentifier: Constant.String.SegueID.prize, sender: nil) })) self.present(alert, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Not Match", message: "You lost a heart, try again", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } if let gameResult = game?.gameResult { switch gameResult { case .gameOver: let alert = UIAlertController(title: "Game Over", message: "See you next time", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Open", style: .default, handler: { _ in self.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) default: break } } } }
// // MovieGridCell.swift // FlixsterIOs // // Created by Eleftherios Troullouris on 3/4/19. // Copyright © 2019 troullouris@hotmail.com. All rights reserved. // import UIKit class MovieGridCell: UICollectionViewCell { @IBOutlet weak var posterView: UIImageView! }
// // SignUpVC.swift // Todo List // // Created by yasser on 9/19/20. // Copyright © 2020 Yasser Aboibrahim. All rights reserved. // import UIKit import Firebase class SignUpVC: UIViewController{ // MARK:- Outlets @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var passwordLabel: UILabel! // MARK:- Properties // MARK:- Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() setTextFielsBorder() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) } // MARK:- Public Methods private func setTextFielsBorder(){ userNameTextField.setBottomBorder(borderColor: UIColor.lightGray.cgColor, backgroundColor: UIColor.clear.cgColor) emailTextField.setBottomBorder(borderColor: UIColor.lightGray.cgColor, backgroundColor: UIColor.clear.cgColor) passwordTextField.setBottomBorder(borderColor: UIColor.lightGray.cgColor, backgroundColor: UIColor.clear.cgColor) } private func isDataEntered()-> Bool{ guard userNameTextField.text != "" else{ showAlertWithCancel(alertTitle: "Incompleted Data Entry",message: "Please Enter Name",actionTitle: "Dismiss") return false } guard emailTextField.text != "" else{ showAlertWithCancel(alertTitle: "Incompleted Data Entry",message: "Please Enter email",actionTitle: "Dismiss") return false } guard passwordTextField.text != "" else{ showAlertWithCancel(alertTitle: "Incompleted Data Entry",message: "Please Enter Password",actionTitle: "Dismiss") return false } return true } private func isValidRegex() -> Bool{ guard isValidEmail(email: emailTextField.text) else{showAlertWithCancel(alertTitle: "Wrong Email Form",message: "Please Enter Valid email(a@a.com)",actionTitle: "Dismiss") return false } guard isValidPassword(testStr: passwordTextField.text) else{ showAlertWithCancel(alertTitle: "Wrong Password Form",message: "Password need to be : \n at least one uppercase \n at least one digit \n at leat one lowercase \n characters total",actionTitle: "Dismiss") return false } return true } private func gotoSignInVC(){ let signInVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: ViewControllerKeys.signInVC) as! SignInVC self.navigationController?.pushViewController(signInVC, animated: true) } private func createUser()-> Bool{ var flag = 1 Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { [weak self] authResult, error in guard self != nil else{ return } guard error == nil else { print(error!.localizedDescription) self?.showAlertWithCancel(alertTitle: "Error", message: "Account creation failed", actionTitle: "Cancel") flag = 0 return } guard let uid = authResult?.user.uid else {return} let values = [FirebaseChildrenKeys.userEmail: self!.emailTextField.text!,FirebaseChildrenKeys.userName: self!.userNameTextField.text!] Database.database().reference().child(FirebaseChildrenKeys.todoUserNote).child(uid).updateChildValues(values, withCompletionBlock: { (error,ref) in if let error = error { print("Faild to update database", error.localizedDescription) return } print("Successfully signed user up") }) } if flag == 0{ return false } return true } // MARK:- Actions @IBAction func selectedUserNameTextField(_ sender: UITextField) { userNameTextField.setBottomBorder(borderColor: UIColor.purple.cgColor, backgroundColor: UIColor.clear.cgColor) userNameLabel.text = "User Name" userNameTextField.placeholder = "" } @IBAction func unselectedUserNameTextField(_ sender: UITextField) { userNameTextField.setBottomBorder(borderColor: UIColor.lightGray.cgColor, backgroundColor: UIColor.clear.cgColor) userNameLabel.text = "" userNameTextField.placeholder = "User Name" } @IBAction func selectedEmailTextField(_ sender: UITextField) { emailTextField.setBottomBorder(borderColor: UIColor.purple.cgColor, backgroundColor: UIColor.clear.cgColor) emailLabel.text = "Email" emailTextField.placeholder = "" } @IBAction func unSelectedEmailTextField(_ sender: UITextField) { emailTextField.setBottomBorder(borderColor: UIColor.lightGray.cgColor, backgroundColor: UIColor.clear.cgColor) emailLabel.text = "" emailTextField.placeholder = "Email" } @IBAction func selectedPasswordTextField(_ sender: UITextField) { passwordTextField.setBottomBorder(borderColor: UIColor.purple.cgColor, backgroundColor: UIColor.clear.cgColor) passwordLabel.text = "Password" passwordTextField.placeholder = "" } @IBAction func unSelectedPasswordTextField(_ sender: UITextField) { passwordTextField.setBottomBorder(borderColor: UIColor.lightGray.cgColor, backgroundColor: UIColor.clear.cgColor) passwordLabel.text = "" passwordTextField.placeholder = "Password" } @IBAction func signUpBtnTapped(_ sender: UIButton) { if isDataEntered(){ if isValidRegex(){ if createUser(){ gotoSignInVC() } } } } @IBAction func signInBtnTapped(_ sender: UIButton) { gotoSignInVC() } }
import UIKit class VProjectsDetailCellSpeed:VProjectsDetailCell { weak var label:UILabel! override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true let label:UILabel = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.isUserInteractionEnabled = false label.backgroundColor = UIColor.clear label.font = UIFont.bold(size:14) label.textAlignment = NSTextAlignment.center label.numberOfLines = 0 self.label = label addSubview(label) let views:[String:UIView] = [ "label":label] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-10-[label]-10-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[label]-0-|", options:[], metrics:metrics, views:views)) } required init?(coder:NSCoder) { fatalError() } }
// // MathHelper.swift // Cardify // // Created by Vu Tiep on 2/18/15. // Copyright (c) 2015 Tiep Vu Van. All rights reserved. // import Foundation func TVVDegreesToRadians(degrees: CGFloat) -> CGFloat { return (degrees / 180.0) * CGFloat(M_PI_2); }
// // Spacer.swift // UIDebugging // // Created by Xu on 2020/11/4. // import UIKit class Spacer: UIView { private var height: CGFloat? private var width: CGFloat? convenience init(height: CGFloat? = nil , width: CGFloat? = nil) { self.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) self.height = height self.width = width } func layout() { self.snp.makeConstraints { (make) in if let height = height { make.height.equalTo(height) return } if let width = width { make.width.equalTo(width) return } make.size.equalTo(CGSize(width: 10, height: 10)) } } func setColor(_ color: UIColor)-> Self { self.backgroundColor = color return self } }
// // TrackerUtils.swift // MakerMobile // // Created by Rafael Laurine Meira on 29/06/17. // Copyright © 2017 SoftwellSolutions. All rights reserved. // import UIKit open class TrackerUtils: NSObject { open static func setAnalyticsID(_ id: String) { guard let gai = GAI.sharedInstance() else { assert(false, "Google Analytics not configured correctly") return } gai.tracker(withTrackingId: id) gai.trackUncaughtExceptions = true } open static func sendView(_ name: String) { guard let tracker = GAI.sharedInstance().defaultTracker else { return } tracker.set(kGAIScreenName, value: name) guard let builder = GAIDictionaryBuilder.createScreenView() else { return } tracker.send(builder.build() as [NSObject : AnyObject]) } open static func sendEvent(_ name: String, rule: String, component: String) { guard let tracker = GAI.sharedInstance().defaultTracker else { return } guard let event = GAIDictionaryBuilder.createEvent(withCategory: name, action: rule, label: component, value: nil) else { return } tracker.send(event.build() as [NSObject : AnyObject]) } open static func sendException(_ exception: String) { guard let tracker = GAI.sharedInstance().defaultTracker else { return } guard let event = GAIDictionaryBuilder.createException(withDescription: exception, withFatal: 1) else { return } tracker.send(event.build() as [NSObject : AnyObject]) } }
// // Splash.swift // PalmTree // // Created by SprintSols on 3/7/20. // Copyright © 2020 apple. All rights reserved. // import UIKit import NVActivityIndicatorView import CollapseTableView class CategoryVC: UIViewController, NVActivityIndicatorViewable, UITextFieldDelegate { //MARK:- Properties @IBOutlet weak var categoriesView: UIView! @IBOutlet weak var tblView: CollapseTableView! @IBOutlet weak var tblAllView: UITableView! @IBOutlet weak var txtSearch: UITextField! @IBOutlet weak var lblTitle: UILabel! //MARK:- Properties var allFilteredCategories = [CategoryJSON]() var subCatArray = [SubCategoryObject]() var filteredArray = [SubCategoryObject]() var selectedCatName = "" var selectedCat = 0 var selectedIndex = -1 var fromVC = "" //MARK:- Cycle override func viewDidLoad() { super.viewDidLoad() createCategoriesView() if categoryArray.count > 0 { setupTableView() tblView.didTapSectionHeaderView = { (sectionIndex, isOpen) in debugPrint("sectionIndex \(sectionIndex), isOpen \(isOpen)") self.txtSearch.resignFirstResponder() let adFilterListVC = self.storyboard?.instantiateViewController(withIdentifier: "AdFilterListVC") as! AdFilterListVC if sectionIndex == 0 { if self.fromVC == "filter" || self.fromVC == "adPost" { adDetailObj.adCategory = self.selectedCatName adDetailObj.catID = self.selectedCat adDetailObj.adSubCategory = "" adDetailObj.subcatID = 0 self.navigationController?.popViewController(animated: true) } else { adFilterListVC.categoryID = self.selectedCat adFilterListVC.catName = self.selectedCatName self.navigationController?.pushViewController(adFilterListVC, animated: true) } } else { let values = self.filteredArray[sectionIndex - 1] if values.hasSub == "0" { if self.fromVC == "filter" || self.fromVC == "adPost" { adDetailObj.adCategory = self.selectedCatName adDetailObj.catID = self.selectedCat adDetailObj.subcatID = values.id if languageCode == "ar" { if values.arabicName != "" { adDetailObj.adSubCategory = values.arabicName } else { adDetailObj.adSubCategory = values.name } } else { adDetailObj.adSubCategory = values.name } self.navigationController?.popViewController(animated: true) } else { adFilterListVC.categoryID = self.selectedCat adFilterListVC.catName = self.selectedCatName adFilterListVC.subcategoryID = values.id if languageCode == "ar" { if values.arabicName != "" { adFilterListVC.subcatName = values.arabicName } else { adFilterListVC.subcatName = values.name } } else { adFilterListVC.subcatName = values.name } self.navigationController?.pushViewController(adFilterListVC, animated: true) } } } } selectedCat = categoryArray[0].id if languageCode == "ar" { selectedCatName = categoryArray[0].arabicName } else { selectedCatName = categoryArray[0].name } selectedIndex = 0 if allCategories.count == 0 { getAllCategoriesAPI() } else { tblView.alpha = 0 tblAllView.alpha = 1 allFilteredCategories = allCategories } } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func setupTableView() { tblView.delegate = self tblView.dataSource = self tblView.tableFooterView = UIView(frame: .zero) tblView.register(UINib(nibName: SectionHeaderView.reuseIdentifier, bundle: nil), forHeaderFooterViewReuseIdentifier: SectionHeaderView.reuseIdentifier) } @IBAction func backBtnACtion(_ sender: Any) { self.navigationController?.popViewController(animated: true) } func createCategoriesView() { for view in categoriesView.subviews { view.removeFromSuperview() } let scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: categoriesView.frame.height) scrollView.showsHorizontalScrollIndicator = false categoriesView.addSubview(scrollView) var xAxis = 0 var width = 0 for i in 0..<(categoryArray.count + 1) { var lblWidth = 0 var objData:CategoryJSON! let lbl = UILabel() if i == 0 { lbl.frame = CGRect(x: 0, y: 0, width: 80, height: 50) width = 80 } else { objData = categoryArray[i - 1] if languageCode == "ar" { lblWidth = Int((objData.arabicName.html2AttributedString?.width(withConstrainedHeight: 50))!) } else { lblWidth = Int((objData.name.html2AttributedString?.width(withConstrainedHeight: 50))!) } width = lblWidth + 80 lbl.frame = CGRect(x: 44, y: 16, width: lblWidth+40, height: 17) } let view = UIView() view.frame = CGRect(x: Int(xAxis), y: 0, width: Int(width), height: 50) lbl.textAlignment = .center lbl.font = UIFont.systemFont(ofSize: 14.0) lbl.backgroundColor = .clear let imgPicture = UIImageView() imgPicture.frame = CGRect(x: 10, y: 10, width: 30, height: 30) imgPicture.contentMode = .scaleAspectFit let btn = UIButton() btn.frame = CGRect(x: 0, y: 0, width: Int(width), height: 50) btn.tag = i + 1000 btn.addTarget(self, action: #selector(clickBtnACtion(button:)), for: .touchUpInside) let lineView = UIView() lineView.frame = CGRect(x: 10, y: Int(view.frame.height - 3.0), width: Int(view.frame.width) - 10, height: 3) lineView.backgroundColor = UIColor(red: 58.0/255.0, green: 171.0/255.0, blue: 51.0/255.0, alpha: 1) lineView.tag = i + 2000 let seperator = UIView() seperator.frame = CGRect(x: width + 5, y: 15, width: 1, height: 20) seperator.alpha = 0.5 seperator.backgroundColor = .lightGray if i == 0 { lineView.alpha = 1 if languageCode == "ar" { lbl.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) lbl.text = "جميع" } else { lbl.text = "All" } } else { if let imgUrl = URL(string: String(format: "%@%@", Constants.URL.imagesUrl, objData.imgUrl.encodeUrl())) { imgPicture.sd_setShowActivityIndicatorView(true) imgPicture.sd_setIndicatorStyle(.gray) imgPicture.sd_setImage(with: imgUrl, completed: nil) } lineView.alpha = 0 if languageCode == "ar" { lbl.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) lbl.text = objData.arabicName } else { lbl.text = objData.name } } view.addSubview(imgPicture) view.addSubview(lbl) view.addSubview(lineView) view.addSubview(btn) if i < categoryArray.count { view.addSubview(seperator) } scrollView.addSubview(view) xAxis += (Int(width)) + 10 } scrollView.contentSize = CGSize(width: xAxis + 10, height: 0) if languageCode == "ar" { scrollView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) } } @IBAction func clickBtnACtion(button: UIButton) { txtSearch.text = "" txtSearch.resignFirstResponder() hideLines() let view = self.view.viewWithTag(button.tag + 1000) view?.alpha = 1 if button.tag == 1000 { tblView.alpha = 0 tblAllView.alpha = 1 allFilteredCategories = allCategories tblAllView.reloadData() } else { tblView.alpha = 1 tblAllView.alpha = 0 let objData = categoryArray[button.tag - 1001] selectedCat = objData.id; selectedCatName = objData.name selectedIndex = button.tag - 1001 filteredArray = [SubCategoryObject]() tblView.reloadData() getSubCategories(catID: selectedCat) } } func hideLines() { for i in 0..<(categoryArray.count + 1) { let view = self.view.viewWithTag(i + 2000) view?.alpha = 0 } } func showLoader() { self.startAnimating(Constants.activitySize.size, message: Constants.loaderMessages.loadingMessage.rawValue,messageFont: UIFont.systemFont(ofSize: 14), type: NVActivityIndicatorType.ballClipRotatePulse) } func getSubCategories(catID: Int) { self.subCategoriesAPI(catID: catID) } func getAllCategoriesAPI() { let parameters: [String: Any] = ["id": "1"] self.showLoader() AddsHandler.getAllCategories(parameter: parameters as NSDictionary, success: { (successResponse) in self.stopAnimating() if successResponse.success { allCategories = successResponse.categories self.allFilteredCategories = allCategories DispatchQueue.main.async { self.tblView.alpha = 0 self.tblAllView.alpha = 1 self.tblAllView.reloadData() } } else { let alert = Constants.showBasicAlert(message: successResponse.message) self.presentVC(alert) } }) { (error) in self.stopAnimating() let alert = Constants.showBasicAlert(message: error.message) self.presentVC(alert) } } func subCategoriesAPI(catID: Int) { let parameters: [String: Any] = ["id": String(format: "%d", catID)] self.showLoader() AddsHandler.getSubCategories(parameter: parameters as NSDictionary, success: { (successResponse) in self.stopAnimating() if successResponse.success { let catArray = successResponse.categories print(catArray) self.subCatArray = [SubCategoryObject]() if catArray!.count > 0 { for obj in catArray! { var subCatObj = SubCategoryObject() subCatObj.id = obj.id subCatObj.name = obj.name subCatObj.hasSub = obj.hasSub subCatObj.hasParent = obj.hasParent if obj.arabicName != nil && obj.arabicName != "" { subCatObj.arabicName = obj.arabicName } else { subCatObj.arabicName = obj.name } DispatchQueue.main.async { self.subCatArray.append(subCatObj) self.filteredArray = self.subCatArray if obj.hasSub == "1" { DispatchQueue.main.async { self.innerCategoriesAPI(catID: obj.id) } } } } } DispatchQueue.main.async { self.tblView.reloadData() } } else { let alert = Constants.showBasicAlert(message: successResponse.message) self.presentVC(alert) } }) { (error) in self.stopAnimating() let alert = Constants.showBasicAlert(message: error.message) self.presentVC(alert) } } func innerCategoriesAPI(catID: Int) { self.showLoader() let parameters: [String: Any] = ["id": String(format: "%d", catID)] AddsHandler.getSubCategories(parameter: parameters as NSDictionary,success: { (successResponse) in NVActivityIndicatorPresenter.sharedInstance.stopAnimating() if successResponse.success { let catArray = successResponse.categories print(catArray) if catArray!.count > 0 { var catArray = [SubCategoryObject]() for obj in successResponse.categories { var subCatObj = SubCategoryObject() subCatObj.id = obj.id subCatObj.name = obj.name subCatObj.hasSub = obj.hasSub if obj.arabicName != nil && obj.arabicName != "" { subCatObj.arabicName = obj.arabicName } else { subCatObj.arabicName = obj.name } catArray.append(subCatObj) } if let index = self.subCatArray.firstIndex(where: { $0.id == catID}) { var obj: SubCategoryObject = self.subCatArray[index] obj.subCatArray = catArray self.subCatArray[index] = obj } self.filteredArray = self.subCatArray DispatchQueue.main.async { self.tblView.reloadData() } } } else { let alert = Constants.showBasicAlert(message: successResponse.message) self.presentVC(alert) } }) { (error) in NVActivityIndicatorPresenter.sharedInstance.stopAnimating() let alert = Constants.showBasicAlert(message: error.message) self.presentVC(alert) } } @IBAction func textFiledDidChange(_ textFiled : UITextField) { if selectedIndex == 0 { if textFiled.text != "" { if languageCode == "ar" { allFilteredCategories = allCategories.filter({ var flag = false if $0.arabicName != nil && $0.arabicName != "" { flag = $0.arabicName.localizedCaseInsensitiveContains(String(format: "%@",textFiled.text!)) } else { flag = $0.name.localizedCaseInsensitiveContains(String(format: "%@",textFiled.text!)) } return flag }) } else { allFilteredCategories = allCategories.filter({$0.name.localizedCaseInsensitiveContains(String(format: "%@",textFiled.text!))}) } } else { allFilteredCategories = allCategories } tblAllView.reloadData() } else { if textFiled.text != "" { if languageCode == "ar" { filteredArray = subCatArray.filter({ var flag = false if $0.arabicName != "" { flag = $0.arabicName.localizedCaseInsensitiveContains(String(format: "%@",textFiled.text!)) } else { flag = $0.name.localizedCaseInsensitiveContains(String(format: "%@",textFiled.text!)) } return flag }) } else { filteredArray = subCatArray.filter({$0.name.localizedCaseInsensitiveContains(String(format: "%@",textFiled.text!))}) } } else { filteredArray = subCatArray } tblView.reloadData() } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { txtSearch.resignFirstResponder() } } extension CategoryVC: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var count = 0 if tableView.tag == 1001 { count = allFilteredCategories.count } else { if section > 0 { if self.filteredArray.count > 0 { count = self.filteredArray[section - 1].subCatArray.count print(count) } } } return count } func numberOfSections(in tableView: UITableView) -> Int { var count = 1 if tableView.tag == 1002 { if self.filteredArray.count > 0 { count = self.filteredArray.count + 1 } } return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: CategoryCell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath) as! CategoryCell if tableView.tag == 1001 { let category = allFilteredCategories[indexPath.row] if languageCode == "ar" { if category.arabicName != nil && category.arabicName != "" { cell.lblName.text = category.arabicName } else { cell.lblName.text = category.name } } else { cell.lblName.text = category.name } } else { if indexPath.section > 0 { let category = self.filteredArray[indexPath.section - 1].subCatArray let subCat = category[indexPath.row] if languageCode == "ar" { if subCat.arabicName != "" { cell.lblName.text = subCat.arabicName } else { cell.lblName.text = subCat.name } } else { cell.lblName.text = subCat.name } } } return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if tableView.tag == 1002 { let view = UIView(frame: CGRect(x: 10, y: 0, width: tableView.frame.size.width, height: 44)) let label = UILabel(frame: CGRect(x: 10, y: 0, width: 300, height: 44)) label.textColor = UIColor.black label.backgroundColor = .white label.font = UIFont.systemFont(ofSize: 14.0) let arrow = UIImageView(frame: CGRect(x: tableView.frame.size.width - 30, y: 15, width: 15, height: 15)) arrow.image = UIImage(named: "drop_arrow") arrow.contentMode = .scaleAspectFit let lineview = UIView(frame: CGRect(x: 10, y: 43.5, width: tableView.frame.size.width - 10, height: 0.5)) lineview.backgroundColor = .lightGray lineview.alpha = 0.5 view.addSubview(label) view.addSubview(lineview) if section == 0 { if languageCode == "ar" { label.text = "جميع الأصناف" } else { label.text = "All types" } } else { let values = self.filteredArray[section - 1] if values.hasSub == "1" { view.addSubview(arrow) } if languageCode == "ar" { if values.arabicName != "" { label.text = values.arabicName } else { label.text = values.name } } else { label.text = values.name } } return view } else { return nil } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { txtSearch.resignFirstResponder() let adFilterListVC = self.storyboard?.instantiateViewController(withIdentifier: "AdFilterListVC") as! AdFilterListVC if tableView.tag == 1001 { let values = allFilteredCategories[indexPath.row] if fromVC == "filter" || fromVC == "adPost" { adDetailObj.catID = Int(values.hasParent) ?? 0 adDetailObj.adCategory = "" adDetailObj.subcatID = values.id if languageCode == "ar" { if values.arabicName != nil && values.arabicName != "" { adDetailObj.adSubCategory = values.arabicName } else { adDetailObj.adSubCategory = values.name } } else { adDetailObj.adSubCategory = values.name } self.navigationController?.popViewController(animated: true) } else { adFilterListVC.categoryID = Int(values.hasParent) ?? 0 adFilterListVC.catName = "" adFilterListVC.subcategoryID = values.id if languageCode == "ar" { if values.arabicName != nil && values.arabicName != "" { adFilterListVC.subcatName = values.arabicName } else { adFilterListVC.subcatName = values.name } } else { adFilterListVC.subcatName = values.name } self.navigationController?.pushViewController(adFilterListVC, animated: true) } } else { if indexPath.section == 0 { if fromVC == "filter" || fromVC == "adPost" { adDetailObj.adCategory = selectedCatName adDetailObj.catID = selectedCat adDetailObj.adSubCategory = "" adDetailObj.subcatID = 0 self.navigationController?.popViewController(animated: true) } else { adFilterListVC.categoryID = selectedCat adFilterListVC.catName = selectedCatName self.navigationController?.pushViewController(adFilterListVC, animated: true) } } else { let category = self.filteredArray[indexPath.section - 1].subCatArray let values = category[indexPath.row] if fromVC == "filter" || fromVC == "adPost" { adDetailObj.adCategory = selectedCatName adDetailObj.catID = selectedCat adDetailObj.subcatID = values.id if languageCode == "ar" { if values.arabicName != "" { adDetailObj.adSubCategory = values.arabicName } else { adDetailObj.adSubCategory = values.name } } else { adDetailObj.adSubCategory = values.name } self.navigationController?.popViewController(animated: true) } else { adFilterListVC.categoryID = selectedCat adFilterListVC.catName = selectedCatName adFilterListVC.subcategoryID = values.id if languageCode == "ar" { if values.arabicName != "" { adFilterListVC.subcatName = values.arabicName } else { adFilterListVC.subcatName = values.name } } else { adFilterListVC.subcatName = values.name } self.navigationController?.pushViewController(adFilterListVC, animated: true) } } } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if tableView.tag == 1002 { return 44 } else { return 0 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } }
// // ListTableViewController.swift // OnTheMap // // Created by Ranjith on 9/1/16. // Copyright © 2016 Ranjith. All rights reserved. // import UIKit class ListTableViewController: UITableViewController { // MARK: Properties // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() // create and set the logout button // parentViewController!.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Reply, target: self, action: #selector(logout)) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) ONMAPClient.sharedInstance().getStudentDetails { (students, error) in if let students = students { StudentData.sharedInstance().studentData = students performUIUpdatesOnMain { self.tableView.reloadData() } } else { print(error) } } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { /* Get cell type */ let cellReuseIdentifier = "StudentTableViewCell" let student = StudentData.sharedInstance().studentData![indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell! /* Set cell defaults */ cell.textLabel!.text = student.firstName + " " + student.lastName cell.imageView!.image = UIImage(named:"pin") return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let stu = StudentData.sharedInstance().studentData{ return stu.count } else { return 0; } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let student = StudentData.sharedInstance().studentData![indexPath.row] //UIApplication.sharedApplication().openURL(NSURL(string: student.mediaURL)!) let app = UIApplication.sharedApplication() if let toOpen = student.mediaURL { app.openURL(NSURL(string: toOpen)!) } } @IBAction func logOutTapped(sender: AnyObject) { failLogOutAlert() } @IBAction func refreshTapped(sender: AnyObject) { ONMAPClient.sharedInstance().getStudentDetails { (students, error) in if let students = students { StudentData.sharedInstance().studentData = students performUIUpdatesOnMain { self.tableView.reloadData() } } else { print(error) let failLoginAlert = UIAlertController(title: "Failed to download", message: "Please check your Network and try again", preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default) { UIAlertAction in } failLoginAlert.addAction(okAction) self.presentViewController(failLoginAlert, animated: true, completion: nil) } } } func logOut() { ONMAPClient.sharedInstance().deleteSession() { (result, error) in if error != nil { self.failAlertGeneral("LogOut Unsuccessful", message: "Something went wrong, please try again", actionTitle: "OK") } else { performUIUpdatesOnMain { print("logout success \(result)") dispatch_async(dispatch_get_main_queue(), { self.dismissViewControllerAnimated(true, completion: nil) }) } } } } func failLogOutAlert() { let failLogoutAlert = UIAlertController(title: "Wanna Logout?", message: "Just double checking, we'll miss you!", preferredStyle: UIAlertControllerStyle.Alert) failLogoutAlert.addAction(UIAlertAction(title: "Log Me Out", style: UIAlertActionStyle.Default, handler: { alertAction in self.logOut() })) failLogoutAlert.addAction(UIAlertAction(title: "Take Me Back!", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(failLogoutAlert, animated: true, completion: nil) } func failAlertGeneral(title: String, message: String, actionTitle: String) { let failAlertGeneral = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) failAlertGeneral.addAction(UIAlertAction(title: actionTitle, style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(failAlertGeneral, animated: true, completion: nil) } private func locationController(){ performUIUpdatesOnMain{ var controller:UINavigationController controller = self.storyboard?.instantiateViewControllerWithIdentifier("nvcontroller") as! UINavigationController self.presentViewController(controller, animated: true, completion: nil) } } @IBAction func pinAddButtonPressed(sender: AnyObject) { ONMAPClient.sharedInstance().getCurrentStudentDetails { (exist, error) in if exist { print("data exist") performUIUpdatesOnMain{ let postAlert = UIAlertController(title: "Exist", message: " pin already exist due u want overwrite", preferredStyle: UIAlertControllerStyle.Alert) postAlert.addAction(UIAlertAction(title: "Update", style: .Default, handler: { (action: UIAlertAction!) in self.locationController() })) postAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in print("Handle Cancel Logic here") })) self.presentViewController(postAlert, animated: true, completion: nil) } } else{ print("not exist") ONMAPClient.sharedInstance().getUserCompleteInfo() { (result, error) in if error != nil { } else { print("success") self.locationController() } } } } } }
// // DoTests.swift // DoTests // // Created by Barak Harel on 05/12/2016. // Copyright © 2016 Barak Harel. All rights reserved. // import XCTest @testable import DoThis class DoTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testExample() { let exp = expectation(description: "test") Do.this { this in print("Do.this") this.succeeded() }.then (name: "result step", after: 2) { this in print("previousResult: \(String(describing: this.previousResult))") this.succeeded(this.name) }.then { this in print("previousResult: \(String(describing: this.previousResult))") this.succeeded("\(this.index) - before error") }.then { this in print("previousResult: \(String(describing: this.previousResult))") //this.failed(NSError(domain: "error4", code: 4, userInfo: nil)) this.succeeded("boop") }.then (on: DispatchQueue.global(qos: .background)) { this in print("previousResult: \(String(describing: this.previousResult)) on: \(DispatchQueue.currentLabel ?? "")") this.done(.success(this.index)) }.then (on: .main) { this in print("previousResult: \(String(describing: this.previousResult)) on: \(DispatchQueue.currentLabel ?? "")") this.done(.success(this.index)) }.catch { error, this in print("catched error: \(String(describing: error)) from \(this.name ?? String(this.index))") }.finally { this in print("finally (previousResult: \(String(describing: this.previousResult)))") exp.fulfill() } self.waitForExpectations(timeout: 25.0) { (error) -> Void in XCTAssert(error == nil, "test took too long, error: \(String(describing: error))") } } } extension DispatchQueue { class var currentLabel: String? { let name = __dispatch_queue_get_label(nil) return String(cString: name, encoding: .utf8) } }
// // MainVC.swift // window-shopper // // Created by Donald Belliveau on 2017-11-28. // Copyright © 2017 Donald Belliveau. All rights reserved. // import UIKit class MainVC: UIViewController { /* IBOutlets */ @IBOutlet weak var wageTxt: CurrencyTxtField! @IBOutlet weak var priceTxt: CurrencyTxtField! @IBOutlet weak var resultLbl: UILabel! @IBOutlet weak var hoursLbl: UILabel! /* Functions */ /* View Did Load */ override func viewDidLoad() { super.viewDidLoad() // Create UIButton attaching to the textfield's keyboard. let calcBtn = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 60)) // Set Button Colour calcBtn.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.4557419206, blue: 0.3894221219, alpha: 1) //Set Button Title calcBtn.setTitle("Calculate", for: .normal) // Set Button Title Colour calcBtn.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal) // Target for when the button is pressed (what function) calcBtn.addTarget(self, action: #selector(MainVC.calculate), for: .touchUpInside) wageTxt.inputAccessoryView = calcBtn priceTxt.inputAccessoryView = calcBtn // Hide Labels resultLbl.isHidden = true hoursLbl.isHidden = true } /* END View Did Load. */ /* Did Receive Memory Warning. */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* END Did Receive Memory Warning. */ /* Calculate Button Function */ @objc func calculate() { // Make sure wageTxt and priceTxt isn't Nil. if let wageTxt = wageTxt.text, let priceTxt = priceTxt.text { // Make sure we can cast the 2 Strings to Doubles. if let wage = Double(wageTxt), let price = Double(priceTxt) { // Dismiss keyboard view.endEditing(true) resultLbl.isHidden = false hoursLbl.isHidden = false resultLbl.text = "\(Wage.getHours(forWage: wage, andPrice: price))" //print(resultLbl.text) } } } /* END Calculate Button Function. */ /* Clear Calcutator Button Pressed Function. */ @IBAction func clearCalculatorPressed(_ sender: Any) { // Hide Labels & Clear Test Fields. resultLbl.isHidden = true hoursLbl.isHidden = true wageTxt.text = "" priceTxt.text = "" } /* END Clear Calaculator Button Pressed Function. */ }
// // ViewController + Extension.swift // CSVAssignment // // Created by Rukmani on 21/08/17. // Copyright © 2017 rukmani. All rights reserved. // import Foundation import UIKit extension ViewController { enum WeatherParam { case Tmax case Tmin case Tmean case Sunshine case Rainfall } func getWeatherParam(type: WeatherParam) -> String{ switch type { case .Tmax: return "Max Temp" case .Tmin: return "Min Temp" case .Tmean: return "Mean Temp" case .Sunshine: return "Sunshine" case .Rainfall: return "Rainfall" } } func createCSVFile(file: String) { let fileName = file + ".csv" var csvText = "region_code,weather_param,year,key,value\n" for data in dictData { let newLine = "\(data.regionCode),\(data.weatherParam),\(data.year),\(data.key),\(data.value)\n" csvText.append(newLine) } do { let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first let path = dir?.appendingPathComponent(fileName) try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8) print("path : ",path!) self.pathName = path! } catch { print("csv file cannot be created") } readCSVFile(fileName: "weather") } func readCSVFile(fileName: String) { do { let content = try String(contentsOf: self.pathName!, encoding: String.Encoding.utf8) dictData.removeAll() var lines = content.components(separatedBy: "\n") lines.removeLast() for line in lines { let columns = line.components(separatedBy: ",") let dict = DataModel(_regionCode: columns[0], _weatherParam: columns[1], _year: columns[2], _key: columns[3], _value: columns[4]) self.dictData.append(dict) } } catch { print("error: ", error.localizedDescription) } DispatchQueue.main.async { self.tableView.reloadData() } } }
// // State.swift // Calculadora // // Created by Everton Zanatta on 29/05/19. // Copyright © 2019 CWI Software. All rights reserved. // import Foundation enum State { case left, operation, right }
// // NSLayoutConstraint+ChangeMultiplier.swift // Bluefruit // // Created by Antonio García on 28/02/2019. // import Foundation // from: https://stackoverflow.com/questions/19593641/can-i-change-multiplier-property-for-nslayoutconstraint/32859742 extension NSLayoutConstraint { /** Change multiplier constraint - parameter multiplier: CGFloat - returns: NSLayoutConstraint */ static func setMultiplier(multiplier:CGFloat, constraint: inout NSLayoutConstraint) { if multiplier == 0 { DLog("Warning: multiplier 0 breaks this function") } NSLayoutConstraint.deactivate([constraint]) let newConstraint = NSLayoutConstraint( item: constraint.firstItem as Any, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: constraint.secondItem, attribute: constraint.secondAttribute, multiplier: multiplier, constant: constraint.constant) newConstraint.priority = constraint.priority newConstraint.shouldBeArchived = constraint.shouldBeArchived newConstraint.identifier = constraint.identifier NSLayoutConstraint.activate([newConstraint]) constraint = newConstraint } }
// // addimage.swift // CoreML in ARKit // // Created by Stephanie on 3/12/18. // Copyright © 2018 CompanyName. All rights reserved. // import UIKit extension UIAlertController { func addImage(image: UIImage) { let maxSize = CGSize(width: 245, height: 380) let imgSize = image.size var ratio: CGFloat! if (imgSize.width > imgSize.height) { ratio = maxSize.width / imgSize.width }else { ratio = maxSize.height / imgSize.height } let scaledSize = CGSize(width: imgSize.width * ratio, height: imgSize.height * ratio) var resizedImage = image.imageWithSize(scaledSize) if (imgSize.height > imgSize.width) { let left = (maxSize.width - resizedImage.size.width) / 2 resizedImage = resizedImage.withAlignmentRectInsets(UIEdgeInsetsMake(0, -left, 0 , 0)) } let imgAction = UIAlertAction(title: "", style: .default, handler: nil) imgAction.isEnabled = true imgAction.setValue(resizedImage.withRenderingMode(.alwaysOriginal), forKey: "image") self.addAction(imgAction) } }
// // UIView+Extension.swift // Big Brain Team // // Created by Nick Oltyan on 08.10.2021. // import Foundation import UIKit extension UIView { /// Self return UIView with given border width and color. /// - parameter borderWidth: View border width /// - parameter color: View border color (CGColor) func with(borderWidth: CGFloat, color: CGColor) -> Self { layer.borderWidth = borderWidth layer.borderColor = color return self } /// Return Self UIView with given background color. /// - parameter bgColor: View background color func with(bgColor: UIColor) -> Self { backgroundColor = bgColor return self } /// Self return UIView with given corner radius. /// - parameter cornerRadius: View corner radius func with(cornerRadius: CGFloat) -> Self { self.layer.cornerRadius = cornerRadius return self } /// Self return UILabel with given autolayout. /// - parameter autolayout: Shoud the label Translates Autoresizing Mask Into Constraints. func with(autolayout: Bool) -> Self { translatesAutoresizingMaskIntoConstraints = autolayout return self } func tap(completion: @escaping(_ completion: Bool) -> Void) { UIView.animate(withDuration: 0.06, animations: { self.transform = CGAffineTransform.init(scaleX: 0.92, y: 0.92) self.alpha = 0.86 }, completion: { (_) in UIView.animate(withDuration: 0.06, animations: { self.transform = CGAffineTransform.init(scaleX: 1, y: 1) self.alpha = 1 }, completion: { (_) in completion(true) }) }) } enum rotationAngle { case vertical case horizontal } func rotate(forPosition position: rotationAngle) { switch position { case .horizontal: UIView.animate(withDuration: 0.2, animations: { self.transform = CGAffineTransform(rotationAngle: 0) }) case .vertical: UIView.animate(withDuration: 0.2, animations: { self.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2) }) } } }
// // GLuniform4.swift // ChaosKit // // Created by Fu Lam Diep on 11.06.15. // Copyright (c) 2015 Fu Lam Diep. All rights reserved. // import Foundation import OpenGL import OpenGL.GL import OpenGL.GL3 public struct GLuniform4d : GLUniform { private let _value : (x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) public init (_ x: GLdouble, _ y: GLdouble, z: GLdouble, w: GLdouble) { _value = (x, y, z, w) } public func assign (location: GLuniformloc) { glUniform4d(GLint(location.index), _value.x, _value.y, _value.z, _value.w) } } public struct GLuniform4f : GLUniform { private let _value : (x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) public init (_ x: GLfloat, _ y: GLfloat, _ z: GLfloat, _ w: GLfloat) { _value = (x, y, z, w) } public init (_ value : vec4) { self.init(value.x, value.y, value.z, value.w) } public func assign (location: GLuniformloc) { glUniform4f(GLint(location.index), _value.x, _value.y, _value.z, _value.w) } } public struct GLuniform4i : GLUniform { private let _value : (x: GLint, y: GLint, z: GLint, w: GLint) public init (_ x: GLint, _ y: GLint, z: GLint, w: GLint) { _value = (x, y, z, w) } public func assign (location: GLuniformloc) { glUniform4i(GLint(location.index), _value.x, _value.y, _value.z, _value.w) } } public struct GLuniform4ui : GLUniform { private let _value : (x: GLuint, y: GLuint, z: GLuint, w: GLuint) public init (_ x: GLuint, _ y: GLuint, z: GLuint, w: GLuint) { _value = (x, y, z, w) } public func assign (location: GLuniformloc) { glUniform4ui(GLint(location.index), _value.x, _value.y, _value.z, _value.w) } }
// // FSAppConfig.swift // FSSwift // // Created by Guazi on 2017/12/22. // Copyright © 2017年 china. All rights reserved. // import UIKit let AppColor_Red = FSKit.rgbColor(r: 250, g: 80, b: 100, a: 1) class FSAppConfig: NSObject { }
// // MapViewController.swift // Dart-Trip // // // Created by Satoru Yoshizaki on 2019/06/25. // Copyright © 2019 Satoru Yoshizaki. All rights reserved. // import UIKit import MapKit import CoreLocation class MapViewController: UIViewController, CLLocationManagerDelegate, MapViewServiceDelegate { @IBOutlet var mapView: MKMapView! @IBOutlet weak var favoriteButton: UIButton! @IBOutlet weak var ThrowButton: UIButton! @IBOutlet weak var zoomInButton: UIButton! @IBOutlet weak var zoomOutButton: UIButton! @IBOutlet weak var detailButton: UIButton! @IBOutlet weak var detailLabel: UILabel! @IBOutlet weak var uiView: UIView! let service = MapViewService(webService: WebServiceImp()) var locManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() service.delegate = self ThrowButton.imageView?.contentMode = .scaleAspectFit zoomInButton.backgroundColor = .black zoomOutButton.backgroundColor = .black uiView.isHidden = true locManager = CLLocationManager() locManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled(){ switch CLLocationManager.authorizationStatus(){ case .authorizedWhenInUse: locManager.delegate = self locManager.startUpdatingLocation() break default: break } } initMap() mapView.addSubview(uiView) } func initMap(){ // デフォルトの縮尺を設定する var region: MKCoordinateRegion = mapView.region region.span.latitudeDelta = 20.0 region.span.longitudeDelta = 20.0 mapView.setRegion(region, animated: true) mapView.showsUserLocation = true mapView.userTrackingMode = .followWithHeading } func updateCurrentPos(_ coordinate:CLLocationCoordinate2D) { var region:MKCoordinateRegion = mapView.region region.center = coordinate region.span.latitudeDelta = 1.5 region.span.longitudeDelta = 1.5 mapView.setRegion(region,animated:true) } @IBAction func didTapThrowButton(_ sender: Any) { mapView.removeAnnotations(mapView.annotations) service.didtapThrowButton() } @IBAction func didTapZoomInButton(_ sender: Any) { var span = MKCoordinateSpan() span.latitudeDelta = mapView.region.span.latitudeDelta/2 span.longitudeDelta = mapView.region.span.longitudeDelta/2 let region = createNewRegion(span: span) mapView.setRegion(region, animated: true) } @IBAction func didTapZoomOutButton(_ sender: Any) { var span = MKCoordinateSpan() span.latitudeDelta = mapView.region.span.latitudeDelta*2 span.longitudeDelta = mapView.region.span.longitudeDelta*2 let region = createNewRegion(span: span) mapView.setRegion(region, animated: true) } func createNewRegion(span: MKCoordinateSpan) -> MKCoordinateRegion{ var region = MKCoordinateRegion() region.span = span region.center = mapView.region.center return region } @IBAction func didTapDetailButton(_ sender: Any) { let controller = DetailViewController() let navigationController = UINavigationController() navigationController.pushViewController(controller, animated: true) } @IBAction func didTapFavoriteButton(_ sender: Any) { service.didTapFavoriteButton() favoriteButton.setTitle("追加済", for: .normal) } func reload() { CLGeocoder().geocodeAddressString(service.location.name) { placemarks, error in var newCoodinate = CLLocationCoordinate2D() if let lat = placemarks?.first?.location?.coordinate.latitude { newCoodinate.latitude = lat } if let lng = placemarks?.first?.location?.coordinate.longitude { newCoodinate.longitude = lng } let annotation = MKPointAnnotation() annotation.coordinate = newCoodinate self.mapView.addAnnotation(annotation) self.updateCurrentPos(newCoodinate) self.uiView.isHidden = false self.detailLabel.text = self.service.location.name } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let nextvc = segue.destination as? DetailViewController{ nextvc.name = self.service.location.name } } }
import RxSwift import RxRelay import RxCocoa class MarketViewModel { private let service: MarketService private let disposeBag = DisposeBag() private let currentTabRelay: BehaviorRelay<MarketModule.Tab> init(service: MarketService) { self.service = service currentTabRelay = BehaviorRelay<MarketModule.Tab>(value: service.initialTab) } } extension MarketViewModel { var currentTabDriver: Driver<MarketModule.Tab> { currentTabRelay.asDriver() } var tabs: [MarketModule.Tab] { MarketModule.Tab.allCases } func onSelect(tab: MarketModule.Tab) { service.set(tab: tab) currentTabRelay.accept(tab) } }
@testable import ShuttleCore import XCTest class TestClient: ShuttleCore.Client { } class RetryTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testReRaisesWhenRetryLimitReachedThrowingTimeoutError() { } func testReRaisesWhenRetryLimitReachedThrowingConnectionFailed() { } func testRetriesWhenTimeoutErrorThrown() { } func testRetriesWhenConnectionFailedErrorThrown() { } func testRaisesAppleTimeoutErrorWhenResponseContains302Found() { } func testSuccessfullyRetriesRequestAfterLoggingInAgainWhenUnauthorizedAccessErrorThrown() { } func testFailsToRetryRequestIfLoginFailsInRetryBlockWhenUnauthorizedAccessErrorThrown() { } func testRetryWhenUserAndPasswordNotFetchedFromCredentialManagerIsAbleToRetryAndLoginSuccessfully() { } } class PersistentCookieTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testUsesEnvWhenSet() { } func testUsesHomeDirByDefault() { } func testUsesTmpDirIfHomeNotAvailable() { } func testFallsBackToTmpDirAsLastResort() { } }
// // TicketMenuItemView.swift // // Copyright © 2020 Steamclock Software. // // 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 Cocoa class TicketMenuItemView: NSView { private var ticket: Ticket! private var backgroundLabel: NSTextField! private var titleLabel: NSTextField! private var imageView: NSImageView! // MARK: Initializers init(frame: NSRect, ticket: Ticket, showLabels: Bool) { super.init(frame: frame) self.ticket = ticket imageView = NSImageView() addSubview(imageView) imageView.snp.makeConstraints { make in make.left.equalToSuperview().offset(20) make.top.bottom.equalToSuperview() } if let image = ticket.type.image { imageView.image = image.imageWithTintColor(tintColor: NSColor.ThemeColor.text, imageName: ticket.type.imageName) imageView.snp.remakeConstraints { make in make.left.equalToSuperview().offset(15) make.centerY.equalToSuperview() make.width.height.equalTo(18) } } backgroundLabel = NSTextField.toLabel addSubview(backgroundLabel) backgroundLabel.backgroundColor = NSColor.clear backgroundLabel.snp.makeConstraints { make in make.edges.equalToSuperview() } backgroundLabel.sizeToFit() var rightAnchor = backgroundLabel.snp.right if showLabels { let maxLabelViewSize = frame.width * 0.6 let labelsView = LabelsView(labels: ticket.labels, frame: NSRect(x: frame.maxX - maxLabelViewSize - 15, y: 0, width: maxLabelViewSize, height: frame.height)) addSubview(labelsView) labelsView.snp.makeConstraints { make in make.top.bottom.equalTo(backgroundLabel) make.right.equalTo(backgroundLabel).inset(20) } rightAnchor = labelsView.snp.left } titleLabel = NSTextField.toLabel titleLabel.stringValue = ticket.name titleLabel.font = NSFont.systemFont(ofSize: 14) titleLabel.cell?.lineBreakMode = .byTruncatingTail titleLabel.cell?.alignment = .left titleLabel.backgroundColor = NSColor.clear addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.left.equalTo(imageView.snp.right) make.right.lessThanOrEqualTo(rightAnchor).offset(-8) make.centerY.equalToSuperview() } } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View Overrides override func draw(_ dirtyRect: NSRect) { if enclosingMenuItem?.isHighlighted == true { NSColor.keyboardFocusIndicatorColor.setFill() toggleHighlighted(true) dirtyRect.fill() } else { toggleHighlighted(false) super.draw(dirtyRect) } } override func mouseUp(with event: NSEvent) { guard let menuItem = enclosingMenuItem, let menu = menuItem.menu else { return } menu.cancelTracking() menu.performActionForItem(at: menu.index(of: menuItem)) } // MARK: Helpers private func toggleHighlighted(_ on: Bool) { let color = on ? NSColor.ThemeColor.highlightedText : NSColor.ThemeColor.text titleLabel.textColor = color backgroundLabel.textColor = color if let image = ticket.type.image { image.isTemplate = true imageView.image = ticket.type.image?.imageWithTintColor(tintColor: on ? NSColor.ThemeColor.highlightedText : NSColor.ThemeColor.text, imageName: ticket.type.imageName) } } }
// // CoreGraphicsTests.swift // swift-utils // // Created by Sven Schmidt on 04/03/2015. // // import XCTest import Nimble let a = CGPoint(x: 1, y: 2) let b = CGPoint(x: 2, y: 3) let c = CGPoint(x: 3, y: 6) let s = CGSize(width: 10, height: 20) class CGPointTests: XCTestCase { func test_addition() { expect(a + b) == CGPoint(x: 3, y: 5) expect(b + a) == CGPoint(x: 3, y: 5) expect(a + (2.0, 3.0)) == CGPoint(x: 3, y: 5) expect(a + (2, 3)) == CGPoint(x: 3, y: 5) } func test_subtraction() { expect(a - c) == CGPoint(x: -2, y: -4) expect(c - b) == CGPoint(x: 1, y: 3) expect(a - s) == CGPoint(x: -9, y: -18) expect(a - (3, 5)) == CGPoint(x: -2, y: -3) } func test_division() { expect(a / 2) == CGPoint(x: 0.5, y: 1) } func test_augmentedAddition() { var x = a x += b expect(x) == a + b } func test_augmentedSubtraction() { var x = a x -= c expect(x) == a - c } func test_initWithSize() { expect(CGPoint(size: s)) == CGPoint(x: 10, y: 20) } } let t = CGSize(width: 15, height: 40) class CGSizeTests: XCTestCase { func test_addition() { expect(s + t) == CGSize(width: 25, height: 60) expect(s + (5, 10)) == CGSize(width: 15, height: 30) } func test_subtraction() { expect(s - t) == CGSize(width: -5, height: -20) expect(t - s) == CGSize(width: 5, height: 20) } func test_division() { expect(s / 2) == CGSize(width: 5, height: 10) } } class CGRectTests: XCTestCase { func test_withPadding() { let r = CGRect(x: 1, y: 2, width: 5, height: 10) expect(r.withPadding(x: 5, y: 15)) == CGRect(x: -4, y: -13, width: 15, height: 40) } func test_createTiles() { let r = CGRect(x: 20, y: 10, width: 100, height: 60) let tiles = r.createTiles(columns: 2, rows: 3) expect(tiles.count) == 6 tiles.each { expect($0.size) == CGSize(width: 50, height: 20) } expect(tiles[0].origin) == CGPoint(x: 20, y: 10) expect(tiles[1].origin) == CGPoint(x: 70, y: 10) expect(tiles[2].origin) == CGPoint(x: 20, y: 30) expect(tiles[3].origin) == CGPoint(x: 70, y: 30) expect(tiles[4].origin) == CGPoint(x: 20, y: 50) expect(tiles[5].origin) == CGPoint(x: 70, y: 50) } func test_center() { let r = CGRect(x: 20, y: 10, width: 100, height: 60) expect(r.center) == CGPoint(x: 70, y: 40) } } class TupleTests: XCTestCase { func test_multiplication() { let x: (CGFloat, CGFloat) = (1, 2) var res = 2.5 * x expect(res.0) == 2.5 expect(res.1) == 5.0 res = x * 2.5 expect(res.0) == 2.5 expect(res.1) == 5.0 } }
// // TodoDBParameters.swift // Todo // // Created by xincun li on 3/8/16. // Copyright © 2016 xincun li. All rights reserved. // import Foundation import SQLite class TodoDBParameters { static let dbPath = NSHomeDirectory() + "/Documents" static let dbName = "mytodo.sqlite3" static let tableName = "todos" // Declare table static let todosTable = Table("todos") //Table Exist static let tableExistSql = "SELECT EXISTS ( SELECT name FROM sqlite_master WHERE name = ?)" // Declare Columns static let id = Expression<String>("id") static let image = Expression<String>("image") static let title = Expression<String>("title") static let date = Expression<String>("date") }
// // UserInstructionService.swift // countit // // Created by David Grew on 22/02/2019. // Copyright © 2019 David Grew. All rights reserved. // import Foundation protocol UserInstructionService { }
// // SearchViewController.swift // MovieSearcher // // Created by Ruud Puts on 14/09/16. // Copyright © 2016 Ruud Puts. All rights reserved. // import UIKit class SearchViewController: UITableViewController, UISearchBarDelegate { var searchResults = [Movie]() var delegate: SearchViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() let searchBar = UISearchBar() searchBar.delegate = self searchBar.sizeToFit() tableView.tableHeaderView = searchBar } // MARK: - Buttons @IBAction func closeButtonPressed(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } // MARK: - UISearchBarDelegate func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.dismiss(animated: true, completion: nil) } } protocol SearchViewControllerDelegate { func searchViewController(searchViewController: SearchViewController, didFindMovie movie: Movie) }
// // WagnerFischer.swift // DEMO_PROJECT // // Created by xurunkang on 2019/7/26. // Copyright © 2019 xurunkang. All rights reserved. import Foundation struct WagnerFischer<T: Hashable>: DiffAlgorithm { typealias T = T typealias Row = [ChangeSet] func diff(o: [T], n: [T]) -> ChangeSet { let nc = n.count // we don't need to use double dimensional array // because we only focus on previous row and current row // define previous row var previousRow: Row = Array(repeating: [], count: nc + 1) // first line represent .insert op n.enumerated().forEach { (index, ele) in let insertItem = (index, ele) previousRow[index + 1] = append(change: .insert(insertItem), to: previousRow[index]) } // define current row var currentRow: Row = previousRow o.enumerated().forEach { (oldIndex, oldEle) in // first row represent .delete op let deleteItem = (oldIndex, oldEle) currentRow[0] = append(change: .delete(deleteItem), to: previousRow[0]) n.enumerated().forEach({ (newIndex, newEle) in if oldEle == newEle { // levenshtein distance + 0 if two elements are equal // use top-left ele currentRow[newIndex + 1] = previousRow[newIndex] } else { // otherwise, levenshtein distance = min(previous_op_s) + 1 // calculate min op let leftTop = previousRow[newIndex] let left = currentRow[newIndex] let top = previousRow[newIndex + 1] let minimum = min( leftTop.count, left.count, top.count ) // top -> next means delete if minimum == top.count { currentRow[newIndex + 1] = append(change: .delete((oldIndex, oldEle)), to: top) } else if minimum == left.count { // left -> next means insert currentRow[newIndex + 1] = append(change: .insert((newIndex, newEle)), to: left) } else if minimum == leftTop.count { // top-left -> next means substitute currentRow[newIndex + 1] = append(change: .substitute((newIndex, oldEle, newEle)), to: leftTop) } } }) previousRow = currentRow // replace previousRow to currentRow } guard let last = currentRow.last else { return [] } return last } } private extension WagnerFischer { private func append(change: Change<T>, to changeSet: ChangeSet) -> ChangeSet { var changeSet = changeSet changeSet.append(change) return changeSet } }
// // SearchResultTableViewCell.swift // PretixScan // // Created by Daniel Jilg on 20.03.19. // Copyright © 2019 rami.io. All rights reserved. // import UIKit class SearchResultTableViewCell: UITableViewCell { var orderPosition: OrderPosition? { didSet { configure() }} var checkInList: CheckInList? { didSet { configure() }} var event: Event? { didSet { configure() }} @IBOutlet private weak var orderCodeLabel: UILabel! @IBOutlet private weak var orderIDLabel: UILabel! @IBOutlet private weak var ticketType: UILabel! @IBOutlet private weak var secretLabel: UILabel! @IBOutlet private weak var statusLabel: UILabel! @IBOutlet private weak var statusBackgroundView: UIView! private func configure() { guard let event = event, let checkInList = checkInList, let orderPosition = orderPosition else { orderCodeLabel.text = "--" ticketType.text = nil statusLabel.text = nil secretLabel.text = nil return } orderCodeLabel.text = "\(orderPosition.attendeeName ?? "--")" orderIDLabel.text = orderPosition.orderCode ticketType.text = orderPosition.item?.name.representation(in: Locale.current) ?? "\(orderPosition.itemIdentifier)" if let variationName = orderPosition.calculatedVariation?.name.representation(in: Locale.current) { ticketType.text = (ticketType.text ?? "") + " – \(variationName)" } secretLabel.text = orderPosition.secret guard let redemptionResponse = orderPosition.createRedemptionResponse(force: false, ignoreUnpaid: false, in: event, in: checkInList) else { statusBackgroundView.backgroundColor = Color.error statusLabel.text = Localization.TicketStatusViewController.InvalidTicket return } if redemptionResponse.status == .redeemed { statusBackgroundView.backgroundColor = Color.okay statusLabel.text = Localization.TicketStatusViewController.ValidTicket } else if redemptionResponse.errorReason == .alreadyRedeemed { statusBackgroundView.backgroundColor = Color.warning statusLabel.text = Localization.TicketStatusViewController.TicketAlreadyRedeemed } else if redemptionResponse.errorReason == .unpaid && checkInList.includePending { statusBackgroundView.backgroundColor = Color.okay statusLabel.text = redemptionResponse.errorReason?.localizedDescription() } else { statusBackgroundView.backgroundColor = Color.error statusLabel.text = redemptionResponse.errorReason?.localizedDescription() } } }
// // DexProvider.swift // adex // // Created by Sena on 29/04/20. // Copyright © 2020 Never Mind Dev. All rights reserved. // import Foundation import Moya public enum DexProvider { case manga(id: String) case chapter(id: String) } extension DexProvider: TargetType { public var baseURL: URL { URL(string: "https://mangadex.org/api/")! } public var path: String { switch self { case .manga(let id): return "manga/\(id)" case .chapter(let id): return "chapter/\(id)" } } public var method: Moya.Method { switch self { case .manga, .chapter: return .get } } public var sampleData: Data { return Data() } public var task: Task { switch self { case .manga, .chapter: return Task.requestPlain } } public var headers: [String : String]? { nil } }
// // AddVC.swift // Maniau // // Created by Ryan Kanno on 6/23/21. // import UIKit import FirebaseFirestore import FirebaseAuth protocol AddVCDelegate { func updateScheduleTable() } class AddVC: UIViewController { var delegate: AddVCDelegate? @IBOutlet private weak var loadingView: UIView! @IBOutlet private weak var loadingIndicator: UIActivityIndicatorView! var updateItem: Bool = false var oldId: String = "" @IBOutlet private weak var titleTF: UITextField! @IBOutlet private weak var descriptionTF: UITextField! @IBOutlet private weak var allDay: UISwitch! @IBOutlet private weak var datePicker: UIDatePicker! @IBOutlet private weak var startBtn: UIButton! @IBOutlet private weak var endBtn: UIButton! private var startWasTapped = false @IBOutlet private weak var repeatBtn: UIButton! @IBOutlet private weak var alertBtn: UIButton! @IBOutlet private weak var colorBtn: UIButton! @IBOutlet weak var pickerBackground: UIView! @IBOutlet weak var colorPickerView: UIView! @IBOutlet var colorButtons: [UIButton]! @IBOutlet private weak var pickerLabel: UILabel! @IBOutlet private weak var picker: UIPickerView! private var pickerIsSelected = false private var hrArray: [String] = [] private var minArray: [String] = [] private var ampmArray: [String] = ["AM", "PM"] private var time: (hr: String, min: String, amPm: String) = ("1", "00", "AM") private var timeToTransfer: String { return "\(time.hr):\(time.min) \(time.amPm)" } private var selectRepeatVC = SelectRepeatVC() private var selectAlertVC = SelectAlertVC() var event = ScheduledEvent( id: UUID().uuidString, title: "", description: "", startTime: "4:00 PM", endTime: "5:00 PM", repeats: "Never", alert: "None", relevantMonth: "", date: Date().formatDate(), selectedDay: Date().getSelectedDay(), dayOfWeek: Date().formatDayOfWeek(), color: "Teal") private var scheduleAdded = false private var date = Date() override func viewDidLoad() { super.viewDidLoad() selectRepeatVC.delegate = self selectAlertVC.delegate = self makePickerArrays() picker.delegate = self picker.dataSource = self datePicker.datePickerMode = .date let tapBackground = UITapGestureRecognizer( target: self, action: #selector(backgroundTapped)) pickerBackground.addGestureRecognizer(tapBackground) colorBtn.layer.cornerRadius = 3 titleTF.text = event.title } override func viewWillAppear(_ animated: Bool) { self.tabBarController?.tabBar.isHidden = true } override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .portrait } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? SelectRepeatVC { destination.delegate = self } else if let destination = segue.destination as? SelectAlertVC { destination.delegate = self } } @IBAction private func saveTapped(_ sender: UIBarButtonItem) { if titleTF.text != "" { displayLoading(with: loadingView, and: loadingIndicator) event.title = titleTF.text! event.description = descriptionTF.text ?? "" event.startTime = startBtn.title(for: .normal) ?? "12:00 AM" event.endTime = endBtn.title(for: .normal) ?? "12:01 AM" event.relevantMonth = date.getRelevantMonth() attemptToSaveData() } else { showError("Please give your event a title") } } private func attemptToSaveData() { if !updateItem { saveSequence() } else { updateSequence() } } private func saveSequence() { let id = Auth.auth().currentUser?.uid Firestore.firestore().collection(id!).document(event.id).setData(Utilities.convertScheduleToDict(event), merge: true) { [weak self] err in guard let self = self else { return } if let err = err { self.showError(err.localizedDescription) } else { print("Successfully saved document") LocalNotificationManager.setNotification(for: self.event) self.delegate?.updateScheduleTable() self.navigationController?.popToRootViewController(animated: true) } } } private func updateSequence() { let id = Auth.auth().currentUser?.uid Firestore.firestore().collection(id!).document(event.title).setData(Utilities.convertScheduleToDict(event), merge: false) { [weak self] err in guard let self = self else { return } if let err = err { self.showError(err.localizedDescription) } else { print("Successfully updated document") LocalNotificationManager.updateNotification( newEvent: self.event, oldId: self.oldId) self.delegate?.updateScheduleTable() self.navigationController?.popToRootViewController(animated: true) } } } @IBAction private func dateTapped(_ sender: UIDatePicker) { event.date = sender.date.formatDate() event.selectedDay = sender.date.getSelectedDay() event.dayOfWeek = sender.date.formatDayOfWeek() print("event.date: \(event.date)") } @IBAction private func displayPicker(_ sender: UIButton) { startWasTapped = sender.tag == 0 ? true : false pickerLabel.text = startWasTapped ? "Select Start Time" : "Select End Time" Animations.fadeInViews( background: pickerBackground, views: [pickerLabel, picker], collection: nil) pickerIsSelected = true } @IBAction private func colorTapped(_ sender: UIButton) { Animations.fadeInViews( background: pickerBackground, views: [colorPickerView], collection: colorButtons) } @objc private func backgroundTapped() { if pickerIsSelected { Animations.fadeOutViews( background: pickerBackground, views: [pickerLabel, picker], collection: nil) pickerIsSelected = false } else { Animations.fadeOutViews( background: pickerBackground, views: [colorPickerView], collection: colorButtons) } } @IBAction private func chosenColorTapped(_ sender: UIButton) { switch sender.tag { case 0: event.color = "Blue" case 1: event.color = "Teal" case 2: event.color = "Green" case 3: event.color = "Orange" case 4: event.color = "Red" case 5: event.color = "Yellow" case 6: event.color = "Gray" default: event.color = "Teal" } colorBtn.backgroundColor = Animations.convertColorString(event.color) Animations.fadeOutViews( background: pickerBackground, views: [colorPickerView], collection: colorButtons) } } extension AddVC: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField { case titleTF: titleTF.endEditing(true) return true case descriptionTF: descriptionTF.endEditing(true) return true default: return false } } } extension AddVC: UIPickerViewDelegate, UIPickerViewDataSource { func makePickerArrays() { for i in 1...12 { hrArray.append("\(i)") } for i in 0...60 { minArray.append("\(i)") } } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 3 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return hrArray.count case 1: return minArray.count case 2: return ampmArray.count default: return NSNotFound } } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { var attributedString: NSAttributedString! switch component { case 0: attributedString = NSAttributedString(string: hrArray[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) case 1: attributedString = NSAttributedString(string: minArray[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) case 2: attributedString = NSAttributedString(string: ampmArray[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) default: attributedString = nil } return attributedString } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: time.hr = "\(row + 1)" case 1: time.min = Utilities.formatMinutes(num: row) case 2: time.amPm = row == 0 ? "AM" : "PM" default: break } if startWasTapped { startBtn.setTitle(timeToTransfer, for: .normal) } else { endBtn.setTitle(timeToTransfer, for: .normal) } } } extension AddVC: SelectRepeatVCDelegate { func setRepeat(_ repeatSelection: String) { repeatBtn.setTitle(repeatSelection, for: .normal) } } extension AddVC: SelectAlertVCDelegate { func setAlert(_ alertSelection: String) { alertBtn.setTitle(alertSelection, for: .normal) } }
// // CompanyOfMapView.swift // Favorites Food // // Created by Pavel Kurilov on 01.11.2018. // Copyright © 2018 Pavel Kurilov. All rights reserved. // import MapKit import SnapKit class CompanyOfMapView: UIView { // MARK: - Init/Deinit CompanyOfMapView override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Create UIElements private let nameCompanyLabel: UILabel = { var companyLabel: UILabel = UILabel() companyLabel.translatesAutoresizingMaskIntoConstraints = false companyLabel.textColor = UIColor.mostlyBlackPink companyLabel.font = UIFont.systemFont(ofSize: 20) return companyLabel }() private let addressLabel: UILabel = { var addressLabel: UILabel = UILabel() addressLabel.translatesAutoresizingMaskIntoConstraints = false addressLabel.textColor = UIColor.mostlyBlackPink addressLabel.font = UIFont.systemFont(ofSize: 14) addressLabel.numberOfLines = 2 return addressLabel }() private let companyImageView: UIImageView = { var imageView: UIImageView = UIImageView() imageView.image = #imageLiteral(resourceName: "dish-image") imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView }() private let descriptionTextView: UITextView = { let textView = UITextView() textView.translatesAutoresizingMaskIntoConstraints = true textView.textColor = UIColor.veryDarkPink textView.font = UIFont.systemFont(ofSize: 14) textView.isScrollEnabled = false return textView }() private let difficultyStackView: UIStackView = { let stackView = UIStackView() stackView.axis = UILayoutConstraintAxis.horizontal stackView.alignment = UIStackViewAlignment.center stackView.distribution = UIStackViewDistribution.fillEqually stackView.translatesAutoresizingMaskIntoConstraints = false return stackView }() // MARK: - Configure CompanyOfMapView private func addCompanyImageView() { addSubview(companyImageView) companyImageView.snp.makeConstraints { (make) in make.left.top.equalTo(self).offset(Constant.offsetValue) make.right.equalTo(self).offset(-((self.frame.width / 2) - Constant.offsetValue)) make.height.equalTo(Constant.imageSizeValue) } } private func addNameCompanyLabel() { addSubview(nameCompanyLabel) nameCompanyLabel.snp.makeConstraints { (make) in make.top.equalTo(self).offset(Constant.offsetValue) make.left.equalTo(companyImageView.snp.right) make.right.equalTo(self).offset(-Constant.offsetValue) make.height.equalTo(Constant.imageSizeValue / 5) } } private func addAddressLabel() { addSubview(addressLabel) addressLabel.snp.makeConstraints { (make) in make.top.equalTo(nameCompanyLabel).offset(Constant.offsetValue / 2) make.left.right.equalTo(nameCompanyLabel) make.height.equalTo(32) } } private func addDescriptionTextView() { addSubview(descriptionTextView) descriptionTextView.snp.makeConstraints { (make) in make.top.equalTo(addressLabel).offset(Constant.offsetValue / 2) make.left.right.equalTo(addressLabel) make.bottom.equalTo(addressLabel) } } private func addDifficultyStackView() { addSubview(difficultyStackView) difficultyStackView.snp.makeConstraints { (make) in make.top.equalTo(companyImageView).offset(Constant.offsetValue / 2) make.left.equalTo(companyImageView) make.right.equalTo(descriptionTextView) make.height.equalTo(Constant.imageSizeValue / 2) } } func setupViews() { addCompanyImageView() addNameCompanyLabel() addAddressLabel() addDescriptionTextView() addDifficultyStackView() self.backgroundColor = .lightGrayishPink } // MARK: - configure data of cell func configure(with viewModel: CompanyDetailModelViewProtocol) { self.companyImageView.image = UIImage(data: viewModel.companyImage) self.nameCompanyLabel.text = viewModel.nameCompany self.addressLabel.text = viewModel.location.name self.descriptionTextView.text = viewModel.description } }
// // RouteMap.swift // iOS // // Created by Chris Sanders on 6/30/20. // import Foundation //struct RouteMapJSON: Codable { // let routes: [String: RouteMapJSON.Route] // // struct Route: Codable { // let id: String // let name: String // let color: String // let alternate_name: String // let routings: RouteMapJSON.Routing // // enum CodingKeys: String, CodingKey { // case id // case name // case color // case alternate_name // case routings // } // } // // struct Routing: Codable { // let north: [[String]] // let south: [[String]] // // enum CodingKeys: String, CodingKey { // case north // case south // } // } //} class RouteMap: ObservableObject { var name: String // var routeData: RouteMapJSON.Route { // Bundle.main.decode(RouteMapJSON.self, from: "route-map.json").routes["name"] // } init(name: String) { self.name = name } // func getRouteNumbers() -> [StationDetails] { // var stations = [StationDetails]() // print(Bundle.main.decode(RouteMapJSON, from: "route-map.json")) // return stations // } }
// Copyright 2019-2022 Spotify AB. // // 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 @testable import MobiusCore import Nimble import Quick private typealias Model = Int private enum Event: String, CustomStringConvertible { case increment case triggerEffect var description: String { return rawValue } } private enum Effect: String, CustomStringConvertible, Equatable { case testEffect var description: String { return rawValue } } class NonReentrancyTests: QuickSpec { // swiftlint:disable function_body_length override func spec() { describe("MobiusLoop") { var loop: MobiusLoop<Model, Event, Effect>! var messages: [String]! var handleEffect: ((Effect, EffectCallback<Event>) -> Void)! func log(_ message: String) { messages.append(message) } beforeEach { messages = [] let update = Update<Model, Event, Effect> { model, event in log("update enter - model: \(model) event: \(event)") defer { log("update exit - model: \(model) event: \(event)") } switch event { case .increment: return .next(model + 1) case .triggerEffect: return .dispatchEffects([.testEffect]) } } let testEffectHandler = AnyEffectHandler<Effect, Event> { handleEffect($0, $1) return AnonymousDisposable {} } let effectConnectable = EffectRouter<Effect, Event>() .routeEffects(equalTo: .testEffect).to(testEffectHandler) .asConnectable loop = Mobius.loop(update: update, effectHandler: effectConnectable) .start(from: 0) } sharedExamples("non-reentrant") { it("does not run update before the effect handler completes") { loop.dispatchEvent(.increment) loop.dispatchEvent(.increment) loop.dispatchEvent(.triggerEffect) // Despite the randomization in WorkBag, we must have two increments, one trigger, then two // increments, with no overlap. The last two increments can be run in either order, but the // effect is the same. let expectedMessages = [ "update enter - model: 0 event: increment", "update exit - model: 0 event: increment", "update enter - model: 1 event: increment", "update exit - model: 1 event: increment", "update enter - model: 2 event: triggerEffect", "update exit - model: 2 event: triggerEffect", "handle enter - effect: testEffect", "handle exit - effect: testEffect", "update enter - model: 2 event: increment", "update exit - model: 2 event: increment", "update enter - model: 3 event: increment", "update exit - model: 3 event: increment", ] expect(messages).to(equal(expectedMessages)) } } context("when effect handler posts events through consumer") { beforeEach { handleEffect = { effect, callback in log("handle enter - effect: \(effect)") defer { log("handle exit - effect: \(effect)") } callback.send(.increment) callback.send(.increment) callback.end() } } itBehavesLike("non-reentrant") } context("when effect handler dispatches effects directly") { // Like above, but calls loop.dispatchEvent. This is an antipattern, but is here to simulate the effect // of events coming in through the view connection of a MobiusController. beforeEach { handleEffect = { effect, _ in log("handle enter - effect: \(effect)") defer { log("handle exit - effect: \(effect)") } loop.dispatchEvent(.increment) loop.dispatchEvent(.increment) } } itBehavesLike("non-reentrant") } } } }
// Copyright © 2019 Zappit. All rights reserved. import CoreLocation import Foundation struct GeoOffersGeoFence: Codable { let logoImageUrl: String let scheduleID: ScheduleID let scheduleDeviceID: String let latitude: Double let longitude: Double let radiusKm: Double var radiusMeters: Double { return radiusKm * 1000 } let notificationTitle: String let notificationMessage: String let notificationDwellDelayMs: Double var notificationDwellDelaySeconds: Double { return notificationDwellDelayMs / 1000 } let notificationDeliveryDelayMs: Double var notificationDeliveryDelaySeconds: Double { return notificationDeliveryDelayMs / 1000 } let doesNotNotify: Bool let notifiesSilently: Bool var regionIdentifier: String { return "\(scheduleID)_\(scheduleDeviceID)" } var key: String { return String(scheduleID) } var location: CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } var cirularRegion: CLCircularRegion { return CLCircularRegion(center: coordinate, radius: radiusMeters, identifier: key) } enum CodingKeys: String, CodingKey { case logoImageUrl case scheduleID = "scheduleId" case scheduleDeviceID = "deviceUid" case latitude = "lat" case longitude = "lng" case radiusKm case notificationTitle = "customEntryNotificationTitle" case notificationMessage = "customEntryNotificationMessage" case notificationDwellDelayMs = "loiteringDelayMs" case notificationDeliveryDelayMs = "deliveryDelayMs" case doesNotNotify case notifiesSilently } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) logoImageUrl = try values.decode(String.self, forKey: .logoImageUrl) if let scheduleIDString = try? values.decode(String.self, forKey: .scheduleID), let scheduleIDInt = Int(scheduleIDString) { scheduleID = scheduleIDInt } else { scheduleID = try values.decode(Int.self, forKey: .scheduleID) } scheduleDeviceID = try values.decode(String.self, forKey: .scheduleDeviceID) if let latitudeString = try? values.decode(String.self, forKey: .latitude), let latitudeDouble = Double(latitudeString) { latitude = latitudeDouble } else { latitude = Double(try values.decode(Double.self, forKey: .latitude)) } if let longitudeString = try? values.decode(String.self, forKey: .longitude), let longitudeDouble = Double(longitudeString) { longitude = longitudeDouble } else { longitude = Double(try values.decode(Double.self, forKey: .longitude)) } if let radiusKmString = try? values.decode(String.self, forKey: .radiusKm) { radiusKm = Double(radiusKmString) ?? 1 } else { radiusKm = try values.decode(Double.self, forKey: .radiusKm) } notificationTitle = try values.decodeIfPresent(String.self, forKey: .notificationTitle) ?? "" notificationMessage = try values.decodeIfPresent(String.self, forKey: .notificationMessage) ?? "" if let delayString = try? values.decode(String.self, forKey: .notificationDeliveryDelayMs) { notificationDeliveryDelayMs = Double(delayString) ?? 0 } else { notificationDeliveryDelayMs = try values.decodeIfPresent(Double.self, forKey: .notificationDeliveryDelayMs) ?? 0 } if let delayString = try? values.decode(String.self, forKey: .notificationDwellDelayMs) { notificationDwellDelayMs = Double(delayString) ?? 0 } else { notificationDwellDelayMs = try values.decodeIfPresent(Double.self, forKey: .notificationDwellDelayMs) ?? 0 } doesNotNotify = try values.decode(Bool.self, forKey: .doesNotNotify) notifiesSilently = try values.decode(Bool.self, forKey: .notifiesSilently) } }
// // Event.swift // SyllaSync // // Created by Joel Wasserman on 8/7/15. // Copyright (c) 2015 IVET. All rights reserved. // import UIKit public class Event: NSObject { public var UUID:String? public var eventDescription:String? public var type:String? public var date:String? public var time:String? public var title:String? public var weight:Int? public var syllabus:String? public var className:String? public var location:String? public var newEvent:Bool? public var group:String? public var price:String? }
// // UIView+Animation.swift // WavesWallet-iOS // // Created by mefilt on 18.09.2018. // Copyright © 2018 Waves Platform. All rights reserved. // import UIKit public extension UIView { public static let fastDurationAnimation: TimeInterval = 0.24 func shake() { self.transform = CGAffineTransform(translationX: 20, y: 0) UIView.animate(withDuration: UIView.fastDurationAnimation, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 1, options: .curveEaseInOut, animations: { self.transform = CGAffineTransform.identity }, completion: nil) } }
// // Coredata.swift // Personality // // Created by Luis Henrique Grassi on 27/10/17. // Copyright © 2017 lhmgrassi. All rights reserved. // import UIKit import CoreData class CoreDataHelper: NSObject { static let shared = CoreDataHelper() // MARK: - Private properties private let dataModelName = "Personality" private lazy var applicationDocumentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() private lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = Bundle.main.url(forResource: self.dataModelName, withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("\(self.dataModelName).sqlite") do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { assertionFailure("Unresolved error") } return coordinator }() // MARK: - Public properties lazy var context: NSManagedObjectContext = { var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator return managedObjectContext }() } extension CoreDataHelper { // MARK: - Fetch func fetch<T>(fetchRequest: NSFetchRequest<NSFetchRequestResult>, forEntity: T.Type) -> [T]? where T: NSManagedObject { do { return try self.context.fetch(fetchRequest) as? [T] } catch { assertionFailure("Unresolved error") return nil } } func getAllObjects<T>(for entity: T.Type) -> [T]? where T: NSManagedObject { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: NSStringFromClass(T.self)) return self.fetch(fetchRequest: fetchRequest, forEntity: entity) } func get<T>(for entity: T.Type, withPredicate: NSPredicate) -> [T]? where T: NSManagedObject { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: NSStringFromClass(T.self)) fetchRequest.predicate = withPredicate return self.fetch(fetchRequest: fetchRequest, forEntity: entity) } // MARK: - Insert func insertNewObject<T>(entity: T.Type) -> T where T : NSManagedObject { guard let entity = NSEntityDescription.insertNewObject(forEntityName: NSStringFromClass(T.self), into: self.context) as? T else { assertionFailure("It was not possible to insert the new object \(NSStringFromClass(T.self))") return T() } return entity } // MARK: - Save func saveContext() -> Bool { if context.hasChanges { do { try context.save() } catch { assertionFailure("Unresolved error") return false } } return true } }
// // SCSNews.swift // leShou365 // // Created by Bella on 15/8/20. // Copyright © 2015年 SmallCobblerStudio. All rights reserved. // import UIKit class SCSNews: NSObject { var newsClassType:String? var newsTitle:String? var newsNumber:String? var newsUpdateDate:String? var newsContent:String? var newsID:String? var newsImg:String? init(dict:[String:AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} // MARK: --加载新闻信息 class func loadNewsList(newsTypeID:String,finished: (dataList: NSMutableArray?, error: NSError?) -> ()) { let urlPath="http://117.34.95.165:8082/AppWebServer.asmx/GetNewsList?newsClassID=\(newsTypeID)" SCSNetworkTools.requestJSON(Method.POST, URLString: urlPath, parameters: nil) { (json, error) -> () in if error != nil { finished(dataList: nil, error: error) return } if let array = json?["result"] as? [[String: AnyObject]] { // 遍历数组,字典转模型 let list:NSMutableArray = NSMutableArray() for dict in array { list.addObject(SCSNews(dict: dict)) } list.sortedArrayUsingComparator({ (obj1, obj2) -> NSComparisonResult in let o1:SCSNewsType=obj1 as! SCSNewsType let o2:SCSNewsType=obj2 as! SCSNewsType return (o1.newsClassTypeID?.compare(o2.newsClassTypeID!))! }) // 获得完整的微博数组,可以回调 finished(dataList: list, error: nil) } else { finished(dataList: nil, error: nil) } } } }
// // LatoApp.swift // Lato // // Created by juandahurt on 30/01/21. // import SwiftUI import AVFoundation @main struct LatoApp: App { var body: some Scene { WindowGroup { MainView() .environmentObject(UserSettings()) } } }
// // ViewController.swift // backbeam // // Created by James Tang on 28/7/14. // Copyright (c) 2014 James Tang. All rights reserved. // import UIKit class ViewController: UIViewController { var request = BBBackbeamRequest() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. request.secret = "<# your app's secret #>" request.key = "<# your app's key #>" request.method = "GET" request.nonce = "6303cd9bf27d27eb6343427ac42365b38b09f112" request.path = "/data/user" // customize to your entity request.time = "1397166331409" request.env = "dev" request.project = "<# your project #>" request.optionals["limit"] = 1 request.send { (data, response, error) in println("data \(data), response \(response), error \(error)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
import UIKit /** * Copyright 2019 Tim Jordan, * * This software is the intellectual property of the author, and can not be * distributed, used, copied, or reproduced, in whole or in part, for any * purpose, commercial or otherwise. The author grants the ASU Software * Engineering program the right to copy, execute, and evaluate this work for * the purpose of determining performance of the author in coursework, and for * Software Engineering program evaluation, so long as this copyright and * right-to-use statement is kept in-tact in such use. All other uses are * prohibited and reserved to the author.<br> * <br> * * Purpose: View controller for UITableView. * * SER 423 * see http://quay.poly.asu.edu/Mobile/ * @author Tim Jordan mailto:tsjorda1@asu.edu * Software Engineering * @version November 24, 2019 */ class PlacesTableViewController: UITableViewController { var viewController: ViewController? override func viewDidLoad() { super.viewDidLoad() viewController = tabBarController as? ViewController tableView.dataSource = viewController viewController?.tableViewController = self self.navigationItem.leftBarButtonItem = self.editButtonItem let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(PlacesTableViewController.addPlace)) self.navigationItem.rightBarButtonItem = addButton } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "PlaceDescriptionSegue") { let placeDetailsViewController: PlaceDetailsViewController = segue.destination as! PlaceDetailsViewController let indexPath = self.tableView.indexPathForSelectedRow! let tempPlaceDescription: PlaceDescription = PlaceDescription() tempPlaceDescription.name = "Loading Place Details..." placeDetailsViewController.placeDescription = tempPlaceDescription placeDetailsViewController.currentPlaceIndex = indexPath.row placeDetailsViewController.placeName = viewController?.placeNames[indexPath.row] } } @objc func addPlace() { print("add button clicked") let promptND = UIAlertController(title: "New Place", message: "Enter New Place Name", preferredStyle: UIAlertController.Style.alert) promptND.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil)) promptND.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: { (action) -> Void in let newPlaceName:String = (promptND.textFields?[0].text == "") ? "unknown" : (promptND.textFields?[0].text)! let newPlace:PlaceDescription = PlaceDescription() newPlace.name = newPlaceName let placesConnect: PlaceLibraryStub = PlaceLibraryStub(urlString: (self.viewController?.urlString)!) let _:Bool = placesConnect.add(placeDescription: newPlace, callback: {(res: String, err: String?) -> Void in if err != nil { NSLog(err!) }else{ NSLog(res) self.viewController?.populatePlaceNames() } }) self.tableView.reloadData() })) promptND.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = "Place Name" }) present(promptND, animated: true, completion: nil) } }
// // LevelSelectionViewController.swift // GU Memory // // Created by Sammy on 11/21/18. // Copyright © 2018 Sammy. All rights reserved. // import UIKit class LevelSelectionViewController: UIViewController { @IBOutlet var levelSelectionLabel: UILabel! @IBOutlet var easyButton: UIButton! @IBOutlet var mediumButton: UIButton! @IBOutlet var hardButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. easyButton.layer.cornerRadius = 10 mediumButton.layer.cornerRadius = 10 hardButton.layer.cornerRadius = 10 let alertControllerNotValidInput = UIAlertController(title: "Game Rules", message: "To begin a game, select the level you would like to play. The easy level is played with 8 cards, the medium level with 16 cards and the hard level with 32 cards. Click on any 2 cards. If the two cards match, you will be awarded points which are added to your score and the cards will stay flipped over. The points added to your score gets lower as it you have non-matches. Otherwise, the cards are flipped back over and you try again. The game is over when all the cards have been matched. To play again, select the \"Play Again\" button. ", preferredStyle: .alert) alertControllerNotValidInput.addAction(UIAlertAction(title: "Got it!", style: .default, handler: nil)) present(alertControllerNotValidInput, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { if identifier == "Level Selection Segue" { } } } }
// // ListPatientCell.swift // HISmartPhone // // Created by MACOS on 12/21/17. // Copyright © 2017 MACOS. All rights reserved. // import UIKit class ListPatientCell: BaseTableViewCell { var index: Int = 0 { didSet { self.orderNumberLabel.text = index.description } } var patient: Patient? { didSet { self.patientCodeLabel.text = self.patient?.patient_ID self.nameLabel.text = self.patient?.patient_Name self.DOBLabel.text = self.patient?.birth_Date.getDescription_DDMMYYYY() self.phoneNumberLabel.text = self.patient?.mobile_Phone let alarmStatus = self.patient?.alarmStatus ?? .null switch alarmStatus { case .null: self.circleView.backgroundColor = Theme.shared.normalStatisticColor break case .low: self.circleView.backgroundColor = Theme.shared.lowStatisticColor break case .normal: self.circleView.backgroundColor = Theme.shared.normalStatisticColor break case .preHigh: self.circleView.backgroundColor = Theme.shared.hightStatisticColor break case .high: self.circleView.backgroundColor = Theme.shared.veryHightStatisticColor break } } } //MARK: UIControl private let orderNumberLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.textColor = Theme.shared.darkBlueTextColor label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize) return label }() private let patientCodeLabel: UILabel = { let label = UILabel() label.textAlignment = .left label.textColor = Theme.shared.darkBlueTextColor label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize, weight: UIFont.Weight.medium) return label }() private let nameLabel: UILabel = { let label = UILabel() label.textAlignment = .left label.textColor = Theme.shared.darkBlueTextColor label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize) return label }() private let DOBLabel: UILabel = { let label = UILabel() label.textAlignment = .left label.textColor = Theme.shared.darkBlueTextColor label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize) return label }() private let phoneNumberLabel: UILabel = { let label = UILabel() label.textAlignment = .right label.textColor = Theme.shared.darkBlueTextColor label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize) return label }() private let circleView: UIView = { let viewConfig = UIView() viewConfig.backgroundColor = Theme.shared.heartRateChartColor viewConfig.layer.cornerRadius = Dimension.shared.widthStatusCircle / 2 viewConfig.layer.masksToBounds = true return viewConfig }() private let lineDivider: UIView = { let viewConfig = UIView() viewConfig.backgroundColor = Theme.shared.lightBlueLineDivider return viewConfig }() //MARK: Initialize function override func setupView() { self.setupViewOderNumber() self.setupViewPatientcodeLabel() self.setupViewNameLabel() self.setupViewDOBLabel() self.setupViewPhoneLabel() self.setupViewStatusCircle() self.setupViewLineDivider() } //MARK: SetupView function private func setupViewOderNumber() { self.addSubview(self.orderNumberLabel) if #available(iOS 11, *) { self.orderNumberLabel.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(Dimension.shared.mediumVerticalMargin) make.left.equalTo(self.safeAreaLayoutGuide).offset(Dimension.shared.normalVerticalMargin) } } else { self.orderNumberLabel.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(Dimension.shared.mediumVerticalMargin) make.left.equalToSuperview().offset(Dimension.shared.normalVerticalMargin) } } } private func setupViewPatientcodeLabel() { self.addSubview(self.patientCodeLabel) if #available(iOS 11, *) { self.patientCodeLabel.snp.makeConstraints { (make) in make.top.equalTo(self.orderNumberLabel) make.left.equalTo(self.safeAreaLayoutGuide).offset(77 * Dimension.shared.widthScale) } } else { self.patientCodeLabel.snp.makeConstraints { (make) in make.top.equalTo(self.orderNumberLabel) make.left.equalToSuperview().offset(77 * Dimension.shared.widthScale) } } } private func setupViewNameLabel() { self.addSubview(self.nameLabel) self.nameLabel.snp.makeConstraints { (make) in make.top.equalTo(self.patientCodeLabel.snp.bottom).offset(Dimension.shared.smallVerticalMargin) make.left.equalTo(self.patientCodeLabel) } } private func setupViewDOBLabel() { self.addSubview(self.DOBLabel) self.DOBLabel.snp.makeConstraints { (make) in make.top.equalTo(self.nameLabel.snp.bottom).offset(Dimension.shared.smallVerticalMargin) make.left.equalTo(self.nameLabel) make.bottom.equalToSuperview().offset(-Dimension.shared.mediumVerticalMargin) } } private func setupViewPhoneLabel() { self.addSubview(self.phoneNumberLabel) if #available(iOS 11, *) { self.phoneNumberLabel.snp.makeConstraints { (make) in make.top.equalTo(self.orderNumberLabel) make.right.equalTo(self.safeAreaLayoutGuide).offset(-Dimension.shared.mediumHorizontalMargin) } } else { self.phoneNumberLabel.snp.makeConstraints { (make) in make.top.equalTo(self.orderNumberLabel) make.right.equalToSuperview().offset(-Dimension.shared.mediumHorizontalMargin) } } } private func setupViewStatusCircle() { self.addSubview(self.circleView) self.circleView.snp.makeConstraints { (make) in make.width.height.equalTo(Dimension.shared.widthStatusCircle) make.right.equalTo(self.phoneNumberLabel) make.top.equalTo(self.phoneNumberLabel.snp.bottom).offset(Dimension.shared.mediumVerticalMargin) } } private func setupViewLineDivider() { self.addSubview(self.lineDivider) self.lineDivider.snp.makeConstraints { (make) in make.width.equalToSuperview().offset(-Dimension.shared.smallHorizontalMargin) make.centerX.equalToSuperview() make.bottom.equalToSuperview() make.height.equalTo(Dimension.shared.heightLineDivider) } } }
// // Day.swift // WhatsNext // // Created by MetroStar on 8/9/17. // Copyright © 2017 TamerBader. All rights reserved. // import UIKit class Day: NSObject { private var weekday:Weekday! private var month:Month! private var dayNumber:Int! private var dayTimestamp:Date! private lazy var tasks:Array<Task> = Array<Task>() var Weekday:String { get {return weekday.rawValue} } var Month: String { get{return month.rawValue} } var DayNumber: Int { get{return dayNumber} set{dayNumber = newValue} } var Timestamp: Date { get{return dayTimestamp} } var Tasks: [Task] { get{return tasks} } init(timestamp:Date) { dayTimestamp = timestamp let result = Day.extractDayDetailsFromTimestamp(timestamp: timestamp) dayNumber = result[0] as! Int weekday = result[1] as! Weekday month = result[2] as! Month } func addTask(newTask: Task) { tasks.append(newTask) } static func extractDayDetailsFromTimestamp (timestamp:Date) -> [Any] { var dayDetails:Array<Any> = Array<Any>() let calendar:Calendar = Calendar.current let components = calendar.dateComponents([.day, .month, .weekday], from: timestamp) let day = components.day let month = components.month let weekday = components.weekday let currentWeekday:Weekday let currentMonth:Month print("Day is \(day ?? 0) and month is \(month ?? 0) weekday is \(weekday ?? 0)") switch weekday! { case 1: currentWeekday = .SUNDAY case 2: currentWeekday = .MONDAY case 3: currentWeekday = .TUESDAY case 4: currentWeekday = .WEDNESDAY case 5: currentWeekday = .THURSDAY case 6: currentWeekday = .FRIDAY case 7: currentWeekday = .SATURDAY default: currentWeekday = .SUNDAY print("UNKNOWN DAY") } switch month! { case 1: currentMonth = .JANUARY case 2: currentMonth = .FEBRUARY case 3: currentMonth = .MARCH case 4: currentMonth = .APRIL case 5: currentMonth = .MAY case 6: currentMonth = .JUNE case 7: currentMonth = .JULY case 8: currentMonth = .AUGUST case 9: currentMonth = .SEPTEMBER case 10: currentMonth = .OCTOBER case 11: currentMonth = .NOVEMBER case 12: currentMonth = .DECEMBER default: currentMonth = .JANUARY print("UNKNOWN Month") } dayDetails.append(day!) dayDetails.append(currentWeekday) dayDetails.append(currentMonth) return dayDetails } }
// // Round.swift // ARCUS // // Created by Sean Perez on 3/26/17. // Copyright © 2017 Leslie Chicoine. All rights reserved. // import Foundation class Round { var roundArray = [Shot]() var currentEnding = [Double]() var roundScores = [[Double]]() var sumScore: Double { return roundArray.reduce(0) { $0 + $1.score } } func numberString() -> String { var string = "" for value in roundArray { string.append(" \(Int(value.score))") } return string } }
// // AlgoliaCommand.swift // // // Created by Vladislav Fitc on 10.03.2020. // import Foundation protocol AlgoliaCommand { var method: HTTPMethod { get } var callType: CallType { get } var path: URL { get } var body: Data? { get } var requestOptions: RequestOptions? { get } } extension AlgoliaCommand { var body: Data? { return nil } }
// // CharactersViewModel.swift // CodeHeroCharacters // // Created by Rafael Escaleira on 17/07/21. // import Foundation import CodeHeroAPI import CodeHeroModels import CodeHeroPagination import RxCocoa import RxSwift public class CharactersViewModel: NSObject, UISearchResultsUpdating, UISearchBarDelegate, PaginationDelegate { var service: CharacterServiceProtocol var bindScrollToTop: () -> () = { } var bindMode: (Mode) -> () = { mode in } var findHeroName: String? var maxOffset: Int = 4 let character = BehaviorRelay<[Character.CharacterData.Result]>(value: []) let disposeBag = DisposeBag() enum Mode { case search, normal } private (set) var offset: Int = 1 private (set) var currentPageFind: Int = 1 init(query: CharacterQuery = .characters(orderBy: .descModified, offset: 1)) { self.service = CharacterService(query: query) super.init() self.fetchCharacters(query: query) } private func fetchCharacters(query: CharacterQuery) { self.service = CharacterService(query: query) self.service.fetchCharacterData { result in switch result { case .failure(let error): print(error.localizedDescription) case .success(let characters): self.character.accept(characters?.data?.results ?? []) self.maxOffset = (characters?.data?.total ?? 16) / 4 } } } public func updateSearchResults(for searchController: UISearchController) { if let searchText = searchController.searchBar.text, searchText.isEmpty == false { self.findHeroName = searchText self.fetchCharacters(query: .characters(nameStartsWith: searchText, orderBy: .ascName, limit: 4, offset: ((self.currentPageFind - 1) * 4) + 1)) self.bindMode(.search) } else { self.findHeroName = nil self.currentPageFind = 1 self.fetchCharacters(query: .characters(orderBy: .descModified, limit: 4, offset: ((self.offset - 1) * 4) + 1)) self.bindMode(.normal) } } public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { self.currentPageFind = 1 self.findHeroName = nil self.fetchCharacters(query: .characters(orderBy: .descModified, limit: 4, offset: ((self.offset - 1) * 4) + 1)) self.bindMode(.normal) } public func pagination(didSelected offset: Int) { if self.findHeroName?.isEmpty == false { self.currentPageFind = offset } else { self.offset = offset } self.bindScrollToTop() self.fetchCharacters(query: .characters(nameStartsWith: self.findHeroName, orderBy: .descModified, limit: 4, offset: ((offset - 1) * 4) + 1)) } }
// // CountryCell.swift // Task4 // // Created by neoviso on 8/9/21. // import UIKit class CountryCell: UITableViewCell { @IBOutlet weak var countryNameLabel: UILabel! @IBOutlet weak var countryFlagImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // EventStream.swift // Nifty // // Copyright © 2016 ElvishJerricco. All rights reserved. // import DispatchKit /// The ChannelWriter class writes values to a channel. /// It's a reference type so `Channel`s have a common object to add handlers to. public class ChannelWriter<T> { /// A threadsafe array of handlers attached to this writer. private var handlersLock = Lock<[T -> ()]>([]) /// Initializes an empty ChannelWriter public init() { } /// - parameter handler: A function to be called when a value is written. public func addHandler(handler: T -> ()) { self.handlersLock.acquire { (inout handlers: [T -> ()]) in handlers.append(handler) } } /// Asynchronously and concurrently writes a value to all attached handlers. /// /// - Note: If the queue passed is not concurrent, /// handlers will not be called concurrently. /// /// - parameter value: The value to write /// - parameter queue: The queue to execute handlers on /// /// - returns: A `Future` that will complete when all handlers have exited. public func write( value: T, queue: DispatchQueue = Dispatch.globalQueue ) -> Future<()> { return self.handlersLock.acquire { (inout handlers: [T -> ()]) in queue.apply(handlers.count) { index in handlers[index](value) } handlers = [] } } /// A `Channel` which will receive values written to this writer. public var channel: Channel<T> { return Channel(self.addHandler) } } /// A `Channel` is a frontend for receiving values written to a `ChannelWriter`. /// A `Channel` provides an interface for adding handlers for these values, /// as well as ways to create new `Channels` that /// change values before passing them to handlers. /// Each handler is only ever called once; /// with the next value the channel receives after adding it. public struct Channel<T> { public let cont: Continuation<(), T> public init(_ cont: Continuation<(), T>) { self.cont = cont } public init(_ cont: (T -> ()) -> ()) { self.cont = Continuation(cont) } } // MARK: Functor public extension Channel { /// Functor fmap. /// /// Maps this channel to a channel of another type. /// /// - parameter mapper: The function to map values of this channel with. /// /// - returns: A channel that receives mapped values from this channel. public func map<U>(mapper: T -> U) -> Channel<U> { return Channel<U>(self.cont.map(mapper)) } } /// Operator for `Channel.map` /// /// - see: `Channel.map` public func <^><T, U>(f: T -> U, channel: Channel<T>) -> Channel<U> { return channel.map(f) } // MARK: Applicative public extension Channel { /// Applicative <*> /// /// Applies functions in another channel to values passed to this channel. /// After `mappers` passes a function, /// the next value passed to self is passed to that function. /// The resulting value is passed to the returned channel. /// /// - parameter mappers: The channel of functions to map with. /// /// - returns: A channel that receives values that /// have been passed through functions received from the `mappers` channel. public func apply<U>(mappers: Channel<T -> U>) -> Channel<U> { return Channel<U>(self.cont.apply(mappers.cont)) } } /// Operator for `Channel.apply` /// /// - see: `Channel.apply` public func <*><A, B>(f: Channel<A -> B>, a: Channel<A>) -> Channel<B> { return a.apply(f) } // MARK: Monad public extension Channel { /// Monad return. /// /// - parameter value: The value to make a channel around. /// /// - returns: A channel that calls all handlers with the same value. public static func of<T>(value: T) -> Channel<T> { return Channel<T>(Continuation.of(value)) } /// Monad bind. /// /// Maps each value received by this channel to a channel, /// and passes values of that channel to the returned channel. /// /// - parameter mapper: The function to map values with. /// /// - returns: A channel that will receive all values of /// the channels that the mapper returns. public func flatMap<U>(mapper: T -> Channel<U>) -> Channel<U> { return Channel<U>(self.cont.flatMap { mapper($0).cont }) } } /// Operator for `Channel.flatMap` /// /// - see: `Channel.flatMap` public func >>==<T, U>(channel: Channel<T>, f: T -> Channel<U>) -> Channel<U> { return channel.flatMap(f) } // MARK: Monoid public extension Channel { /// - returns: A channel that never receives any values. public static func empty<T>() -> Channel<T> { return Channel<T> { _ in } } /// - parameter other: A channel to append with this one. /// /// - returns: A channel that receives all values that /// either this channel or the `other` channel receives. public func appended(other: Channel<T>) -> Channel<T> { return Channel<T> { handler in self.addHandler(handler) other.addHandler(handler) } } } /// Operator for `Channel.appended` /// /// - see: `Channel.appended` public func +<T>(a: Channel<T>, b: Channel<T>) -> Channel<T> { return a.appended(b) } // MARK: Util public extension Channel { /// - parameter predicate: A test for values received by this channel. /// /// - returns: A channel that only receives values that pass the predicate. public func filter(predicate: T -> Bool) -> Channel<T> { return self.flatMap { value in if predicate(value) { return Channel.of(value) } else { return self.filter(predicate) } } } } // MARK: Run public extension Channel { /// - parameter handler: Receives the next value this channel receives. public func addHandler(handler: T -> ()) { self.cont.run(handler) } /// - returns: A future representing the next value this channel receives. public func next() -> Future<T> { let promise = Promise<T>() self.addHandler { promise.complete($0) } return promise.future } }
// // Enum+CurrentCellType.swift // WeatherAPP // // Created by hyeri kim on 12/08/2019. // Copyright © 2019 hyeri kim. All rights reserved. // import UIKit enum CurrentCellType: Int { case TimesCell = 0 case DetailCell case DaysCell } extension CurrentCellType { var cellType: UITableViewCell.Type { switch self { case .DaysCell: return DaysTableViewCell.self case .DetailCell: return DetailTableViewCell.self case .TimesCell: return CurrentWeatherTimesTableViewCell.self } } }
// // AppDelegate.swift // TorusDirectSDKDemo // // Created by Shubham on 24/4/20. // Copyright © 2020 Shubham. All rights reserved. // import UIKit import OHHTTPStubs //import Atlantis class AppDelegate: UIResponder, UIApplicationDelegate, UISceneDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // print("starting atlantis") // Atlantis.start() let stubs = registerStubs() HTTPStubs.setEnabled(true) HTTPStubs.setEnabled(true, for: URLSession.shared.configuration) print("Installed HTTPStubs stubs: \(HTTPStubs.allStubs())") HTTPStubs.onStubActivation { (request: URLRequest, stub: HTTPStubsDescriptor, response: HTTPStubsResponse) in print("[OHHTTPStubs][stubbed] Request to \(request.url!) has been stubbed with \(String(describing: stub.name)), body: \(request.ohhttpStubs_httpBody)") } HTTPStubs.onStubMissing{request in print("[OHHTTPStubs][missing] Request to \(request.url!) is missing stubs.") print("[OHHTTPStubs][missing] Request info: \(request.description), \(request.url!.host!), \(request.debugDescription), \(String(decoding: request.ohhttpStubs_httpBody ?? Data.init(), as: UTF8.self)), \(String(describing: request.allHTTPHeaderFields)), \(String(describing: request.httpMethod))") } 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. let sceneConfig = UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) sceneConfig.delegateClass = SceneDelegate.self return sceneConfig } 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. } }
// // UserRegister.swift // HISmartPhone // // Created by DINH TRIEU on 1/9/18. // Copyright © 2018 MACOS. All rights reserved. // import UIKit struct BloodPressure { var low: Int var preHigh: Int var high: Int mutating func setValue(low: Int, preHigh: Int, high: Int) { self.low = low self.preHigh = preHigh self.high = high } func CheckValue() -> Bool { if self.low <= 0 { return false } if self.preHigh <= 0 { return false } if self.high <= 0 { return false } if self.low > 500 { return false } if self.preHigh > 500 { return false } if self.high > 500 { return false } return true } } class Patient: Mapper { private (set) var PID_ID: String private (set) var patient_ID: String private (set) var patient_Password: String private (set) var patient_Name: String private (set) var birth_Date: Date private (set) var address_ID: Int private (set) var idCard_Number: Int private (set) var sex_ID: Gender private (set) var occupation: String private (set) var mobile_Phone: String private (set) var email: String private (set) var status: Int private (set) var image: String private (set) var remove: Int private (set) var access_Lasttime: Date private (set) var access_Status: String private (set) var acc_Status: String private (set) var alarmStatus: AlarmStatus private (set) var bloodType: String private (set) var TBPM_ID: String private (set) var lowSystolic: Int private (set) var lowDiastolic: Int private (set) var preHighSystolic: Int private (set) var preHighDiastolic: Int private (set) var highSystolic: Int private (set) var highDiastolic: Int private (set) var BPOPatient: BPOPatient? private (set) var address: Address? private (set) var doctorsFollow: [User]? private (set) var mainDoctor: MainDoctor? init() { self.PID_ID = "" self.patient_ID = "" self.patient_Password = "" self.patient_Name = "" self.birth_Date = Date() self.address_ID = 0 self.idCard_Number = 0 self.sex_ID = .male self.occupation = "" self.mobile_Phone = "" self.email = "" self.status = 0 self.acc_Status = "" self.image = "" self.remove = 0 self.access_Status = "" self.access_Lasttime = Date() self.alarmStatus = AlarmStatus.low self.bloodType = "" self.TBPM_ID = "" self.lowSystolic = 0 self.lowDiastolic = 0 self.preHighSystolic = 0 self.preHighDiastolic = 0 self.highSystolic = 0 self.highDiastolic = 0 } init(from data: Patient) { self.PID_ID = data.PID_ID self.patient_ID = data.patient_ID self.patient_Password = data.patient_Password self.patient_Name = data.patient_Name self.birth_Date = data.birth_Date self.address_ID = data.address_ID self.idCard_Number = data.idCard_Number self.sex_ID = data.sex_ID self.occupation = data.occupation self.mobile_Phone = data.mobile_Phone self.email = data.email self.status = data.status self.acc_Status = data.acc_Status self.image = data.image self.remove = data.remove self.access_Status = data.access_Status self.access_Lasttime = data.access_Lasttime self.alarmStatus = data.alarmStatus self.bloodType = data.bloodType self.TBPM_ID = data.TBPM_ID self.lowSystolic = data.lowSystolic self.lowDiastolic = data.lowDiastolic self.preHighSystolic = data.preHighSystolic self.preHighDiastolic = data.preHighDiastolic self.highSystolic = data.highSystolic self.highDiastolic = data.highDiastolic self.address = data.address self.BPOPatient = data.BPOPatient self.doctorsFollow = data.doctorsFollow } required init(_ data: [String : Any]) { self.PID_ID = data["PID_ID"] as? String ?? "" self.patient_ID = data["Patient_ID"] as? String ?? "" self.patient_Password = data["Patient_Password"] as? String ?? "" self.patient_Name = data["Patient_Name"] as? String ?? "" self.birth_Date = (data["Birth_Date"] as? String ?? "").getDate() self.idCard_Number = data["IdCard_Number"] as? Int ?? 0 self.address_ID = data["Address_ID"] as? Int ?? 0 self.sex_ID = Gender(rawValue: data["Sex_ID"] as? Int ?? 0) ?? .male self.occupation = data["Occupation"] as? String ?? "" self.mobile_Phone = data["Mobile_Phone"] as? String ?? "" self.email = data["Email"] as? String ?? "" self.status = data["Status"] as? Int ?? 0 self.image = data["Image"] as? String ?? "" self.remove = data["Remove"] as? Int ?? 0 self.access_Lasttime = (data["Access_LastTime"] as? String ?? "").getDate() self.access_Status = data["Acc_Status"] as? String ?? "" self.alarmStatus = AlarmStatus(rawValue: data["AlarmStatus"] as? Int ?? 0) ?? .null self.bloodType = data["BloodType"] as? String ?? "" self.TBPM_ID = data["TBPM_ID"] as? String ?? "" self.lowSystolic = data["LowSystolic"] as? Int ?? 0 self.lowDiastolic = data["LowDiastolic"] as? Int ?? 0 self.preHighSystolic = data["PreHighSystolic"] as? Int ?? 0 self.preHighDiastolic = data["PreHighDiastolic"] as? Int ?? 0 self.highSystolic = data["HighSystolic"] as? Int ?? 0 self.highDiastolic = data["HighDiastolic"] as? Int ?? 0 self.acc_Status = data["Acc_Status"] as? String ?? "" } init(from user: User) { self.PID_ID = user.userID self.patient_ID = user.userName self.patient_Password = user.password self.patient_Name = user.fullName self.birth_Date = Date() self.address_ID = 0 self.idCard_Number = 0 self.sex_ID = user.gender self.occupation = "" self.mobile_Phone = user.mobile_Phone self.email = "" self.status = 0 self.image = "" self.remove = 0 self.access_Status = "" self.access_Lasttime = Date() self.alarmStatus = .null self.bloodType = "" self.TBPM_ID = "" self.lowSystolic = 0 self.lowDiastolic = 0 self.preHighSystolic = 0 self.preHighDiastolic = 0 self.highSystolic = 0 self.highDiastolic = 0 self.acc_Status = "" } func setBPOPatient(_ BPOPatient: BPOPatient?) { self.BPOPatient = BPOPatient } func setPatientID(_ id: String) { self.patient_ID = id } func setPatientName(_ name: String) { self.patient_Name = name } func setBirthDate(_ date: Date) { self.birth_Date = date } func setPassword(_ pass: String) { self.patient_Password = pass } func setAddressID(_ id: Int) { self.address_ID = id } func setSexID(_ id: Gender) { self.sex_ID = id } func setPhoneNumber(_ phone: String) { self.mobile_Phone = phone } func setEmail(_ email: String) { self.email = email } func setAddress(_ address: Address?) { self.address = address } func setDoctorsFollow(_ data: [User]) { self.doctorsFollow = data } func setMainDoctor(_ doctor: MainDoctor?) { self.mainDoctor = doctor } //MARK: GET func isFillAllInfo() -> Bool { if self.patient_ID == "" || self.patient_Name == "" || self.birth_Date == Date() || self.address_ID == 0 || self.mobile_Phone == "" || self.email == "" { return false } return true } func setSystolic(bloodPressure: BloodPressure) { self.lowSystolic = bloodPressure.low self.preHighSystolic = bloodPressure.preHigh self.highSystolic = bloodPressure.high } func setDiastolic(bloodPressure: BloodPressure) { self.lowDiastolic = bloodPressure.low self.preHighDiastolic = bloodPressure.preHigh self.highDiastolic = bloodPressure.high } func isEqual(_ object: Patient) -> Bool { if self.patient_Name == object.patient_Name && self.birth_Date == object.birth_Date && self.address_ID == object.address_ID && self.mobile_Phone == object.mobile_Phone && self.email == object.email && self.sex_ID.rawValue == object.sex_ID.rawValue { return true } return false } } //MARK: - NSCopying extension Patient: NSCopying { func copy(with zone: NSZone? = nil) -> Any { let patient = Patient.init(from: self) return patient } } //MARK: - TransfromData extension Patient: TransfromData { func transformDictionaty() -> [String : Any] { return ["PID_ID": (self.PID_ID == "" ? arc4random_uniform(1000000000).description : self.PID_ID), "Patient_ID": self.patient_ID, "Patient_Password": self.patient_Password, "Patient_Name": self.patient_Name, "Birth_Date": self.birth_Date.getDesciption(), "Address_ID": self.address_ID, "IdCard_Number": self.idCard_Number, "Sex_ID": self.sex_ID.rawValue, "Occupation": self.occupation, "Mobile_Phone": self.mobile_Phone, "Email": self.email, "Status": self.status, "Image": self.image, "Remove": self.remove, "Access_Lasttime": self.access_Lasttime.getDesciption(), "Access_Status": self.acc_Status, "AlarmStatus": self.alarmStatus.rawValue, "BloodType": self.bloodType, "TBPM_ID": self.TBPM_ID, "LowSystolic": self.lowSystolic, "LowDiastolic": self.lowDiastolic, "PreHighSystolic": self.preHighSystolic, "PreHighDiastolic": self.preHighDiastolic, "HighSystolic": self.highSystolic, "HighDiastolic": self.highDiastolic, "Acc_Status": self.acc_Status ] } func transformDictionatyRegister() -> [String : Any] { return ["PID_ID": (self.PID_ID == "" ? arc4random_uniform(1000000000).description : self.PID_ID), "Patient_ID": self.patient_ID, "Patient_Password": self.patient_Password, "Patient_Name": self.patient_Name, "Birth_Date": self.birth_Date.getDesciption(), "Address_ID": self.address_ID, "IdCard_Number": self.idCard_Number, "Sex_ID": self.sex_ID.rawValue, "Occupation": self.occupation, "Mobile_Phone": self.mobile_Phone, "Email": self.email, "Status": self.status, "Image": self.image, "Remove": self.remove, "Access_Lasttime": self.access_Lasttime.getDesciption(), "Access_Status": self.acc_Status ] } }
// // StructOperation.swift // Transact // // Created by An Nguyen on 4/14/20. // Copyright © 2020 An Nguyen. All rights reserved. // import Foundation class StructOperation { struct globalVariable{ static var userName = String() } }
// // ViewController.swift // TaskManager // // Created by Истина on 06/06/2019. // Copyright © 2019 Истина. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController, ChangeButton { @IBOutlet weak var tableView: UITableView! var fetchedResultsController = CoreDataManager.instance.fetchedResultsController(entityName: "EntityTask", keyForSort: "taskComplete") var myTask: EntityTask? @IBAction func addNewTask(_ sender: Any) { performSegue(withIdentifier: R.segue.viewController.taskManagerToTask, sender: nil) } @IBAction func goToSettings(_ sender: Any) { performSegue(withIdentifier: R.segue.viewController.taskToSettings, sender: nil) } override func viewDidLoad() { super.viewDidLoad() fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch { print(error) } tableView.delegate = self tableView.dataSource = self tableView.reloadData() } func changeButton(checked: EntityTask ) { if checked.taskComplete == true { checked.taskComplete = false checked.notification = false } else { checked.taskComplete = true checked.notification = true } CoreDataManager.instance.saveContext() CoreDataManager.instance.managedObjectContext.refreshAllObjects() tableView.reloadInputViews() } func dateString(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yy, hh:mm" let dateResult = dateFormatter.string(from: date) return dateResult } } extension ViewController: UITableViewDelegate, UITableViewDataSource { // MARK: - TableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { return sections[section].numberOfObjects } else { return 0 } } internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.taskcell, for: indexPath as IndexPath) else { fatalError("DequeueReusableCell failed while casting") } guard let task = self.fetchedResultsController.object(at: indexPath as IndexPath) as? EntityTask else { fatalError("Failed while casting") } cell.taskTitle.text = task.taskTitle cell.catName.text = task.taskCategory cell.prioritySign.backgroundColor = task.categories?.colour as? UIColor cell.dateStart.text = dateString(date: task.dateStart! as Date) cell.dateFinish.text = dateString(date: task.dateComplete! as Date) if task.taskComplete { cell.checkBoxOutlet.setImage(R.image.checkmark(), for: .normal) cell.prioritySign.backgroundColor = R.color.frog() cell.backgroundColor = R.color.frog() } else { cell.checkBoxOutlet.setImage(R.image.checkmarkempty(), for: .normal) cell.prioritySign.backgroundColor = task.categories?.colour as? UIColor cell.backgroundColor = UIColor.white } cell.delegate = self cell.task = task return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let task = fetchedResultsController.object(at: indexPath) as? EntityTask performSegue(withIdentifier: R.segue.viewController.taskManagerToTask, sender: task) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cotroller = R.segue.viewController.taskManagerToTask(segue: segue) { cotroller.destination.myTask = sender as? EntityTask } } //DeleteRow func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { guard let managedObject = fetchedResultsController.object(at: indexPath) as? NSManagedObject else { fatalError("Error") } CoreDataManager.instance.managedObjectContext.delete(managedObject) CoreDataManager.instance.saveContext() } } } extension ViewController: NSFetchedResultsControllerDelegate { // MARK: - FetchedResultsControllerDelegate func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: if let indexPath = newIndexPath { tableView.insertRows(at: [indexPath], with: .fade) } case .delete: if let indexPath = indexPath { tableView.deleteRows(at: [indexPath], with: .fade) } case .update: tableView.reloadRows(at: [indexPath!], with: .automatic) case .move: if let indexPath = indexPath { tableView.deleteRows(at: [indexPath], with: .fade) } if let newIndexPath = newIndexPath { tableView.insertRows(at: [newIndexPath], with: .fade) } @unknown default: fatalError() } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } }
// // ARModifyViewController.swift // AR-Voice-Tutorial-iOS // // Created by 余生丶 on 2020/9/9. // Copyright © 2020 AR. All rights reserved. // import UIKit import ARtmKit enum ARChatInfoState: NSInteger { case name,announcement,welcome } class ARModifyViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var infoTextView: UITextView! @IBOutlet weak var placeholderLabel: UILabel! @IBOutlet weak var limitLabel: UILabel! @IBOutlet weak var textViewHeight: NSLayoutConstraint! let list = ["房间名称","公告","欢迎语"] let placeholderList = ["请输入房间名称","请输入公告内容","请输入欢迎语"] let limitList = ["4~32","192","16"] var infoState: ARChatInfoState? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. placeholderLabel.text = placeholderList[infoState!.rawValue] limitLabel.text = limitList[infoState!.rawValue] (infoState == ARChatInfoState(rawValue: 1)) ? (textViewHeight.constant = 203) : (textViewHeight.constant = 64) let leftButton: UIButton = UIButton.init(type: .custom) leftButton.frame = CGRect.init(x: 0, y: 0, width: 100, height: 17) leftButton.setTitle(list[infoState!.rawValue], for: .normal) leftButton.titleLabel?.font = UIFont(name: "PingFang SC", size: 17) leftButton.setTitleColor(RGB(r: 96, g: 96, b: 96), for: .normal) leftButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0); leftButton.setImage(UIImage(named: "icon_return"), for: .normal) leftButton.addTarget(self, action: #selector(didClickBackButton), for: .touchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftButton) initializeChatInfo() } func initializeChatInfo() { if infoState == ARChatInfoState(rawValue: 0) { infoTextView.text = chatModel.roomName } else if (infoState == ARChatInfoState(rawValue: 1)) { infoTextView.text = chatModel.announcement } else { infoTextView.text = chatModel.welcome } if infoTextView.text.count != 0 { placeholderLabel.isHidden = true } } @objc func didClickBackButton() { let channelAttribute: ARtmChannelAttribute = ARtmChannelAttribute() var value: String! (infoTextView.text.count == 0) ? (value = "") : (value = infoTextView.text) if infoState == ARChatInfoState(rawValue: 0) { if value!.count >= 4 { channelAttribute.key = "roomName" channelAttribute.value = value chatModel.roomName = value addOrUpdateChannel(attribute: channelAttribute) } else { print("invalid") } } else if (infoState == ARChatInfoState(rawValue: 1)) { channelAttribute.key = "notice" channelAttribute.value = value addOrUpdateChannel(attribute: channelAttribute) } else { channelAttribute.key = "welecomeTip" channelAttribute.value = value addOrUpdateChannel(attribute: channelAttribute) } self.navigationController?.popViewController(animated: true) } func textViewDidChange(_ textView: UITextView) { (textView.text.count == 0) ? (placeholderLabel.isHidden = false) : (placeholderLabel.isHidden = true) if (infoState == ARChatInfoState(rawValue: 0)) { //4~32 if textView.text.count > 32 { textView.text = String(textView.text.prefix(32)) textView.undoManager?.removeAllActions() textView.becomeFirstResponder() } } else if (infoState == ARChatInfoState(rawValue: 1)) { //192 if textView.text.count > 192 { textView.text = String(textView.text.prefix(192)) textView.undoManager?.removeAllActions() textView.becomeFirstResponder() } } else if (infoState == ARChatInfoState(rawValue: 2)) { //16 if textView.text.count > 16 { textView.text = String(textView.text.prefix(16)) textView.undoManager?.removeAllActions() textView.becomeFirstResponder() } } } }
// // Copyright (c) 2018. Aleksandr Darmeiko // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import RibletsKit class TripsService { enum MyTrip { case none case some([Trip]) } class LoadMyTrips: ServiceOperation<MyTrip> { var myTrips = [Trip(train: Train(name: "Sprinter", number: "A1F", route: Route(departure: "Moscow", arrival: "Erevan"), shcedule: Shcedule(departure: Date(), arrival: Date())))] override init() { super.init() closure = { Thread.sleep(forTimeInterval: 1.5) $0 << .success(.some(self.myTrips)) } } } class SearchTripsOperation: ServiceOperation<[Trip]> { var route: Route? override init() { super.init() closure = { guard let route = self.route else { $0 << .error(0, "Route is empty") return } Thread.sleep(forTimeInterval: 2.0) $0 << .success([ Trip(train: Train(name: "Sprinter", number: "A1F", route: route, shcedule: Shcedule(departure: Date(), arrival: Date()))), Trip(train: Train(name: "Sprinter", number: "A1F", route: route, shcedule: Shcedule(departure: Date(), arrival: Date()))), ]) } } } var loadMyTrips = LoadMyTrips() let searchTrips = SearchTripsOperation() }
// // AttributedStringWrapper.swift // AttributedStringWrapper // // Created by 郜宇 on 2017/6/13. // Copyright © 2017年 Loopeer. All rights reserved. // import Foundation public extension String { var toAttributed: AttributedStringWrapper { return AttributedStringWrapper(rawValue: NSMutableAttributedString(string: self)) } } public struct AttributedStringWrapper: RawRepresentable { public typealias RawValue = NSMutableAttributedString public var rawValue: NSMutableAttributedString public init(rawValue: AttributedStringWrapper.RawValue) { self.rawValue = rawValue } } public extension AttributedStringWrapper { typealias ParagraphStyleSetup = (NSMutableParagraphStyle) -> Void typealias ShadowStyleSetup = (NSShadow) -> Void @available(iOS 9.0, *) typealias WriteDirection = (formatType: NSWritingDirectionFormatType, direction: NSWritingDirection) public var allRange: NSRange { return NSMakeRange(0, self.rawValue.length) } /// NSParagraphStyleAttributeName(段落) @discardableResult func paragraph(range: NSRange? = nil, setup: ParagraphStyleSetup) -> AttributedStringWrapper { let paragraphStyle = NSMutableParagraphStyle() setup(paragraphStyle) rawValue.addAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle], range: range ?? allRange) return self } /// NSForegroundColorAttributeName(字体颜色) @discardableResult func foregroundColor(_ color: UIColor, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.foregroundColor: color], range: range ?? allRange) return self } /// NSFontAttributeName(字体) @discardableResult func font(_ font: UIFont, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.font: font], range: range ?? allRange) return self } /// NSBackgroundColorAttributeName(字体背景色) @discardableResult func backgroundColor(_ color: UIColor, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.backgroundColor: color], range: range ?? allRange) return self } /// NSStrikethroughStyleAttributeName(删除线) @discardableResult func strikethrough(style: [NSUnderlineStyle], color: UIColor? = nil, range: NSRange? = nil) -> AttributedStringWrapper { // iOS10.3 bugs: https://stackoverflow.com/questions/43070335/nsstrikethroughstyleattributename-how-to-strike-out-the-string-in-ios-10-3 rawValue.addAttributes([NSAttributedStringKey.strikethroughStyle: style.reduce(0) { $0 | $1.rawValue }, NSAttributedStringKey.baselineOffset: 0], range: range ?? allRange) guard let color = color else { return self } rawValue.addAttributes([NSAttributedStringKey.strikethroughColor: color], range: range ?? allRange) return self } /// NSUnderlineStyleAttributeName(下划线) @discardableResult func underLine(style: [NSUnderlineStyle], color: UIColor? = nil, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.underlineStyle: style.reduce(0) { $0 | $1.rawValue }], range: range ?? allRange) guard let color = color else { return self } rawValue.addAttributes([NSAttributedStringKey.underlineColor: color], range: range ?? allRange) return self } /// NSShadowAttributeName(阴影) @discardableResult func shadow(range: NSRange? = nil, setup: ShadowStyleSetup) -> AttributedStringWrapper { let shadow = NSShadow() setup(shadow) rawValue.addAttributes([NSAttributedStringKey.shadow: shadow], range: range ?? allRange) return self } /// NSObliquenessAttributeName 设置字形倾斜度,正值右倾,负值左倾 @discardableResult func obliqueness(angle: CGFloat, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.obliqueness: angle], range: range ?? allRange) return self } /// NSWritingDirectionAttributeName 设置文字书写方向,从左向右书写或者从右向左书写 @available(iOS 9.0, *) @discardableResult func writingDirection(write: WriteDirection, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.writingDirection: [write.direction.rawValue | write.formatType.rawValue]], range: range ?? allRange) return self } /// 空心字 颜色, 线宽 @discardableResult func stroke(color: UIColor, width: CGFloat, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.strokeColor: color], range: range ?? allRange) rawValue.addAttributes([NSAttributedStringKey.strokeWidth: width], range: range ?? allRange) return self } /// NSKernAttributeName 文字间的间距 @discardableResult func kern(padding: CGFloat, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.kern: padding], range: range ?? allRange) return self } /// NSExpansionAttributeName 拉伸压缩 正值横向拉伸 负值横向压缩 @discardableResult func expansion(value: CGFloat, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.expansion: value], range: range ?? allRange) return self } /// NSLigatureAttributeName 连体 0 表示没有连体字符。1 表示使用默认的连体字符。2表示使用所有连体符号。默认值为 1(注意,iOS 不支持值为 2) @discardableResult func ligature(value: CGFloat, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.ligature: value], range: range ?? allRange) return self } /// NSBaselineOffsetAttributeName 基线偏移量 正值上偏 负值下偏 @discardableResult func baselineOffset(value: CGFloat, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.baselineOffset: value], range: range ?? allRange) return self } /// NSTextEffectAttributeName 特殊效果 目前只有NSTextEffectLetterpressStyle(凸版印刷效果)可用 @discardableResult func textEffect(value: NSAttributedString.TextEffectStyle = .letterpressStyle, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.textEffect: value], range: range ?? allRange) return self } /// NSVerticalGlyphFormAttributeName 横、竖排版 0横向排版 1竖向排版 @discardableResult func verticalGlyphForm(value: Int, range: NSRange? = nil) -> AttributedStringWrapper { rawValue.addAttributes([NSAttributedStringKey.verticalGlyphForm: value], range: range ?? allRange) return self } /// get height, Before this, you must set the height of the text firstly func getHeight(by fixedWidth: CGFloat) -> CGFloat { let h = rawValue.boundingRect(with: CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT)), options: [.usesFontLeading , .usesLineFragmentOrigin, .usesDeviceMetrics], context: nil).size.height return ceil(h) } /// get width, Before this, you must set the height of the text firstly func getWidth(by fixedHeight: CGFloat) -> CGFloat { let w = rawValue.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: fixedHeight), options: [.usesFontLeading , .usesLineFragmentOrigin], context: nil).size.width return ceil(w) } } public func + (lf: AttributedStringWrapper, rf: AttributedStringWrapper) -> AttributedStringWrapper { lf.rawValue.append(rf.rawValue) return lf }
// // YTNavigationController.swift // AdressListWithSwift2 // // Created by caixiasun on 16/9/8. // Copyright © 2016年 yatou. All rights reserved. // import UIKit class YTNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func setNavigationBarBackImg(img:UIImage!) -> () { self.navigationBar.setBackgroundImage(img, forBarMetrics: UIBarMetrics.Default) } func setNavigationBarFont(fontColor:UIColor) -> () { self.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:fontColor] } func setNavigationBarFont(fontSize:CGFloat,fontColor:UIColor) -> () { self.navigationBar.titleTextAttributes = [NSFontAttributeName:UIFont.systemFontOfSize(fontSize),NSForegroundColorAttributeName:fontColor] } func initNavigationBar() -> () { setNavigationBarBackImg(UIImage(named: "navi_bg.png")) setNavigationBarFont(WhiteColor) } func initNavigationBar(bgImg:UIImage!, fontColor:UIColor) -> () { setNavigationBarBackImg(bgImg) setNavigationBarFont(fontColor) } }
// // DetailGameViewController.swift // iOSFundamentalOne // // Created by iei19100004 on 16/09/21. // import UIKit class DetailGameViewController: UIViewController { var textTest = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.systemBackground NSLog("ini Log: \(textTest)") } }
// // RestoreViewController.swift // Slidecoin // // Created by Oleg Samoylov on 17.12.2019. // Copyright © 2019 Oleg Samoylov. All rights reserved. // import UIKit import Toolkit final class RestoreViewController: UIViewController { // MARK: Private Properties private let alertService = Assembly.alertService private let requestSender = Assembly.requestSender private var formValidationHelper: FormValidationHelper? // MARK: Outlets @IBOutlet private weak var currentPasswordField: UITextField! @IBOutlet private weak var passwordField: UITextField! @IBOutlet private weak var repeatPasswordField: UITextField! @IBOutlet private weak var doneButton: BigButton! @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var stackView: UIStackView! // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() setupKeyboard() setupNavigationBar() setupFormValidationHelper() } // MARK: Private private func setupKeyboard() { scrollView.bottomAnchor.constraint(lessThanOrEqualTo: keyboardLayoutGuide.topAnchor).isActive = true } private func setupNavigationBar() { navigationItem.title = "Изменение пароля" if presentingViewController != nil { let closeButton = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(close)) navigationItem.rightBarButtonItem = closeButton } } private func setupFormValidationHelper() { let textFields: [UITextField] = [currentPasswordField, passwordField, repeatPasswordField] formValidationHelper = FormValidationHelper(textFields: textFields, button: doneButton, stackView: stackView) } @IBAction private func changePasswordDidTap() { guard let currentPassword = currentPasswordField.text, let newPassword = passwordField.text else { return } doneButton.showLoading() let config = RequestFactory.reset(currentPassword: currentPassword, newPassword: newPassword) requestSender.send(config: config) { [weak self] result in guard let self = self else { return } self.doneButton.hideLoading() DispatchQueue.main.async { switch result { case .success(let message): let alert = self.alertService.alert(message, title: .info, isDestructive: false) { _ in if message.contains("success") { self.dismiss(animated: true) } } self.present(alert, animated: true) case .failure(let error): let alert = self.alertService.alert(error.localizedDescription) self.present(alert, animated: true) } } } } @objc private func close() { dismiss(animated: true) } }
// // Photo.swift // RxViewModel // // Created by Thuc on 1/13/18. // Copyright © 2018 Thuc. All rights reserved. // import UIKit import RxDataSources struct CurrentPage: Decodable { var currentPage: Int var feature: String // var filters: [String: String] var photos: [Photo] init(currentPage: Int, feature: String, photos: [Photo]) { self.currentPage = currentPage self.feature = feature // self.filters = filters self.photos = photos } enum CurrentPageKeys: String, CodingKey { case currentpage = "current_page" case feature = "feature" case filters = "filters" case photos = "photos" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CurrentPageKeys.self) let currentPage = try container.decode(Int.self, forKey: .currentpage) let feature = try container.decode(String.self, forKey: .feature) // let filters = try container.decode([String: String].self, forKey: .filters) let photos = try container.decode([Photo].self, forKey: .photos) self.init(currentPage: currentPage, feature: feature, photos: photos) } } struct Photo { var camera: String? var createdAt: String? var imageUrl: URL? init(camera: String?, createdAt: String?, imageUrl: URL?) { self.camera = camera self.createdAt = createdAt self.imageUrl = imageUrl } } extension Photo: Decodable { enum MyPhotoKeys: String, CodingKey { case camera = "camera" case created_at = "created_at" case image_url = "image_url" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: MyPhotoKeys.self) let camera = try? container.decode(String.self, forKey: .camera) let createAt = try container.decode(String.self, forKey: .created_at) let imageUrl = try container.decode(URL.self, forKey: .image_url) self.init(camera: camera, createdAt: createAt, imageUrl: imageUrl) } } struct SectionOfPhotos { var title: String var items: [Photo] } extension SectionOfPhotos: SectionModelType { init(original: SectionOfPhotos, items: [Photo]) { self = original self.items = items } }
// // This source file is part of the Apodini open source project // // SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <paul.schmiedmayer@tum.de> // // SPDX-License-Identifier: MIT // import Foundation extension Encodable { func toJSON(outputFormatting: JSONEncoder.OutputFormatting? = nil) throws -> Data { let encoder = JSONEncoder() if let outputFormatting = outputFormatting { encoder.outputFormatting = outputFormatting } return try encoder.encode(self) } } extension Decodable { static func fromJSON(_ data: Data) throws -> Self { try JSONDecoder().decode(Self.self, from: data) } }
// // LaunchCell.swift // Liftoff // // Created by Pavol Margitfalvi on 13/08/2017. // Copyright © 2017 Pavol Margitfalvi. All rights reserved. // import UIKit @IBDesignable class LaunchCell: UITableViewCell { @IBOutlet weak var rocketName: UILabel! @IBOutlet weak var date: UILabel! @IBInspectable var lineWidth: CGFloat = 4 @IBInspectable var radiusRatio: CGFloat = 0.2 @IBInspectable var boundsOffset: CGFloat = 5 @IBInspectable var fillColor = UIColor(red: 0.30, green: 0.56, blue: 0.78, alpha: 1.0) @IBInspectable var strokeColor: UIColor? = nil override func draw(_ rect: CGRect) { let radius = CGFloat(radiusRatio) * min(rect.width, rect.height) let newRect = CGRect(x: rect.minX + boundsOffset, y: rect.minY + boundsOffset, width: rect.width - 2 * boundsOffset, height: rect.height - 2 * boundsOffset) let path = UIBezierPath.init(roundedRect: newRect, cornerRadius: radius) path.lineWidth = lineWidth if let color = strokeColor { color.setStroke() path.stroke() } fillColor.setFill() path.fill() } }
// // coloplancell.swift // idashboard // // Created by Hasanul Isyraf on 01/05/2018. // Copyright © 2018 Hasanul Isyraf. All rights reserved. // import UIKit class coloplancell: UITableViewCell { @IBOutlet weak var vdslplan: UILabel! @IBOutlet weak var region: UILabel! @IBOutlet weak var dslamid: UILabel! @IBOutlet weak var oldcabinet: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
import SpriteKit import GameplayKit import Smorgasbord open class Game { public var stateMachine: GameStateMachine? public weak var view: Presenter? public var currentScene: GKScene? public var currentGameScene: GameScene? { currentScene?.rootNode as? GameScene } public init() { stateMachine = GameStateMachine(states: [ EnterLevelState(), PlayingState(), MainMenuState() ]) stateMachine?.game = self } public func each<Component: GKComponent>(_: Component.Type) -> [Component] { return currentScene?.each(Component.self) ?? [] } var players: [Player] { guard let level = currentScene else { return [] } return level.entities.compactMap{ $0 as? Player } } func getEntities(nodes: [SKNode]) -> [GKEntity] {return nodes.compactMap{ $0.entity }} func addPlayers(to level: GKScene, players: [Player]) { for player in players { level.addEntity(player) } } func getPlayersFromShootables() -> [Player] { let shootableNodes = each(ShootableComponent.self).compactMap{ $0.nodeComponent?.node } var players: [Player] = [] let arr = (shootableNodes.compactMap{ $0.userData?["shootable"] as? Int }) let set = Set(arr) for _ in set { players.append(Player(game: self)) } return players } open func runLevel(_ level: GKScene) { currentScene = level guard let scene = level.rootNode as? GameScene else { return } addPlayers(to: level, players: getPlayersFromShootables()) assignStarts() assignDraggables() assignRotations() assignShootables() stateMachine?.enter(EnterLevelState.self) view?.presentScene(scene) } func assignStarts() { // Only works if start nodes are sorted left-right min-max let startComponents = each(StartComponent.self) for shootable in each(ShootableComponent.self) { guard let shootableNodeData = shootable.nodeComponent?.node.userData else { continue } guard let index = shootableNodeData["start"] as? Int else { continue } startComponents[index].shootable = shootable } } func assignDraggables() { associateComponentsWithPlayer(each(DraggableComponent.self)) } func assignRotations() { associateComponentsWithPlayer(each(RotateableComponent.self)) } func assignShootables() { associateComponentsWithPlayer(each(ShootableComponent.self)) } func getPlayerFromComponentSKNodeData(_ component: GameComponent) -> Player? { guard let nodeData = component.nodeComponent?.node.userData else { return nil } guard let i = nodeData["\(component.className.lowercased().split(separator: ".")[1])"] as? Int else { return nil } guard i < players.count && i >= 0 else { return nil } return players[i] } func associateComponentsWithPlayer(_ components: [GameComponent]) { for component in components { component.player = getPlayerFromComponentSKNodeData(component) } } }
// // GuideViewController.swift // GameOfThrones // // Created by Ibraheem rawlinson on 11/20/18. // Copyright © 2018 Pursuit. All rights reserved. // import UIKit class GuideViewController: UIViewController { @IBOutlet weak var secondImgView: UIImageView! @IBOutlet weak var guideTitleVIew: UILabel! @IBOutlet weak var seasonView: UILabel! @IBOutlet weak var episodeVIew: UILabel! @IBOutlet weak var runTimeVIew: UILabel! @IBOutlet weak var airDateView: UILabel! @IBOutlet weak var guideDialogueVIew: UITextView! // private var myGOTList: [[GOTEpisode]] override func viewDidLoad() { super.viewDidLoad() } private func secondViewSetUp(){ // let guideForGOT = myGOTList[][] // secondImgView.image = UIImage(named: ) } }
// // UIButtonExtension.swift // Enbac // // Created by Nguyen Tien Dung on 7/10/15. // Copyright © 2015 Hoang Duy Nam. All rights reserved. // import Foundation import UIKit extension UIButton { @IBInspectable var autoScare: Bool { get { return false } set (autoScare) { self.titleLabel?.minimumScaleFactor = 0.5 } } }
// // MovieListViewModel.swift // BookMyShow-Test // // Created by Prathamesh Mestry on 04/06/21. // import Foundation protocol MovieListViewModelDelegate { func didGetMovieListData() } class MovieListViewModel { var movieList: MoviePlayingModel? var delegate: MovieListViewModelDelegate? weak var vc: ViewController? //MARK: API Call for Now Playing Movies func getMovieNowPlayingList() { let movieManager = MovieListManager() movieManager.getMovieList() { (response) in self.movieList = response self.vc?.movieList = self.movieList?.movieResult self.delegate?.didGetMovieListData() } errorCompletionHandler: { (error) in print("\(error?.localizedDescription ?? "")") } } }
// // TimeManager.swift // NutrAI // // Created by Vinicius Mangueira on 04/07/19. // Copyright © 2019 Vinicius Mangueira. All rights reserved. // import Foundation class TimeManager { static func getCurrentTimer() -> String { let formatter = DateFormatter() formatter.dateFormat = "hh" let hourString = formatter.string(from: Date()) return hourString } }
// // DataEntryModel.swift // COVID // // Created by KT on 2020/9/5. // Copyright © 2020 The Riders. All rights reserved. // import Foundation class CountryModel : NSObject { private var name : String private var cases : Int private var deaths : Int private var recovered : Int private var updated : String init(name: String, cases: Int, deaths: Int, recovered: Int, updated: String) { self.name = name self.cases = cases self.deaths = deaths self.recovered = recovered self.updated = updated super.init() } func getName() -> String { return name } func getCases() -> Int { return cases } func getDeaths() -> Int { return deaths } func getRecovered() -> Int { return recovered } }
// // UserInfo.swift // UIPickerHW // // Created by Иван on 3/31/21. // import Foundation struct User { let name: String let password: String static func getUserData() -> User { User(name: "User", password: "Password") } }
import SwiftUI @available(iOS 13.0, *) extension SingleTaskGraphView { func tTaskpro(_ TaskPro: String) { print(TaskPro) } }
// // VHeroSwapPosition.swift // TG // // Created by Andrii Narinian on 9/23/17. // Copyright © 2017 ROLIQUE. All rights reserved. // import Foundation import SwiftyJSON extension Swap { init (json: JSON) { hero = Actor(id: json["Hero"].stringValue, type: .actor) playerId = json["Player"].string side = Side(string: json["Team"].string) } } extension Position { init (json: JSON) { self.x = json.arrayValue[0].doubleValue self.y = json.arrayValue[1].doubleValue self.z = json.arrayValue[2].doubleValue } }
import UIKit import Darwin /* /////////////////////////////////////////////////////////////////// /// 1. Придумать класс, методы которого могут завершаться неудачей /// /// и возвращать либо значение, либо ошибку Error?. /// /// Реализовать их вызов и обработать результат метода /// /// при помощи конструкции if let, или guard let. /// /////////////////////////////////////////////////////////////////// */ struct Baggage { let id: Int let name: String let description: String let space: Int } enum Transmission: String { case auto = "Автоматическая" case manual = "Механическая" case none = "Отсутствует" } enum EngineStatus: String { case running = "Запущен" case stopped = "Не запущен" } enum WindowsStauts: String { case open = "Открыты" case close = "Закрыты" } enum TrunkError: Error { case nothingToRemove // "Багажник пуст!" case baggageDoesNotExists(id: Int) // "В багажнике нет вещи с id: \(id)" case noSpace // "В багажнике нет места!" } class Car { var model: String var year: UInt16 var trunkSpace: Int var usedTrunkSpace: Int var baggageArray: [Baggage] init?(model: String, year: UInt16, trunkSpace: Int, baggageArray: [Baggage]) { self.usedTrunkSpace = 0 for baggage in baggageArray { self.usedTrunkSpace += baggage.space } guard usedTrunkSpace <= trunkSpace else { return nil } self.model = model self.year = year self.trunkSpace = trunkSpace self.baggageArray = baggageArray } private func increaseTrunkSpace(_ space: Int) -> Bool { var result = false if usedTrunkSpace + space <= trunkSpace { usedTrunkSpace += space result = true } return result } private func decreaseTrunkSpace(_ space: Int) -> Bool { var result = false if usedTrunkSpace - space >= 0 { usedTrunkSpace -= space result = true } return result } func addBaggage(_ baggage: Baggage) -> TrunkError? { guard increaseTrunkSpace(baggage.space) else { return .noSpace } baggageArray.append(baggage) return nil } func removeBaggageBy(id: Int) -> (Baggage?, TrunkError?) { guard baggageArray.count > 0 else { return (nil, .nothingToRemove) } var result: Baggage? = nil for i in 0..<baggageArray.count { let baggage = baggageArray[i] if baggage.id == id { guard decreaseTrunkSpace(baggage.space) else { return (nil, .nothingToRemove) } result = baggageArray.remove(at: i) break } } guard result != nil else { return (nil, .baggageDoesNotExists(id: id)) } return (result, nil) } func printStatus() { print(""" \n Тип: Легковой Модель: \(model) Год выпуска: \(year) Объем багажника: \(trunkSpace) Использованный объем багажника: \(usedTrunkSpace) \n """) } func printBaggage() { guard baggageArray.count > 0 else { print("Багажник пуст.") return } print("\nСодержимое багажника:") for baggage in baggageArray { print("\(baggage.name) занимает \(baggage.space) пространства багажника.") } print("Занято \(usedTrunkSpace) из \(trunkSpace)\n") } } func testCar() { let car = Car(model: "Test", year: 2000, trunkSpace: 200, baggageArray: []) guard let strongCar = car else { return } let pc = Baggage(id: 0, name: "PC", description: "Обычный PC", space: 30) let chair = Baggage(id: 1, name: "Стул", description: "Обычный стул", space: 70) let table = Baggage(id: 2, name: "Стол", description: "Обычный стол", space: 180) strongCar.addBaggage(pc) strongCar.addBaggage(chair) strongCar.removeBaggageBy(id: 1) // Успешное удаление strongCar.addBaggage(table) // Ошибка о том что не поместится print(strongCar.removeBaggageBy(id: 1000)) // Удаление несуществующего элемента strongCar.removeBaggageBy(id: 0) strongCar.printBaggage() print(strongCar.removeBaggageBy(id: 0)) // Ошибка удаления элемента из пустого багажника. } testCar() /* ///////////////////////////////////////////////////////////////////////////////// /// 2. Придумать класс, методы которого могут выбрасывать ошибки. /// /// Реализуйте несколько throws-функций. /// /// Вызовите их и обработайте результат вызова при помощи конструкции try/catch. /// ///////////////////////////////////////////////////////////////////////////////// */ enum PasswordValidationError: Error { case tooShort case noCapitalLetters case noNumbers case noSymbols case noSmallLetters } class PasswordValidation { private let smallLetters = "qwertyuiopasdfghjklzxcvbnm" private let numbers = "0123456789" private let capitalLetters = "QWERTYUIOPASDFGHJKLZXCVBNM" private let symbols = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" private let minimalLength: Int init(minimalLength: Int) { self.minimalLength = minimalLength } private func checkSmallLetters(_ password: String) throws { var flag = false for char in password { if smallLetters.contains(char) { flag = true break } } if !flag { throw PasswordValidationError.noSmallLetters } } private func checkNumbers(_ password: String) throws { var flag = false for char in password { if numbers.contains(char) { flag = true break } } if !flag { throw PasswordValidationError.noNumbers } } private func checkCapitalLetters(_ password: String) throws { var flag = false for char in password { if capitalLetters.contains(char) { flag = true break } } if !flag { throw PasswordValidationError.noCapitalLetters } } private func checkSymbols(_ password: String) throws { var flag = false for char in password { if symbols.contains(char) { flag = true break } } if !flag { throw PasswordValidationError.noSymbols } } private func checkLength(_ password: String) throws { guard password.count >= minimalLength else { throw PasswordValidationError.tooShort } } func validate(password: String) throws { do { try checkLength(password) try checkSmallLetters(password) try checkCapitalLetters(password) try checkNumbers(password) try checkSymbols(password) } catch PasswordValidationError.noSmallLetters { throw PasswordValidationError.noSmallLetters } catch PasswordValidationError.noCapitalLetters { throw PasswordValidationError.noCapitalLetters } catch PasswordValidationError.noNumbers { throw PasswordValidationError.noNumbers } catch PasswordValidationError.noSymbols { throw PasswordValidationError.noSymbols } catch PasswordValidationError.tooShort { throw PasswordValidationError.tooShort } } } let validator = PasswordValidation(minimalLength: 6) let pass0 = "qQ1/aaa" // Все ок let pass1 = "qQ1aaa" // без символов let pass2 = "qQ/aaa" // без цифр let pass3 = "Q1/111" // без маленьких букв let pass4 = "q1/aaa" // без заглавных букв let pass5 = "q1/A" // Меньше заданной длинны do { // try validator.validate(password: pass0) try validator.validate(password: pass1) // try validator.validate(password: pass2) // try validator.validate(password: pass3) // try validator.validate(password: pass4) // try validator.validate(password: pass5) } catch PasswordValidationError.noSmallLetters { print("Пароль не содержит маленьких букв!") } catch PasswordValidationError.noCapitalLetters { print("Пароль не содержит заглавных букв!") } catch PasswordValidationError.noNumbers { print("Пароль не содержит цифр!") } catch PasswordValidationError.noSymbols { print("Пароль не содержит символов!") } catch PasswordValidationError.tooShort { print("Пароль слишком короткий!") }
// // Lesson.swift // Nihongo // // Created by Dang Nguyen Vu on 3/9/17. // Copyright © 2017 Dang Nguyen Vu. All rights reserved. // import Foundation import FirebaseDatabase struct Lesson { var index: Int? // var vocabs: [Vocab]? var name: String? var key: String? init(name: String, index: Int = 99) { self.name = name self.index = index } init(snapshot: FIRDataSnapshot) { let snapshotValue = snapshot.value as! [String: AnyObject] name = snapshotValue["name"] as? String index = snapshotValue["index"] as? Int key = snapshot.key } func toAnyObject() -> Any? { guard let name = self.name else { return nil } return ["name": name, "index": index ?? 0] } }
// // NTWConnectiosPagesParenViewController.swift // Networkd // // Created by CloudStream on 5/12/17. // Copyright © 2017 CloudStream LLC. All rights reserved. // import UIKit class NTWConnectiosPagesParentViewController: UIViewController { var pageIndex: Int! @IBOutlet weak var connectionsTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.connectionsTableView.rowHeight = UITableViewAutomaticDimension self.connectionsTableView.estimatedRowHeight = 20 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension NTWConnectiosPagesParentViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "connectionCell", for: indexPath) as! NTWConnectionTableViewCell if pageIndex != 2 { cell.hideMeLabel.isHidden = true } return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } }
// // GlobalNavigationController.swift // InspireME // // Created by Brad Siegel on 3/25/16. // Copyright © 2016 Brad Siegel. All rights reserved. // import UIKit import Firebase enum Segue: String { case Register = "registration" case CreatePost = "createPost" case PostFeed = "landingScreen" } protocol SeguePerformer: class { func navigateWithSegue(segueToPerform: String, dataForSegue: AnyObject?) } protocol RequiresSeguePerformer: class { func setSeguePerformer(performer: SeguePerformer) } class GlobalNavigationController: UINavigationController, UINavigationControllerDelegate, SeguePerformer { private var mostRecentController: UIViewController? override func awakeFromNib() { super.awakeFromNib() self.delegate = self } func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { if let destination = viewController as? RequiresSeguePerformer { destination.setSeguePerformer(self) } } func navigateWithSegue(segueToPerform: String, dataForSegue: AnyObject?) { dispatch_async(dispatch_get_main_queue(),{ self.performSegueWithIdentifier( segueToPerform, sender: nil) }) } }
// // Created by Daniel Heredia on 2/27/18. // Copyright © 2018 Daniel Heredia. All rights reserved. // // Sorted Merge import Foundation func merge(in a: inout [Int], from b: [Int], lastA: Int) -> Bool{ if lastA >= a.count || (a.count - (lastA + 1)) < b.count { return false } var indexA = lastA var indexB = b.count - 1 var current = a.count - 1 while indexB >= 0 { if indexA >= 0 && a[indexA] == b[indexB] { a[current] = a[indexA] current -= 1 indexA -= 1 a[current] = b[indexB] indexB -= 1 } else if indexA >= 0 && a[indexA] > b[indexB] { a[current] = a[indexA] indexA -= 1 } else { a[current] = b[indexB] indexB -= 1 } current -= 1 } return true } var a = [1,3,5,7,10,0,0,0,0,0] var b = [2,4,6,8,10] let lastA = 4 if merge(in: &a, from: b, lastA: lastA) { print("Merged array: \(a)") } else { print("Inout error") }
// // FeedbackViewController.swift // OnceMemory // // Created by Rui Huang on 4/22/18. // Copyright © 2018 BaikalSeal. All rights reserved. // import UIKit class FeedbackViewController: SuperViewController, UITextViewDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var naviBar: UINavigationBar! override func viewDidLoad() { super.viewDidLoad() textView.delegate = self textView!.layer.borderWidth = 0.7 textView!.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor textView!.layer.cornerRadius = 5.0 // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textViewDidEndEditing(_ textView: UITextView) { self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) } func textView (_ textView: UITextView, shouldChangeTextIn range:NSRange, replacementText text:String) -> Bool { if(text == "\n"){ textView.resignFirstResponder() return false } if range.location >= 20 { let alertController = UIAlertController(title: "Attention", message: "You can input up to 50 words", preferredStyle: .alert) let okAction = UIAlertAction(title: "Okay", style: .cancel, handler: nil) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) return false } return true } override func handelNotification(notification: NSNotification) { guard let theme = notification.object as? ThemeProtocol else { return } naviBar.barTintColor = theme.navigationBarColor naviBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: theme.textColor] naviBar.tintColor = theme.barItemColor naviBar.isTranslucent = false let barView = UIView(frame: CGRect(x:0, y:0, width:view.frame.width, height:UIApplication.shared.statusBarFrame.height)) barView.backgroundColor = theme.navigationBarColor self.view.addSubview(barView) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // Artist.swift // FolkArt // // Created by Tyler White on 3/23/17. // Copyright © 2017 Luke Karns. All rights reserved. // import Foundation import RealmSwift class Artist: Object { dynamic var name = "" dynamic var about = "" dynamic var mediaOfWork = "" dynamic var profileImageName = "" dynamic var artImageName = "" dynamic var booth: Booth? dynamic var country: Country? dynamic var media: Media? override static func primaryKey() -> String? { return "name" } }
// // NSFileManager+Extensions.swift // Current // // Created by Scott Jones on 3/30/16. // Copyright © 2016 Barf. All rights reserved. // import Foundation extension NSFileManager { public static var documents:String { return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] } public func createDirectoryInDirectory(directory:String, path:String)->String { let filePath = NSString(format:"%@", directory).stringByAppendingPathComponent(path) if fileExistsAtPath(filePath) == false { do { try createDirectoryAtPath(filePath, withIntermediateDirectories:true, attributes: nil) } catch { // print("Error : createPathInDirectory : \(error)") } } return path } public func createIndexedPath(directory:String, fileName:String, ext:String)->String { var numContents:Int = 0 do { numContents = try contentsOfDirectoryAtPath(directory).count } catch { // print("Error : createIndexedPath : \(error)") } return "\(directory)/\(fileName) \(numContents).\(ext)" } public func deleteItem(path:String) { do { try removeItemAtPath(path) } catch { // print("Error : deleteItem : \(error)") } } public func deleteAllInDirectory(directory:String) { var numContents:[String] = [] do { numContents = try contentsOfDirectoryAtPath(directory) for n in numContents { deleteItem(n) } } catch { // print("Error : deleteAllInDirectory : \(error)") } } public func bytesSizeOfAllFiles(files:[String])->UInt64 { let totalBytesOfFiles = files.map { var size:UInt64 = 0 do { size = try attributesOfItemAtPath($0)[NSFileSize]?.unsignedLongLongValue ?? 0 } catch _ {} return UInt64(size) }.flatMap{ $0 }.reduce(UInt64(0), combine:+) return totalBytesOfFiles } public func sizeOfFile(filePath:String)->UInt64 { var fileSize : UInt64 = 0 do { let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath) if let _attr = attr { fileSize = _attr.fileSize(); } } catch { // print("Error : sizeOfFile : \(filePath) : \(error)") } return fileSize } public func contentsOfDirectory(directory:String)->[String] { do { let contents = try contentsOfDirectoryAtPath(directory) return contents } catch { // print("Error : createIndexedPath : \(error)") return [] } } public func fileCreationDate(path:String)->NSDate? { do { let info = try attributesOfItemAtPath(path) return info[NSFileCreationDate] as? NSDate } catch { // print("Error : fileCreationDate : \(error)") return nil } } }
// // DataModule.swift // ViperTest // // Created by Vyacheslav Pavlov on 20.09.2018. // Copyright © 2018 Вячеслав Павлов. All rights reserved. // import UIKit class DataModule { class func create() -> DataModuleInput { let storyboard = UIStoryboard(name: "Data", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! DataViewController let presenter = DataPresenter() let interactor = DataInteractor() presenter.interactor = interactor presenter.view = viewController interactor.presenter = presenter viewController.output = presenter return presenter } }
// // ImageMatrixItem.swift // ImageMatrix // // Created by gavinning on 2018/4/9. // Copyright © 2018年 gavinning. All rights reserved. // import UIKit public class ImageMatrixItem: UIView { // var tmpCenter = CGPoint(x: 0, y: 0) // var tmpSize = CGSize(width: 0, height: 0) public var delegate: ImageMatrixItemDelegate? public override var frame: CGRect { didSet { delegate?.imageMatrixItem?(didLayout: self) self.layout() } } private lazy var deleteIcon: UIButton = { let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) btn.setImage(UIImage(named: "icon-close-white"), for: .normal) btn.contentEdgeInsets = UIEdgeInsets(top: 6, left: 14, bottom: 14, right: 6) btn.addTarget(self, action: #selector(self.deleteItem), for: .touchUpInside) return btn }() // 显示删除按钮 public var showDeleteIcon: Bool = false { didSet { showDeleteIcon ? self.addSubview(deleteIcon): deleteIcon.removeFromSuperview() } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(frame: CGRect) { super.init(frame: frame) // 溢出隐藏 self.clipsToBounds = true self.layout() } public convenience init() { self.init(frame: CGRect()) } public override func addSubview(_ view: UIView) { super.addSubview(view) // 删除按钮层级提升 if showDeleteIcon { self.bringSubview(toFront: deleteIcon) } } private func layout() { // 更新deleteIcon的位置 deleteIcon.frame.origin.x = frame.width - deleteIcon.frame.width // 删除按钮层级提升 if showDeleteIcon { self.bringSubview(toFront: deleteIcon) } } // 从父级Matrix视图删除自身 @objc private func deleteItem() { if let parent = self.superview as? ImageMatrix { let _ = parent.items.remove(of: self) delegate?.imageMatrixItem?(didRemoved: self) } } // override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // self.tmpCenter = self.center // self.tmpSize = self.frame.size // UIView.animate(withDuration: 0.15, animations: { () -> Void in // self.frame.size = CGSize(width: self.frame.size.width*0.95, height: self.frame.size.height*0.95) // self.center = self.tmpCenter // }) // } // // override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { // UIView.animate(withDuration: 0.15, animations: { () -> Void in // self.backgroundColor = .gray // self.frame.size = self.tmpSize // self.center = self.tmpCenter // }) // } }
// // DataBaseManagerProtocol.swift // FoodicsAssesment // // Created by mohamed gamal on 12/19/20. // import Foundation import Promises protocol DataBaseManagerProtocol: class { // Clears all records func clear() -> Promise<Void> func start() -> Promise<Void> func insert<Input>(data: Input) -> Promise<Void> func fetch<Query, Output>(query: Query, outputType: Output.Type) -> Promise<[Output]> func save() -> Promise<Void> }
// // Reddit_ClientApp.swift // Reddit Client // // Created by Женя on 24.05.2021. // import SwiftUI @main struct Reddit_ClientApp: App { let persistenceController = PersistenceController.shared var body: some Scene { WindowGroup { let networkManager = NetworkManager() let listViewModel = PostListViewModel(manager: networkManager) ContentView(postListViewModel: listViewModel) } } }
// // HUViewControllerProtocol.swift // HULiveDemo // // Created by 胡校明 on 16/9/2. // Copyright © 2016年 huxiaoming. All rights reserved. // import UIKit /// 自定义协议,不继承自 NSObjectProtocol 无法修饰 week 类型的对象 public protocol HUViewControllerProtocol: NSObjectProtocol { var itemAnimation: CAAnimation? { set get } var index : Int { set get } /// 静态方法,实例化一个跟控制器为 UITabBarController 的控制器 /// - parameter typeClass: 要实例化的控制器类型 /// - parameter itemIndex: tabBarItem脚标 /// - parameter itemTitle: 根控制器标签 /// - parameter itemTitleColor: tabBarItem普通状态文字颜色 /// - parameter itemSelectedTitleColor: tabBarItem选中状态文字颜色 /// - parameter itemImage: tabBarItem普通状态图标 /// - parameter selectedItemImage: tabBarItem选中状态图标 static func creat<T:UIViewController where T:HUViewControllerProtocol> (typeClass typeClass: T, itemIndex: Int, itemTitle: String, itemTitleColor: UIColor, itemSelectedTitleColor: UIColor, itemImage: UIImage, selectedItemImage: UIImage) -> T func resetTabBarItemAnimation(itemIndex: Int) -> (() -> (CAAnimation)?)? } extension HUViewControllerProtocol { public static func creat<T:UIViewController where T:HUViewControllerProtocol> (typeClass typeClass: T, itemIndex: Int, itemTitle: String, itemTitleColor: UIColor, itemSelectedTitleColor: UIColor, itemImage: UIImage, selectedItemImage: UIImage) -> T { let viewController = typeClass viewController.title = itemTitle let tabBarController = viewController.tabBarController as! HUTabBarController viewController.tabBarItem = HUTabBarItem(index: itemIndex, title: itemTitle, titleColor: itemTitleColor, selectedTitleColor: itemSelectedTitleColor, image: itemImage, selectedImage: selectedItemImage, animation: tabBarController.itemAnimation, delegate: viewController) return viewController } public func resetTabBarItemAnimation(itemIndex: Int) -> (() -> (CAAnimation)?)? { return nil } }
// // LoginView.swift // Foody2 // // Created by Sebastian Strus on 2018-06-01. // Copyright © 2018 Sebastian Strus. All rights reserved. // import UIKit class AccountView: UIView { private let imageContainer: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() private let infoContainer: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() private let buttonsContainer: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() // views to imageContainer let profileImageView: UIImageView = { let iv = UIImageView(image: #imageLiteral(resourceName: "image_user")) iv.translatesAutoresizingMaskIntoConstraints = false iv.layer.borderWidth = Device.IS_IPHONE ? 0.5 : 1 iv.layer.borderColor = UIColor.darkGray.cgColor return iv }() let cameraButton: UIButton = { let button = UIButton(title: "Camera".localized, color: AppColors.DODGER_BLUE) button.addTarget(self, action: #selector(handleCamera), for: .touchUpInside) return button }() let libraryButton: UIButton = { let button = UIButton(title: "Library".localized, color: AppColors.DODGER_BLUE) button.addTarget(self, action: #selector(handleLibrary), for: .touchUpInside) return button }() // views to info container let userNameLabel: UILabel = { let label = UILabel() label.text = "Username: ".localized return label }() let emailLabel: UILabel = { let label = UILabel() label.text = "Email: ".localized return label }() let numberOfMealsLabel: UILabel = { let label = UILabel() label.text = "Saved meals: ".localized return label }() let registrationDateLabel: UILabel = { let label = UILabel() label.text = "Registration date: ".localized return label }() // buttons to buttonsContainer let logoutButton: UIButton = { let button = UIButton(title: "Log out".localized, color: AppColors.DODGER_BLUE) button.addTarget(self, action: #selector(handleLogOut), for: .touchUpInside) return button }() let removeAccountButton: UIButton = { let button = UIButton(title: "Remove account".localized, color: AppColors.RED_BORDER) button.addTarget(self, action: #selector(handleRemoveAccount), for: .touchUpInside) return button }() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { [imageContainer, infoContainer, buttonsContainer].forEach({addSubview($0)}) //imageContainer imageContainer.widthAnchor.constraint(equalTo: widthAnchor).isActive = true imageContainer.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5).isActive = true imageContainer.topAnchor.constraint(equalTo: topAnchor).isActive = true imageContainer.addSubview(profileImageView) imageContainer.addSubview(cameraButton) imageContainer.addSubview(libraryButton) profileImageView.heightAnchor.constraint(equalTo: imageContainer.heightAnchor, multiplier: 0.7).isActive = true profileImageView.widthAnchor.constraint(equalTo: imageContainer.heightAnchor, multiplier: 0.7).isActive = true profileImageView.centerXAnchor.constraint(equalTo: imageContainer.centerXAnchor).isActive = true profileImageView.centerYAnchor.constraint(equalTo: imageContainer.centerYAnchor).isActive = true cameraButton.setAnchor(top: profileImageView.bottomAnchor, leading: profileImageView.leadingAnchor, bottom: nil, trailing: nil, paddingTop: 5, paddingLeft: 10, paddingBottom: 0, paddingRight: 0) cameraButton.widthAnchor.constraint(equalTo: profileImageView.widthAnchor, multiplier: 0.4).isActive = true libraryButton.setAnchor(top: profileImageView.bottomAnchor, leading: nil, bottom: nil, trailing: profileImageView.trailingAnchor, paddingTop: 5, paddingLeft: 0, paddingBottom: 0, paddingRight: 10) libraryButton.widthAnchor.constraint(equalTo: profileImageView.widthAnchor, multiplier: 0.4).isActive = true //info container infoContainer.widthAnchor.constraint(equalTo: widthAnchor).isActive = true infoContainer.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.30).isActive = true infoContainer.topAnchor.constraint(equalTo: imageContainer.bottomAnchor).isActive = true let stackview = createStackView(views: [userNameLabel, emailLabel, numberOfMealsLabel, registrationDateLabel]) infoContainer.addSubview(stackview) stackview.setAnchor(top: infoContainer.topAnchor, leading: infoContainer.leadingAnchor, bottom: infoContainer.bottomAnchor, trailing: infoContainer.trailingAnchor, paddingTop: 10, paddingLeft: 80, paddingBottom: 10, paddingRight: 10) // two buttons container buttonsContainer.widthAnchor.constraint(equalTo: widthAnchor).isActive = true buttonsContainer.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.20).isActive = true buttonsContainer.topAnchor.constraint(equalTo: infoContainer.bottomAnchor).isActive = true let stackView: UIStackView = UIStackView(arrangedSubviews: [logoutButton, removeAccountButton]) stackView.axis = .vertical stackView.backgroundColor = UIColor.red stackView.distribution = .fillProportionally stackView.spacing = 6 buttonsContainer.addSubview(stackView) stackView.setAnchor(top: nil, leading: nil, bottom: nil, trailing: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: Device.IS_IPHONE ? 150 : 300, height: Device.IS_IPHONE ? 70 : 140) stackView.centerYAnchor.constraint(equalTo: buttonsContainer.centerYAnchor).isActive = true stackView.centerXAnchor.constraint(equalTo: buttonsContainer.centerXAnchor).isActive = true } // Actions var cameraAction: (() -> Void)? var libraryAction: (() -> Void)? var logoutAction: (() -> Void)? var removeAccountAction: (() -> Void)? @objc func handleCamera() { cameraAction?() } @objc func handleLibrary() { libraryAction?() } @objc func handleLogOut() { logoutAction?() } @objc func handleRemoveAccount() { removeAccountAction?() } }
// // ScoreVC.swift // QuizApp // // Created by Nitish Dash on 26/07/17. // Copyright © 2017 Nitish Dash. All rights reserved. // import UIKit class ScoreVC: UIViewController { @IBOutlet weak var scoreLabel: UILabel! var score = 0 override func viewDidLoad() { super.viewDidLoad() scoreLabel.text = "\(score)%" self.navigationItem.setHidesBackButton(true, animated:true); } @IBAction func backToHomeButton(_ sender: Any) { self.performSegue(withIdentifier: "backToHome", sender: Any?.self) } }
// // DetailRouter.swift // ViperTest // // Created by Alex Golub on 10/28/16. // Copyright (c) 2016 Alex Golub. All rights reserved. // import UIKit protocol DetailRouterInput { } final class DetailRouter { weak var viewController: DetailViewController! } extension DetailRouter: ViperRouter { convenience init(withViewController controller: ViperViewController) { self.init() self.viewController = controller as! DetailViewController } }
// // Property.swift // Modeller // // Created by Ericsson on 2016-08-03. // Copyright © 2016 hedgehoglab. All rights reserved. // import Foundation import CoreData class Property: NSManagedObject { // Insert code here to add functionality to your managed object subclass func fullType() -> String { var text = "models." text += type text += "(" if self.parameters.count > 0 { text += ExporterService.newLine(1) for p in parameters { text += ExporterService.indent(2) if p.name == "" { text += "\(p.value!)" } else { text += "\(p.name!) = \(p.value!)" } if p as! Parameter != parameters.array.last as! Parameter { text += "," } text += ExporterService.newLine(1) } text += ExporterService.indent(1) } text += ")" return text } convenience init(name: String, type: String, parameters: [Parameter], context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("Property", inManagedObjectContext: context) self.init(entity: entity!, insertIntoManagedObjectContext: context) self.name = name self.type = type self.parameters = NSOrderedSet(array: parameters) } // MARK: Parameter Management func getParameters() -> [Parameter] { return self.parameters.array as! [Parameter] } func getParameter(index :Int) throws -> Parameter { if self.parameters.count > index { return self.parameters.array[index] as! Parameter } else { print("parameter not found: in getParameter(index: \(index))") throw ParameterError.NotFound } } func appendParameter(parameter: Parameter) -> Int { let mutableArray = self.parameters.mutableCopy() as! NSMutableOrderedSet mutableArray.addObject(parameter) self.parameters = mutableArray as NSOrderedSet return self.parameters.count - 1 } func insertParameter(parameter: Parameter, atIndex index: Int) throws { if self.parameters.count > index { let mutableArray = self.parameters.mutableCopy() as! NSMutableOrderedSet mutableArray.insertObject(parameter, atIndex: index) self.parameters = mutableArray as NSOrderedSet } else { throw ParameterError.InsertionError(index: index) } } func removeParameter(parameter: Parameter) { let mutableArray = self.parameters.mutableCopy() as! NSMutableOrderedSet mutableArray.removeObject(parameter) self.parameters = mutableArray as NSOrderedSet } func removeParameterAtIndex(index: Int) throws -> Parameter { if self.parameters.count > index { let mutableArray = self.parameters.mutableCopy() as! NSMutableOrderedSet let parameter = self.parameters[index] as! Parameter mutableArray.removeObjectAtIndex(index) self.parameters = mutableArray as NSOrderedSet return parameter } else { print("parameter not found: in removeParameter(index: \(index))") throw ParameterError.NotFound } } func indexOfParameter(parameter: Parameter) throws -> Int { let array = self.parameters.array as! [Parameter] let index = array.indexOf(parameter) if index != nil { return index! } else { print("index not found for parameter: in indexOfParameter(parameter: \(parameter.name))") throw ParameterError.IndexNotFound } } }
// // TabularDataRowCellModel.swift // BodyMetrics // // Created by Ken Yu on 12/1/15. // Copyright © 2015 Ken Yu. All rights reserved. // import Foundation public class TabularDataRowCellModel { let cellModels: [TabularDataCellModel] var uniqueId: String var hidden: Bool let isSubRow: Bool var isExpanded: Bool var isHeader: Bool var isExpandable: Bool var isCompleted: Bool public init(_ cellModels: [TabularDataCellModel], uniqueId: String, hidden: Bool, isSubRow: Bool = false, isExpanded: Bool = false, isHeader: Bool = false, isExpandable: Bool = false, isCompleted: Bool = false) { self.uniqueId = uniqueId self.cellModels = cellModels self.hidden = hidden self.isSubRow = isSubRow self.isExpanded = isExpanded self.isHeader = isHeader self.isExpandable = isExpandable self.isCompleted = isCompleted } }
// // DBRepoContainer.swift // Feedit // // Created by Tyler D Lawrence on 4/23/21. // import Foundation import CoreData import SwiftUI import Combine class PersistenceManager { lazy var managedObjectContext: NSManagedObjectContext = { let context = self.persistentContainer.viewContext context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return context }() lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "RSS") container.loadPersistentStores { (persistentStoreDescription, error) in if let error = error { fatalError(error.localizedDescription) } } return container }() } // MARK: - NSManagedObjectContext extension NSManagedObjectContext { func configureAsReadOnlyContext() { automaticallyMergesChangesFromParent = true mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy undoManager = nil shouldDeleteInaccessibleFaults = true } func configureAsUpdateContext() { mergePolicy = NSOverwriteMergePolicy undoManager = nil } } protocol PersistentStore { typealias DBOperation<Result> = (NSManagedObjectContext) throws -> Result func count<T>(_ fetchRequest: NSFetchRequest<T>) -> AnyPublisher<Int, Error> func fetch<T, V>(_ fetchRequest: NSFetchRequest<T>, map: @escaping (T) throws -> V?) -> AnyPublisher<Array<V>, Error> func update<Result>(_ operation: @escaping DBOperation<Result>) -> AnyPublisher<Result, Error> } struct CoreDataStack: PersistentStore { private let container: NSPersistentContainer private let isStoreLoaded = CurrentValueSubject<Bool, Error>(false) private let bgQueue = DispatchQueue(label: "com.acumen.rss.coredata") private var onStoreIsReady: AnyPublisher<Void, Error> { return isStoreLoaded .filter { $0 } .map { _ in } .eraseToAnyPublisher() } init(directory: FileManager.SearchPathDirectory = .documentDirectory, domainMask: FileManager.SearchPathDomainMask = .userDomainMask, version vNumber: UInt) { let version = Version(vNumber) container = NSPersistentContainer(name: version.modelName) if let url = version.dbFileURL(directory, domainMask) { let store = NSPersistentStoreDescription(url: url) container.persistentStoreDescriptions = [store] } container.loadPersistentStores { [weak isStoreLoaded, weak container] (storeDescription, error) in if let error = error { isStoreLoaded?.send(completion: .failure(error)) } else { container?.viewContext.configureAsReadOnlyContext() isStoreLoaded?.value = true } } // container.managedObjectModel // bgQueue.async { [weak isStoreLoaded, weak container] in // } } func count<T>(_ fetchRequest: NSFetchRequest<T>) -> AnyPublisher<Int, Error> where T : NSFetchRequestResult { return onStoreIsReady .flatMap { [weak container] in Future<Int, Error> { promise in do { let count = try container?.viewContext.count(for: fetchRequest) ?? 0 promise(.success(count)) } catch let error { promise(.failure(error)) } } } .eraseToAnyPublisher() } func fetch<T, V>(_ fetchRequest: NSFetchRequest<T>, map: @escaping (T) throws -> V?) -> AnyPublisher<Array<V>, Error> where T : NSFetchRequestResult { assert(Thread.isMainThread) let fetch = Future<Array<V>, Error> { [weak container] promise in guard let context = container?.viewContext else { return } context.performAndWait { do { let managedObjects = try context.fetch(fetchRequest) let result = managedObjects.compactMap { reqResult -> V? in do { let mapped = try map(reqResult) if let mo = reqResult as? NSManagedObject { context.refresh(mo, mergeChanges: false) } return mapped } catch { print("compactMap error: \(error)") return nil } } promise(.success(result)) } catch { promise(.failure(error)) } } } return onStoreIsReady .flatMap { fetch } .eraseToAnyPublisher() } func update<Result>(_ operation: @escaping DBOperation<Result>) -> AnyPublisher<Result, Error> { let update = Future<Result, Error> { [weak bgQueue, weak container] promise in bgQueue?.async { guard let context = container?.newBackgroundContext() else { return } context.configureAsUpdateContext() context.performAndWait { do { let result = try operation(context) if context.hasChanges { try context.save() } context.reset() promise(.success(result)) } catch { context.reset() promise(.failure(error)) } } } } return onStoreIsReady .flatMap { update } .receive(on: DispatchQueue.main) // bgqueue .eraseToAnyPublisher() } } extension CoreDataStack.Version { static var actual: UInt { 1 } } extension CoreDataStack { struct Version { private let number: UInt init(_ number: UInt) { self.number = number } var modelName: String { return "RSS" } func dbFileURL(_ directory: FileManager.SearchPathDirectory, _ domainMask: FileManager.SearchPathDomainMask) -> URL? { return FileManager.default .urls(for: directory, in: domainMask).first? .appendingPathComponent(subpathToDB) } private var subpathToDB: String { return "\(modelName).sql" } } } protocol RSSSourcesInteractor { func load(sources: Binding<[RSS]>) func store(source: RSS) func store(url: String, title: String, desc: String?, image: String?) } struct RealRSSSourcesInteractor: RSSSourcesInteractor { let dbRepository: RSSSourcesDBRepository let appState: Store<AppState> func load(sources: Binding<[RSS]>) { let cancelBag = CancelBag() dbRepository.sources().sink(receiveCompletion: { subscriptionCompletion in if case Subscribers.Completion.failure(let error) = subscriptionCompletion { print("error = \(error)") } }, receiveValue: { value in sources.wrappedValue = value }) .store(in: cancelBag) } func store(url: String, title: String, desc: String?, image: String?) { let cancelBag = CancelBag() dbRepository.store(url: url, title: title, desc: desc, image: image).sink(receiveCompletion: { subscriptionCompletion in if case Subscribers.Completion.failure(let error) = subscriptionCompletion { print("error = \(error)") } }, receiveValue: { }) .store(in: cancelBag) } func store(source: RSS) { let cancelBag = CancelBag() dbRepository.store(sources: [source]).sink(receiveCompletion: { subscriptionCompletion in if case Subscribers.Completion.failure(let error) = subscriptionCompletion { print("error = \(error)") } }, receiveValue: { }) .store(in: cancelBag) } } protocol RSSSourcesDBRepository { func hasLoadedSources() -> AnyPublisher<Bool, Error> func sources() -> AnyPublisher<Array<RSS>, Error> func store(sources: [RSS]) -> AnyPublisher<Void, Error> func store(url: String, title: String, desc: String?, image: String?) -> AnyPublisher<Void, Error> } struct RealRSSSourcesDBRepository: RSSSourcesDBRepository { let persistentStore: PersistentStore func hasLoadedSources() -> AnyPublisher<Bool, Error> { let fetchRequest: NSFetchRequest<RSS> = RSS.fetchRequest() return persistentStore .count(fetchRequest) .map { $0 > 0 } .eraseToAnyPublisher() } func sources() -> AnyPublisher<Array<RSS>, Error> { let fetchRequest: NSFetchRequest<RSS> = RSS.fetchRequest() fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createTime", ascending: false)] return persistentStore .fetch(fetchRequest) { $0 } .eraseToAnyPublisher() } func store(sources: [RSS]) -> AnyPublisher<Void, Error> { let cancelBag = CancelBag() return persistentStore .update { context in sources.forEach { $0.store(in: context) fetchNewRSS(model: $0).sink(receiveCompletion: { subscriptionCompletion in if case Subscribers.Completion.failure(let error) = subscriptionCompletion { print("error = \(error)") } }, receiveValue: { value in print("value = \(String(describing: value))") }) .store(in: cancelBag) } } } func store(url: String, title: String, desc: String?, image: String?) -> AnyPublisher<Void, Error> { return persistentStore .update { context in RSS.create(url: url, title: title, desc: desc ?? "", image: image ?? "", in: context) } } } struct SubRSSSourcesInteractor: RSSSourcesInteractor { func load(sources: Binding<[RSS]>) { } func store(source: RSS) { } func store(url: String, title: String, desc: String?, image: String?) { } } struct RootViewAppearance: ViewModifier { @Environment(\.injected) private var injected: DIContainer @State private var isActive: Bool = false let inspection = PassthroughSubject<((AnyView) -> Void), Never>() func body(content: Content) -> some View { content .onReceive(stateUpdate) { self.isActive = $0 } .onReceive(inspection) { callback in callback(AnyView(self.body(content: content))) } } private var stateUpdate: AnyPublisher<Bool, Never> { injected.appState.updates(for: \.system.isActive) } } struct AppState { var userData = UserData() var routing = ViewRouting() var system = System() } extension AppState { struct System: Equatable { var isActive: Bool = false } } extension AppState { struct UserData: Equatable { } } extension AppState { struct ViewRouting: Equatable { } } extension AppState { static func == (lhs: AppState, rhs: AppState) -> Bool { return lhs.userData == rhs.userData && rhs.routing == rhs.routing && lhs.system == rhs.system } } extension DIContainer { struct Interactors { let rssSourcesInteractor: RSSSourcesInteractor static var stub: Self { .init(rssSourcesInteractor: SubRSSSourcesInteractor()) } } } struct DIContainer: EnvironmentKey { let appState: Store<AppState> let interactors: Interactors init(appState: Store<AppState>, interactors: Interactors) { self.appState = appState self.interactors = interactors } init(appState: AppState, interactors: Interactors) { self.init(appState: Store<AppState>(appState), interactors: interactors) } static var defaultValue: Self { Self.default } private static let `default` = DIContainer(appState: AppState(), interactors: .stub) } extension EnvironmentValues { var injected: DIContainer { get { self[DIContainer.self] } set { self[DIContainer.self] = newValue } } } extension View { func inject(_ appState: AppState, _ interactors: DIContainer.Interactors) -> some View { let container = DIContainer(appState: .init(appState), interactors: interactors) return inject(container) } func inject(_ container: DIContainer) -> some View { return self .modifier(RootViewAppearance()) .environment(\.injected, container) } } typealias Store<State> = CurrentValueSubject<State, Never> extension Store { subscript<T>(keyPath: WritableKeyPath<Output, T>) -> T where T: Equatable { get { value[keyPath: keyPath] } set { var value = self.value if value[keyPath: keyPath] != newValue { value[keyPath:keyPath] = newValue self.value = value } } } func updates<Value>(for keyPath: KeyPath<Output, Value>) -> AnyPublisher<Value, Failure> where Value: Equatable { return map(keyPath).removeDuplicates().eraseToAnyPublisher() } } extension Binding where Value: Equatable { func dispatched<State>(to state: Store<State>, _ keyPath: WritableKeyPath<State, Value>) -> Self { return onSet { state[keyPath] = $0 } } } extension Binding { typealias ValueClosure = (Value) -> Void func onSet(_ perform: @escaping ValueClosure) -> Self { return .init(get: { () -> Value in self.wrappedValue }, set: { value in self.wrappedValue = value perform(value) }) } } final class CancelBag { var subscriptions = Set<AnyCancellable>() func cancel() { subscriptions.forEach { $0.cancel() } subscriptions.removeAll() } } extension AnyCancellable { func store(in cancelBag: CancelBag) { cancelBag.subscriptions.insert(self) } }
// // Episode.swift // PodcastKoCore // // Created by John Roque Jorillo on 5/22/21. // Copyright © 2021 JohnRoque Inc. All rights reserved. // import Foundation public struct Episode: Equatable, Codable { public let title: String? public let pubDate: Date? public let description: String? public let author: String? public let streamUrl: String? public let image: String? public var fileUrl: String? public init(title: String?, pubDate: Date?, description: String?, author: String?, streamURL: String?, image: String?, fileURL: String? = nil) { self.title = title self.pubDate = pubDate self.description = description self.author = author self.streamUrl = streamURL self.image = image self.fileUrl = fileURL } }
import Routing import Vapor import Leaf /// Register your application's routes here. /// /// [Learn More →](https://docs.vapor.codes/3.0/getting-started/structure/#routesswift) public func routes(_ router: Router) throws { //Save a feeling router.post("saveFeel") { (request) -> Future<Feel> in return try request.content.decode(NewFeelRequest.self).map(to: Feel.self) { newFeel in if newFeel.feel < 0 || newFeel.feel > 5 { throw HTTPError(identifier: "Vapor", reason: "Invalid request") } let feel = Feel(value: newFeel.feel) try feel.save() return feel } } //Fetch Feelings router.get("feels") { (request) -> [AggregateResult] in //let filters = try request.query.decode(FeelFilters.self) return try Feel.feels()//fetchAllFeels(for:filters) } router.get { req -> Future<View> in let leaf = try req.make(LeafRenderer.self) let feels = try Feel.feels() //let context = [String: String]() return leaf.render("home", ["feels":feels]) } }
// // UserDefaults.swift // ColorSlider // // Created by Franklin Byaruhanga on 31/05/2020. // Copyright © 2020 Franklin Byaruhanga. All rights reserved. // import UIKit.UIColor // Extending UserDefaults to handel UIColor extension UserDefaults { // Retriving of UIColor func color(forKey: String) -> UIColor? { var colorSaved: UIColor? if let colorData = data(forKey: forKey) { do { if let color = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(colorData) as? UIColor { colorSaved = color } } catch { print("Error UserDefaults") } } return colorSaved } // Saving of UIColor func set(color: UIColor?, forKey key: String) { var colorData: NSData? if let color = color { do { let data = try NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) as NSData? colorData = data } catch { print("Error UserDefaults") } } set(colorData, forKey: key) } }
// // MCGCDTimer.swift // XTAnimations // // Created by summerxx on 2023/3/30. // Copyright © 2023 夏天然后. All rights reserved. // import Foundation typealias ActionBlock = () -> () class MCGCDTimer { //单例 static let shared = MCGCDTimer() lazy var timerContainer = [String: DispatchSourceTimer]() /// GCD定时器 /// /// - Parameters: /// - name: 定时器名字 /// - timeInterval: 时间间隔 /// - queue: 队列 /// - repeats: 是否重复 /// - action: 执行任务的闭包 func scheduledDispatchTimer(WithTimerName name: String?, timeInterval: Double, queue: DispatchQueue, repeats: Bool, action: @escaping ActionBlock) { if name == nil { return } var timer = timerContainer[name!] if timer == nil { timer = DispatchSource.makeTimerSource(flags: [], queue: queue) timer?.resume() timerContainer[name!] = timer } //精度1毫秒 timer?.schedule(deadline: .now(), repeating: timeInterval, leeway: DispatchTimeInterval.milliseconds(1)) timer?.setEventHandler(handler: { [weak self] in action() if repeats == false { self?.cancleTimer(WithTimerName: name) } }) } /// 取消定时器 /// /// - Parameter name: 定时器名字 func cancleTimer(WithTimerName name: String?) { let timer = timerContainer[name!] if timer == nil { return } timerContainer.removeValue(forKey: name!) timer?.cancel() } /// 检查定时器是否已存在 /// /// - Parameter name: 定时器名字 /// - Returns: 是否已经存在定时器 func isExistTimer(WithTimerName name: String?) -> Bool { if timerContainer[name!] != nil { return true } return false } }