text
stringlengths
8
1.32M
// // webViewViewController.swift // alinaNutrisport // // Created by Brandon Gonzalez on 13/07/20. // Copyright © 2020 Easycode. All rights reserved. // import UIKit import WebKit class webViewViewController: UIViewController, WKNavigationDelegate, WKUIDelegate { @IBOutlet weak var webView: WKWebView! var urlToVisit: String! = "" var activityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() setupWebView() setupActivityIndicator() } func setupWebView() { webView.navigationDelegate = self webView.uiDelegate = self let url = URL(string: urlToVisit)! webView.load(URLRequest(url: url)) webView.allowsBackForwardNavigationGestures = true } func setupActivityIndicator() { activityIndicator = UIActivityIndicatorView() activityIndicator.center = self.webView.center activityIndicator.hidesWhenStopped = true activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge view.addSubview(activityIndicator) } func showActivityIndicator(show: Bool) { if show { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } } @IBAction func getOut(_ sender: Any) { self.dismiss(animated: true, completion: nil) } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { UIApplication.shared.isNetworkActivityIndicatorVisible = true showActivityIndicator(show: true) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { UIApplication.shared.isNetworkActivityIndicatorVisible = false showActivityIndicator(show: false) } }
// // IssueListCell.swift // Saturdays // // Created by Said Ozcan on 03/06/2017. // Copyright © 2017 Said Ozcan. All rights reserved. // import UIKit import Shimmer class IssueListCell: UITableViewCell { //MARK : Subviews let issueImageView : UIImageView = { let imageView = UIImageView(frame: CGRect.zero) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = Defines.colors.lightGray imageView.layer.masksToBounds = true imageView.layer.cornerRadius = Defines.sizes.issueListCellCornerRadius imageView.contentMode = UIViewContentMode.scaleAspectFill return imageView }() fileprivate lazy var issueTitleView : UIView = { [unowned self] in let titleView = UIView(frame: CGRect.zero) titleView.translatesAutoresizingMaskIntoConstraints = false titleView.backgroundColor = UIColor.black titleView.layer.cornerRadius = Defines.sizes.issueListCellCornerRadius titleView.layer.masksToBounds = true titleView.addSubview(self.issueTitleLabel) NSLayoutConstraint.activate([ self.issueTitleLabel.topAnchor.constraint(equalTo: titleView.topAnchor, constant:Defines.spacings.singleUnit), self.issueTitleLabel.leadingAnchor.constraint(equalTo: titleView.leadingAnchor, constant: Defines.spacings.singleUnit), self.issueTitleLabel.bottomAnchor.constraint(equalTo: titleView.bottomAnchor, constant: -Defines.spacings.singleUnit), self.issueTitleLabel.trailingAnchor.constraint(equalTo: titleView.trailingAnchor, constant: -Defines.spacings.singleUnit) ]) titleView.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) return titleView }() fileprivate let issueTitleLabel : UILabel = { let label = UILabel(frame: CGRect.zero) label.translatesAutoresizingMaskIntoConstraints = false label.font = Defines.fonts.body label.textColor = Defines.colors.white return label }() //MARK: Properties override var frame: CGRect { get { return super.frame } set (newFrame) { var frame = newFrame frame.size.width = frame.width - (2 * Defines.spacings.doubleUnit) frame.origin.x = Defines.spacings.doubleUnit super.frame = frame } } // MARK : Lifecycle override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.setupCell() self.addSubviews() self.setupLayoutConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() self.issueImageView.image = nil self.issueTitleLabel.text = nil } // MARK : Private fileprivate func setupCell() { self.backgroundColor = Defines.colors.white self.selectionStyle = .none self.layer.masksToBounds = true } fileprivate func addSubviews() { self.contentView.addSubview(self.issueImageView) self.contentView.addSubview(self.issueTitleView) } fileprivate func setupLayoutConstraints() { let spacing = Defines.spacings.doubleUnit let trailingConstraintOfTitleView = self.issueTitleView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -spacing) trailingConstraintOfTitleView.priority = UILayoutPriorityDefaultLow - 1 NSLayoutConstraint.activate([ self.issueImageView.topAnchor.constraint(equalTo: self.contentView.topAnchor), self.issueImageView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), self.issueImageView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), self.issueImageView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor), self.issueTitleView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: spacing), self.issueTitleView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -spacing), trailingConstraintOfTitleView ]) } // MARK : Public Interface func configure(with model: IssueViewModel) { self.issueTitleLabel.text = model.title } }
// // EditPhotosViewController.swift // provoq // // Created by parry on 4/26/16. // Copyright © 2016 provoq. All rights reserved. // import UIKit class EditPhotosViewController: UIViewController { var imagePicker: UIImagePickerController! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func onButtonPressed(sender: UIButton) { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in // ... } alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "Take a Photo", style: .Default) { (action) in // ... self.imagePicker = UIImagePickerController() // imagePicker.delegate = self self.imagePicker.sourceType = .Camera self.presentViewController(self.imagePicker, animated: true, completion: nil) } alertController.addAction(OKAction) let destroyAction2 = UIAlertAction(title: "Choose from Library", style: .Default) { (action) in print(action) if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary ){ print("Button capture") let imagePicker = UIImagePickerController() // imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary; imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) } } alertController.addAction(destroyAction2) let destroyAction3 = UIAlertAction(title: "Choose from Facebook", style: .Default) { (action) in print(action) // self.picker.delegate = self // self.presentViewController(self.picker, animated: true, completion: nil) } alertController.addAction(destroyAction3) let destroyAction4 = UIAlertAction(title: "Choose from Instagram", style: .Default) { (action) in print(action) self.performSegueWithIdentifier("instagram", sender: nil) } alertController.addAction(destroyAction4) self.presentViewController(alertController, animated: true) { // ... } } // MARK: OLFacebookImagePickerControllerDelegate // // func facebookImagePicker(imagePicker: OLFacebookImagePickerController!, didFinishPickingImages images: [AnyObject]!) { // dismissViewControllerAnimated(true, completion: nil) // // do something with the OLFacebookImage image objects // // } // // func facebookImagePickerDidCancelPickingImages(imagePicker: OLFacebookImagePickerController!) { // dismissViewControllerAnimated(true, completion: nil) // // } // // func facebookImagePicker(imagePicker: OLFacebookImagePickerController!, didFailWithError error: NSError!) { // // do something with the error such as display an alert to the user // // print("error") // } //getting image from camera pic func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { imagePicker.dismissViewControllerAnimated(true, completion: nil) // imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage } //getting image from camera roll func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){ self.dismissViewControllerAnimated(true, completion: { () -> Void in }) // imageView.image = image } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if let target = segue.destinationViewController as? PhotoBrowserCollectionViewController { // target.user = user; } } }
// // CategoryCell.swift // GPS // // Created by Allen Hsiao on 2020/6/27. // Copyright © 2020 Allen Hsiao. All rights reserved. // import Foundation import UIKit class CategoryCell: UITableViewCell { var category : Category var selectedLevel : Int var nextLevel : [Category] var nameLabel : UILabel = { var textLabel = UILabel() textLabel.translatesAutoresizingMaskIntoConstraints = false textLabel.backgroundColor = .clear textLabel.font = UIFont(name: "NotoSansTC-Regular", size: 17) textLabel.textColor = MYTLE textLabel.clipsToBounds = true; return textLabel }() var checkMarkImageView : UIImageView = { var imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.layer.cornerRadius = 15; imageView.clipsToBounds = true; imageView.image = #imageLiteral(resourceName: " ic_fill_check") return imageView }() var arrow : UIImageView = { var imageView = UIImageView() imageView.clipsToBounds = true; imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = #imageLiteral(resourceName: " arw_right_sm_grey") imageView.isHidden = true return imageView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { self.category = Category(id: 0, name: "", level: 0, nextLevel: []) self.selectedLevel = 0 self.nextLevel = [] super.init(style: style, reuseIdentifier : reuseIdentifier) self.backgroundColor = .clear self.addSubview(nameLabel) self.addSubview(checkMarkImageView) self.addSubview(arrow) } override func setSelected(_ selected: Bool, animated: Bool) { super .setSelected(selected, animated: animated) if (selected) { checkMarkImageView.isHidden = false nameLabel.textColor = ATLANTIS_GREEN } else { checkMarkImageView.isHidden = true nameLabel.textColor = MYTLE } } override func layoutSubviews() { super .layoutSubviews() // let theCategory = category { nameLabel.text = category.name // } if (self.category.level > selectedLevel) { nameLabel.text = " " + category.name } else { nameLabel.text = category.name } if nextLevel.count > 0 && isSelected == false { arrow.isHidden = false } else { arrow.isHidden = true } nameLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 16).isActive = true nameLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true nameLabel.heightAnchor.constraint(equalToConstant: 22).isActive = true checkMarkImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true checkMarkImageView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true checkMarkImageView.widthAnchor.constraint(equalToConstant: 30).isActive = true checkMarkImageView.heightAnchor.constraint(equalToConstant: 30).isActive = true arrow.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true arrow.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // GameInformationViewController.swift // Teachify // // Created by Christian Pfeiffer on 02.05.18. // Copyright © 2018 Christian Pfeiffer. All rights reserved. // import UIKit class GameDetailViewController: UIViewController { let gameController : GameController = GameController() @IBOutlet weak var gamelistTableView: UITableView! @IBOutlet weak var gameImage: UIImageView! @IBOutlet weak var gameDescriptionLabel: UILabel! @IBOutlet weak var gameTitleLabel: UILabel! let tabledelegate = GameDetailTableDelegate() let tabledatasource = GameDetailListDataSource() var myExercises : [TKExercise]? = nil override func viewDidLoad() { gamelistTableView.delegate = tabledelegate gamelistTableView.dataSource = tabledatasource print("View did Load!") super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(launchGame(_:)), name: .launchGame, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(setExercises(_:)), name: .exerciseSelected, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(setDetailedExercise(_:)), name: .setDetailedExercise, object: nil) } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self) } // sets a detailed Document @objc func setDetailedExercise(_ notification: Notification){ if let myExDic = notification.userInfo as Dictionary? { if let myExIndex = myExDic[0] as? Int { if let exercises = myExercises { let gametyp = exercises[myExIndex].type gameImage.image = gametyp.icon gameDescriptionLabel.text = gametyp.description gameTitleLabel.text = gametyp.name print("new Exercise selected in CardDetail: \(gametyp.name) 🔝") } } } } // Only launches the first Exercise in the Notification contained Dictionary @objc func launchGame(_ notification: Notification){ if let myDictionary = notification.userInfo as Dictionary? { if let myExercise = myDictionary[0] as? TKExercise { gameController.resetInstanceForGame(game: myExercise.type) let gameVC = gameController.getViewControllerForGame(game: myExercise.type) self.present(gameVC,animated: true) } } } // sets the Game Detail according to the index of the selected Exercise Cell @objc func setExercises(_ notification:Notification) { if let myDictionary = notification.userInfo as Dictionary? { if let newExercises = myDictionary[0] as? [TKExercise] { myExercises = newExercises let gametyp = newExercises[0].type gameImage.image = gametyp.icon gameDescriptionLabel.text = gametyp.description gameTitleLabel.text = gametyp.name tabledatasource.setExercises(exc: newExercises) gamelistTableView.reloadData() gamelistTableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!) } } } }
// // HHButton.swift // HHUIKit // // Created by master on 2019/12/31. // Copyright © 2019 com.ian.Test. All rights reserved. // import UIKit @IBDesignable open class HHButton: UIButton { var timer:DispatchSourceTimer? override open var isSelected: Bool{ didSet{ guard let _ = hhSelectedBackgroundColor else {return} if isSelected { self.backgroundColor = hhSelectedBackgroundColor }else{ self.backgroundColor = normalBackgroundColor } } } override open var isEnabled: Bool{ didSet{ guard let _ = hhDisnabledBackgroundColor else {return} if isEnabled{ guard let _ = hhSelectedBackgroundColor else {return} if isSelected { self.backgroundColor = hhSelectedBackgroundColor }else{ self.backgroundColor = normalBackgroundColor } }else{ self.backgroundColor = hhDisnabledBackgroundColor } } } @IBInspectable public var normalBackgroundColor:UIColor?{ didSet{ self.backgroundColor = normalBackgroundColor } } @IBInspectable public var hhSelectedBackgroundColor:UIColor? @IBInspectable public var hhDisnabledBackgroundColor:UIColor? @IBInspectable public var countDownNum:Double = 60{ didSet{ self._countDownNum = countDownNum } } @IBInspectable public var normalTitle:String?{ didSet{ self.setTitle(normalTitle, for: .normal) } } @IBInspectable public var countDownColor:UIColor = UIColor.lightGray var isCountting:Bool = false var _countDownNum:Double = 60 open func countDown(){ isCountting = true if isCountting{ } self.isEnabled = false self.timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main) timer?.schedule(deadline: .now(), repeating: 1) timer?.setEventHandler { if self._countDownNum == 0 { self.isEnabled = true self.isCountting = false self._countDownNum = self.countDownNum self.setTitle(self.normalTitle, for: .normal) self.timer?.cancel() }else{ self._countDownNum -= 1 DispatchQueue.main.async { self.setTitle("\(Int(self._countDownNum))S", for: .normal) } } } self.timer?.resume() } }
// // CTFIntegerRange.swift // Impulse // // Created by James Kizer on 10/7/16. // Copyright © 2016 James Kizer. All rights reserved. // import UIKit import BridgeAppSDK //public protocol SBANumberRange: class { // var minNumber: NSNumber? { get } // var maxNumber: NSNumber? { get } // var unitLabel: String? { get } // var stepInterval: Int { get } //} class CTFIntegerRange: NSObject, SBANumberRange { var minValue: Int? var maxValue: Int? var unitLabel: String? var interval: Int? var minNumber: NSNumber? { guard let minValue = self.minValue else { return nil } return NSNumber(value: minValue) } var maxNumber: NSNumber? { guard let maxValue = self.maxValue else { return nil } return NSNumber(value: maxValue) } var stepInterval: Int { return self.interval ?? 0 } }
// // JWTabBarController.swift // JW_TabBarController // // Created by Jacob Wagstaff on 8/18/17. // Copyright © 2017 Jacob Wagstaff. All rights reserved. // import UIKit open class PutItOnMyTabBarController: UITabBarController, CustomTabBarDelegate { // MARK: - View var customTabBar = CustomTabBar() override open func viewDidLoad() { super.viewDidLoad() layoutView() } // MARK: - Initial Setup func layoutView(){ view.addAutoLayoutSubview(customTabBar) NSLayoutConstraint.activate([ customTabBar.leftAnchor.constraint(equalTo: view.leftAnchor), customTabBar.rightAnchor.constraint(equalTo: view.rightAnchor), customTabBar.heightAnchor.constraint(equalTo: tabBar.heightAnchor), customTabBar.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) customTabBar.delegate = self customTabBar.setup() customTabBar.highlightSelected(index: 0) } func didSelectViewController(_ tabBarView: CustomTabBar, atIndex index: Int) { let gen = UIImpactFeedbackGenerator(style: .light) gen.impactOccurred() selectedIndex = index } // MARK: Mandatory Functions Child Class must override //Specifies how many tabs there are open func numberOfTabs() -> Int{ fatalError("subclass must implement numberOfTabBars") } //Gives TabBar all of the images it needs for when a tab is highlighted (in order of Tabs) open func highLightedImages() -> [UIImage] { fatalError("subclass must implement highLightedImages") } //Gives TabBar all of the images it needs for when a tab is not selected (in order of Tabs) open func unHighlightedImages() -> [UIImage] { fatalError("subclass must implement unHighlightedImages") } // MARK: Optional Overrides // Gives Background to Tab Bar - Default is white open func backgroundColor() -> UIColor{ return .white } // Optional Slider View that moves to selected Tab - Default is clear open func sliderColor() -> UIColor { return .clear } // Sets the height of a slider as a percentage of the total tab bar height - Default is 10% open func sliderHeightMultiplier() -> CGFloat { return 0.1 } // Sets the sliders width as a percentage of each tab bars width - Default is 100% open func sliderWidthMultiplier() -> CGFloat { return 1.0 } // Sets the animation duration for the slider default is 0.35 open func animationDuration() -> Double { return 0.35 } // MARK: Titles Defaults to none open func tabBarType() -> TabBarItemType {//Return .label return .icon } open func titles() -> [String] { return [] } open func titleColors() -> (UIColor, UIColor) { return (.white, .white) } open func fontForTitles() -> UIFont { return UIFont.systemFont(ofSize: 10) } } //extension PutItOnMyTabBarController: CustomTabBarDelegate{ // // func didSelectViewController(_ tabBarView: CustomTabBar, atIndex index: Int) { // let gen = UIImpactFeedbackGenerator(style: .light) // gen.impactOccurred() // selectedIndex = index // } // // // MARK: Mandatory Functions Child Class must override // // // //Specifies how many tabs there are // open func numberOfTabs() -> Int{ // fatalError("subclass must implement numberOfTabBars") // } // // //Gives TabBar all of the images it needs for when a tab is highlighted (in order of Tabs) // open func highLightedImages() -> [UIImage] { // fatalError("subclass must implement highLightedImages") // } // // //Gives TabBar all of the images it needs for when a tab is not selected (in order of Tabs) // open func unHighlightedImages() -> [UIImage] { // fatalError("subclass must implement unHighlightedImages") // } // // // MARK: Optional Overrides // // // Gives Background to Tab Bar - Default is white // open func backgroundColor() -> UIColor{ // return .white // } // // // Optional Slider View that moves to selected Tab - Default is clear // open func sliderColor() -> UIColor { // return .clear // } // // // Sets the height of a slider as a percentage of the total tab bar height - Default is 10% // open func sliderHeightMultiplier() -> CGFloat { // return 0.1 // } // // // Sets the sliders width as a percentage of each tab bars width - Default is 100% // open func sliderWidthMultiplier() -> CGFloat { // return 1.0 // } // // // Sets the animation duration for the slider default is 0.35 // open func animationDuration() -> Double { // return 0.35 // } // // // MARK: Titles Defaults to none // open func tabBarType() -> TabBarItemType {//Return .label // return .icon // } // // open func titles() -> [String] { // return [] // } // // open func titleColors() -> (UIColor, UIColor) { // return (.white, .white) // } // // open func fontForTitles() -> UIFont { // return UIFont() // } // //}
// // MainViewController.swift // Jojo Vectores // // Created by Marco A. Peyrot on 10/23/17. // Copyright © 2017 Marco A. Peyrot. All rights reserved. // import UIKit class MainViewController: UIViewController, RestoreQuestionState { var currentQuestionNumber = -1 var currentQuestionsAnswered = 0 @IBOutlet weak var PracticaBT: UIButton! @IBOutlet weak var EvaluacionBT: UIButton! @IBOutlet weak var EstudioBT: UIButton! @IBOutlet weak var CreditosBT: UIButton! override func viewDidLoad() { super.viewDidLoad() setButtons() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. navigationItem.title = "Atrás" if segue.identifier == "evaluation" { let targetView = segue.destination as! EvaluacionViewController targetView.delegate = self targetView.currentQuestion = currentQuestionNumber targetView.answered_questions = currentQuestionsAnswered } } // MARK: - RestoreQuestionState func setValues(questionIndex: Int, questionsAnswered: Int){ self.currentQuestionNumber = questionIndex self.currentQuestionsAnswered = questionsAnswered } func setButtons(){ let practicaColor = UIColor(rgb: 0x81C0E8) PracticaBT.backgroundColor = practicaColor PracticaBT.layer.borderColor = UIColor.black.cgColor PracticaBT.layer.borderWidth = 1.5 PracticaBT.layer.cornerRadius = 10 PracticaBT.clipsToBounds = true let evaluacionColor = UIColor(rgb: 0xCBEF43) EvaluacionBT.backgroundColor = evaluacionColor EvaluacionBT.layer.borderColor = UIColor.black.cgColor EvaluacionBT.layer.borderWidth = 1.5 EvaluacionBT.layer.cornerRadius = 10 EvaluacionBT.clipsToBounds = true let estudioColor = UIColor(rgb: 0x76ED47) EstudioBT.backgroundColor = estudioColor EstudioBT.layer.borderColor = UIColor.black.cgColor EstudioBT.layer.borderWidth = 1.5 EstudioBT.layer.cornerRadius = 10 EstudioBT.clipsToBounds = true let creditosColor = UIColor(rgb: 0xEAA78C) CreditosBT.backgroundColor = creditosColor CreditosBT.layer.borderColor = UIColor.black.cgColor CreditosBT.layer.borderWidth = 1.5 CreditosBT.layer.cornerRadius = 10 CreditosBT.clipsToBounds = true let bckColor = UIColor(rgb: 0xE0DFD5) view.backgroundColor = bckColor } override var shouldAutorotate: Bool { return true } }
// // RepairCD+CoreDataProperties.swift // Harvey // // Created by Sean Hart on 9/20/17. // Copyright © 2017 TangoJ Labs, LLC. All rights reserved. // import Foundation import CoreData extension RepairCD { @nonobjc public class func fetchRequest() -> NSFetchRequest<RepairCD> { return NSFetchRequest<RepairCD>(entityName: "RepairCD") } @NSManaged public var order: Int32 @NSManaged public var repair: String? @NSManaged public var repairID: String? @NSManaged public var structureID: String? @NSManaged public var datetime: NSDate? @NSManaged public var stage: Int32 }
// // AssetTypes.swift // WavesWallet-iOS // // Created by mefilt on 14.08.2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import Extensions import DomainLayer enum AssetDetailTypes {} extension AssetDetailTypes { enum ViewModel {} enum DTO {} } extension AssetDetailTypes { struct State: Mutating { enum TransactionStatus { case none case empty case loading case transaction([DomainLayer.DTO.SmartTransaction]) var isLoading: Bool { switch self { case .loading: return true default: return false } } } var assets: [DTO.Asset] var transactionStatus: TransactionStatus var displayState: DisplayState } enum Event { case readyView case changedAsset(id: String) case setTransactions([DomainLayer.DTO.SmartTransaction]) case setAssets([DTO.Asset]) case refreshing case tapFavorite(on: Bool) case tapSend case tapReceive case tapExchange case tapTransaction(DomainLayer.DTO.SmartTransaction) case tapHistory case showReceive(DomainLayer.DTO.SmartAssetBalance) case showSend(DomainLayer.DTO.SmartAssetBalance) case tapBurn(asset: DomainLayer.DTO.SmartAssetBalance, delegate: TokenBurnTransactionDelegate?) } struct DisplayState: DataSourceProtocol, Mutating { enum Action { case none case refresh case changedCurrentAsset case changedFavorite } var isAppeared: Bool var isRefreshing: Bool var isFavorite: Bool var isDisabledFavoriteButton: Bool var isUserInteractionEnabled: Bool var currentAsset: DTO.Asset.Info var assets: [DTO.Asset.Info] var sections: [ViewModel.Section] = [] var action: Action } } extension AssetDetailTypes.ViewModel { struct Section: SectionProtocol { enum Kind { case none case title(String) case skeletonTitle } var kind: Kind var rows: [AssetDetailTypes.ViewModel.Row] } enum Row { case balanceSkeleton case balance(AssetDetailTypes.DTO.Asset.Balance) case spamBalance(AssetDetailTypes.DTO.Asset.Balance) case viewHistory case viewHistoryDisabled case viewHistorySkeleton case lastTransactions([DomainLayer.DTO.SmartTransaction]) case transactionSkeleton case assetInfo(AssetDetailTypes.DTO.Asset.Info) case tokenBurn(AssetDetailTypes.DTO.Asset.Info) } } extension AssetDetailTypes.DTO { struct Asset { struct Info { let id: String let issuer: String let name: String let description: String let issueDate: Date let isReusable: Bool let isMyWavesToken: Bool let isWavesToken: Bool let isWaves: Bool var isFavorite: Bool let isFiat: Bool let isSpam: Bool let isGateway: Bool let sortLevel: Float let icon: AssetLogo.Icon var assetBalance: DomainLayer.DTO.SmartAssetBalance } struct Balance: Codable { let totalMoney: Money let avaliableMoney: Money let leasedMoney: Money let inOrderMoney: Money let isFiat: Bool } var info: Info let balance: Balance } } extension AssetDetailTypes.ViewModel.Section { var assetBalance: DomainLayer.DTO.SmartAssetBalance? { if let row = rows.first(where: {$0.asset != nil}) { if let asset = row.asset { return asset.assetBalance } } return nil } } extension AssetDetailTypes.ViewModel.Row { var asset: AssetDetailTypes.DTO.Asset.Info? { switch self { case .assetInfo(let info): return info default: return nil } } }
// // Warrior.swift // Rpg FrenchGame Factory // // Created by Timothy jounier on 29/09/2021. // import Foundation // Objet Guerrier qui hérite de Character class Warrior: Character { init(name: String) { // utiliser l'init de la classe mère (Caractères avec toutes les convenances) super.init(name: name, type: .Damage, lifePoints: 100, maxLife: 100, weapon: Axe()) } }
// // ShowDetailViewModel.swift // ScoopWhoop // // Created by Sachin's Macbook Pro on 23/06/21. // import UIKit class ShowDetailViewModel{ weak var showDetailsViewController: ShowDetailViewController? var showDetailsArr = [ShowDetailsModelData]() var showDetailsHeader: ShowDetails? var isPaginating = false func fetchShowDetails(pagination: Bool = false, topicSlug: String, offset: Int){ guard let showURL = URL(string: "\(Constants.showDetailsURL)\(topicSlug)&offset=\(offset)") else {return} if pagination{ isPaginating = true } URLSession.shared.dataTask(with: showURL) { (data, response, err) in if let error = err{ print(error.localizedDescription) return }else{ if let safeData = data{ do{ let jsonData = try JSONDecoder().decode(ShowDetailsModel.self, from: safeData) DispatchQueue.global().asyncAfter(deadline: .now() + (pagination ? 1.5 : 0)) { if let json = jsonData.data, let headerDetails = jsonData.showDetails{ self.showDetailsArr.append(contentsOf: json) self.showDetailsHeader = headerDetails if let offset = jsonData.nextOffset{ self.showDetailsViewController?.offsetValue = offset } DispatchQueue.main.async { [self] in self.showDetailsViewController?.detailCollectionView.reloadData() } if pagination{ self.isPaginating = false } } }}catch (let jsonErr){ print(jsonErr.localizedDescription) return } } } }.resume() } }
// // MonthlyTotalCell.swift // simpleSavings // // Created by Stephenson Ang on 1/15/20. // Copyright © 2020 Stephenson Ang. All rights reserved. // import UIKit class ExpensesCell: UITableViewCell { @IBOutlet weak var month: UILabel! @IBOutlet weak var totalExpense: UILabel! var monthlyExpense : NSNumber = 0 func currencyFormatter() -> NumberFormatter { let currencyFormatter = NumberFormatter() currencyFormatter.usesGroupingSeparator = true currencyFormatter.numberStyle = .currency // localize to your grouping and decimal separator currencyFormatter.locale = Locale.current return currencyFormatter } func configureCell(monthlyTotal: ExpenseModel) { self.month.text = monthlyTotal.month self.monthlyExpense = NSNumber(value: 0.00) let priceString = self.currencyFormatter().string(from: self.monthlyExpense)! self.totalExpense.text = priceString } }
// // AppDelegate.swift // SheypoorTest // // Created by i Daliri on 7/28/17. // Copyright © 2017 i Daliri. All rights reserved. // import UIKit import XCGLogger // TODO: Fix Response Log let log: XCGLogger = { let log = XCGLogger.default log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil, fileLevel: .debug) return log }() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UINavigationBar.appearance().barStyle = .blackOpaque UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), for:UIBarMetrics.default) return true } }
// // loginVC.swift // iOsBmoby // // Created by Magomed Souleymnov on 25/09/2016. // Copyright © 2016 BMoby. All rights reserved. // import UIKit class loginVC: UIViewController { // title & textfields @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var loginEmailTxtField: UITextField! @IBOutlet weak var passwordTxtField: UITextField! // bouttons @IBOutlet weak var loginBtn: UIButton! @IBOutlet weak var registerBtn: UIButton! @IBOutlet weak var forgotPasswordBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // MealService.swift // UBIEAT // // Created by UBIELIFE on 2016-08-15. // Copyright © 2016 UBIELIFE Inc. All rights reserved. // import UIKit typealias resultBlock = (data: Dictionary<String , AnyObject>? , error: NSError?) -> Void class MealService: NSObject { class var sharedInstance: MealService{ struct Static { static var oneToken: dispatch_once_t = 0 static var instance: MealService? = nil } dispatch_once(&Static.oneToken) { () -> Void in Static.instance = MealService() } return Static.instance! } let afRequestManager = AFHTTPSessionManager() func getRestaurantList(params: Dictionary<String , String>? , domain: String , callBack: (data: [AnyObject]? , error: NSError?) -> Void) { let url = Constant.BASE_URL + domain // // self.afRequestManager.requestSerializer.setValue("application/json", forHTTPHeaderField: "content-type") // self.afRequestManager.requestSerializer.timeoutInterval = 10 // self.afRequestManager.responseSerializer.acceptableContentTypes = NSSet.init(objects: "application/json", "text/json", "text/javascript","text/html") as? Set<String> // self.afRequestManager.requestSerializer = AFJSONRequestSerializer.init(writingOptions: NSJSONWritingOptions.init(rawValue: 0)) // // // // self.afRequestManager.GET(url, parameters: nil, progress: { (progres: NSProgress) -> Void in // }, success: { (task: NSURLSessionDataTask, data: AnyObject?) -> Void in // //callBack(data: data, error: nil) // print(data) // // }) { (task: NSURLSessionDataTask?, error: NSError) -> Void in // print(error.localizedDescription) // } UBINetwork.sharedInstance.getWithoutCache(url, params: params) { (result, error) in if result == nil{ callBack(data: nil , error: error) print(error!.localizedDescription) return } if let result = result!["data"] as? [AnyObject]{ callBack(data: result, error: nil) } } } func postRestaurantList(params: Dictionary<String , String> , domain: String , callBack: (data: [AnyObject]? , error: NSError?) -> Void) { self.afRequestManager.POST("", parameters: params, progress: { (progres: NSProgress) -> Void in }, success: { (task: NSURLSessionDataTask, data: AnyObject?) -> Void in //callBack(data: data, error: nil) print(data) }) { (task: NSURLSessionDataTask?, error: NSError) -> Void in print(error.localizedDescription) } callBack(data: nil,error: nil) } }
// // CoreDataConfig.swift // countit // // Created by David Grew on 23/12/2018. // Copyright © 2018 David Grew. All rights reserved. // import Foundation import CoreData class CoreDataConfig { public static func getCoreDataContext(test: Bool) -> NSManagedObjectContext { if test { let managedObjectModel: NSManagedObjectModel = { let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])! return managedObjectModel }() let persistantContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "countit", managedObjectModel: managedObjectModel) let description = NSPersistentStoreDescription() description.type = NSInMemoryStoreType description.shouldAddStoreAsynchronously = false container.persistentStoreDescriptions = [description] container.loadPersistentStores { (description, error) in print("error loading persistent stores") } return container }() return persistantContainer.viewContext } else { let container = NSPersistentContainer(name: "countit") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container.viewContext } } }
extension Tableau { /// Container of `terms` and `constant` that is converted from `Expression` AST. public struct RowInfo { public var terms: [Tableau.Column: Double] public var constant: Double public init(terms: [Tableau.Column: Double] = [:], constant: Double = 0) { self.terms = terms self.constant = constant } public init(expression: Expression) { switch expression { case let .variable(variable): self = .init(terms: [.variable(variable): 1]) case let .constant(value): self = .init(constant: value) case let .multiply(coeff, expr): let rowInfo = RowInfo(expression: expr) self = .init( terms: rowInfo.terms.mapValues { $0 * coeff }, constant: rowInfo.constant * coeff ) case let .add(expr1, expr2): let rowInfo1 = RowInfo(expression: expr1) let rowInfo2 = RowInfo(expression: expr2) self = .init( terms: rowInfo1.terms.merging(rowInfo2.terms, uniquingKeysWith: +), constant: rowInfo1.constant + rowInfo2.constant ) } } /// Find a preferred basic variable from `rowInfo`. /// /// - Parameter candidates: /// Slack variables that can enter into basic variable. public func findBasicColumn(candidates: [Column]) -> Column? { for (column, _) in self.terms { if column.isExternal { return column } } for candidate in candidates { if case .slackVariable = candidate { if self.terms[candidate, default: 0] < 0 { return candidate } } } return nil } /// Solve for `column` variable by modifying rowInfo's `column` to be zero /// and divide whole rowInfo by "its coefficient * `-1`". /// /// For example, if `self.terms = [x1: 1, x2: 2, x3: 3]` and `column = x3`, /// modified `self.terms` will have `[x1: -1/3, x2: -2/3]` /// which is a *basic feasible solved form*: `x3 = -1/3 * x1 + -2/3 * x2`. /// /// - Returns: Reciprocal of (previous) column's coefficient. @discardableResult public mutating func solve(column: Column) -> Double { let coeff = self.terms.removeValue(forKey: column)! let reciprocal = 1.0 / coeff self *= -reciprocal return reciprocal } } } extension Tableau.RowInfo: CustomStringConvertible { public var description: String { let terms = self.terms .sorted(by: { $0.key < $1.key }) .map { key, value -> String in value.isNearlyEqual(to: 1) ? "\(key)" : value.isNearlyEqual(to: -1) ? "-\(key)" : "\(_shortString(value))*\(key)" } .joined(separator: " + ") let constant = _shortString(self.constant) let expr = terms.isEmpty ? "\(constant)" : self.constant.isNearlyEqual(to: 0) ? "\(terms)" : "\(constant) + \(terms)" return expr.replacingOccurrences(of: "+ -", with: "- ") } }
// // IntroductionViewController.swift // TheDocument // import Foundation import Firebase import UIKit class IntroductionViewController : UIViewController { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var backButton: UIButton! var currentPage:Int = 0 override func viewDidLoad() { super.viewDidLoad() scrollView.delegate = self //startActivityIndicator() pageControl.currentPageIndicatorTintColor = Constants.Theme.mainColor pageControl.pageIndicatorTintColor = Constants.Theme.authButtonNormalBorderColor Database.database().reference().child("introduction").observeSingleEvent(of: .value, with: { (snapshot) in if let introDict = snapshot.value as? [String : [String:String] ] { var offset:CGFloat = 0 if introDict.keys.count <= 1 { self.pageControl.isHidden = true } else { self.pageControl.numberOfPages = introDict.keys.count } for key in introDict.keys { guard let screen = introDict[key], let image = screen["image"] , let title = screen["title"], let body = screen["body"] else { break } let page = self.storyboard?.instantiateViewController(withIdentifier: Constants.introductionPageVCStoryboardIdentifier) as! IntroPageViewController page.imageURLString = "\(Constants.FIRStoragePublicURL)\(image)?alt=media" page.titleString = title page.bodyString = body page.view.frame = self.view.frame.offsetBy(dx: offset * page.view.frame.width, dy: 0.0) self.addChildViewController(page) self.scrollView.addSubview(page.view) page.didMove(toParentViewController: self) offset += 1 } self.scrollView.contentSize = CGSize(width: self.view.frame.size.width * offset, height: self.view.frame.size.height - 64) self.scrollView.isPagingEnabled = true //self.stopActivityIndicator() } }) let tap = UITapGestureRecognizer(target: self, action: #selector(closeIntro)) tap.numberOfTapsRequired = 2 view.addGestureRecognizer(tap) } @objc func closeIntro() { UserDefaults.standard.set(true, forKey: Constants.shouldSkipIntroKey) self.dismiss(animated: true, completion: nil) } override var prefersStatusBarHidden : Bool { return true } @IBAction func nextPage(_ sender: UIButton) { guard (currentPage < pageControl.numberOfPages - 1) else { closeIntro(); return } currentPage += 1 var frame = scrollView.frame frame.origin.x = frame.size.width * CGFloat(currentPage) scrollView.scrollRectToVisible(frame, animated: true) } @IBAction func prevPage(_ sender: UIButton) { guard currentPage > 0 else { return } currentPage -= 1 var frame = scrollView.frame frame.origin.x = frame.size.width * CGFloat(currentPage) scrollView.scrollRectToVisible(frame, animated: true) } } extension IntroductionViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageWidth = scrollView.frame.size.width let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0))) // Update the currentPage self.pageControl.currentPage = page currentPage = self.pageControl.currentPage backButton.isHidden = page == 0 if page == self.pageControl.numberOfPages - 1 { nextButton.setImage(nil, for: .normal) nextButton.setTitle("Done", for: .normal) } else { nextButton.setTitle("", for: .normal) nextButton.setImage(UIImage(named: "ArrowForward"), for: .normal) } } }
// // MessageCarousel.swift // Lenna // // Created by MacBook Air on 2/18/19. // Copyright © 2019 sdtech. All rights reserved. // import UIKit import SDWebImage protocol CarouselButtonMessageDelegate { func CarouselMessageButton (newMessage: String) } class MessageCarousel: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, CarouselButtonDelegate { @IBOutlet weak var carouselImage: UICollectionView! var arrCarousel = [ColumnCarousel]() var btnMessageDelegate : CarouselButtonMessageDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code self.carouselImage.dataSource = self self.carouselImage.delegate = self self.carouselImage.register(UINib.init(nibName: "CarouselViewCell", bundle: nil), forCellWithReuseIdentifier: "carouselViewID") // let layout = self.carouselImage.collectionViewLayout as! UICollectionViewFlowLayout // let width = UIScreen.main.bounds.width // layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) // layout.minimumLineSpacing = 20 // layout.minimumInteritemSpacing = 20 // // layout.itemSize = CGSize(width: (width - 13) / (3/2), height: 355) } func CarouselButton(newMessage: String) { print("MessageCarousel CarouselButton", newMessage) btnMessageDelegate?.CarouselMessageButton(newMessage: newMessage) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return arrCarousel.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let dataCarousel = arrCarousel[indexPath.item] print("MessageCarousel->",dataCarousel); let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "carouselViewID", for: indexPath as IndexPath) as! CarouselViewCell cell.imageArrayCarousel.sd_setImage(with: URL(string: dataCarousel.thumbnailImageUrl), completed: nil) cell.imageArrayCarousel.layer.masksToBounds = true cell.imageArrayCarousel.layer.cornerRadius = 12 cell.imageArrayCarousel.layer.maskedCorners = [.layerMaxXMinYCorner , .layerMinXMinYCorner] let clear_text = dataCarousel.title.replacingOccurrences(of: "<br>", with: "") let clear_text_des = dataCarousel.text.replacingOccurrences(of: "<br>", with: "") cell.title.text = clear_text cell.subTitle.text = clear_text_des cell.btnDelegate = self cell.arrAction = dataCarousel.actions //auto height cell.btnList.rowHeight = UITableViewAutomaticDimension cell.btnList.reloadData() return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("MessageCarousel->2",arrCarousel[indexPath.item]) } }
// // ViewController.swift // RealmStretchyList // // Created by Thiago Hissa on 2017-08-04. // Copyright © 2017 Thiago Hissa. All rights reserved. // import UIKit import RealmSwift class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var navView: UIView! @IBOutlet weak var navHeight: NSLayoutConstraint! @IBOutlet weak var buttonBottomConstraint: NSLayoutConstraint! @IBOutlet weak var stackButton: UIStackView! @IBOutlet weak var stackHeightConstraint: NSLayoutConstraint! @IBOutlet weak var myTableView: UITableView! let realm = try! Realm() // [1] var arrayOfLanguages: Results<Language> { // [2] get { return realm.objects(Language.self) } } // var arrayOfLanguages: Results<Language>! override func viewDidLoad() { super.viewDidLoad() print(self.arrayOfLanguages.description) } //MARK: Button Actions @IBAction func addButton(_ sender: UIButton) { if self.navHeight.constant == 200 { self.navHeight.constant = 80 self.stackButton.isHidden = true self.stackButton.isHidden = true } else{ self.navHeight.constant = 200 self.stackButton.isHidden = false self.stackButton.isHidden = false } UIView.animate(withDuration: 1.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 3, options: UIViewAnimationOptions.curveEaseIn, animations: { sender.transform = sender.transform.rotated(by: CGFloat(Double.pi/4)) if self.stackButton.isHidden { self.buttonBottomConstraint.constant = 8 self.stackHeightConstraint.constant = 30 } else{ self.buttonBottomConstraint.constant = 50 self.stackHeightConstraint.constant = 60 } self.view.layoutIfNeeded() }, completion: nil) } @IBAction func swiftButtonPressed(_ sender: Any) { let language = Language() language.languageName = "Swift" language.languageImageString = "swift.png" try! realm.write{ realm.add(language) } self.myTableView.insertRows(at: [IndexPath.init(row: self.arrayOfLanguages.count-1, section: 0)], with: .automatic) } @IBAction func objcButtonPressed(_ sender: Any) { let language = Language() language.languageName = "Objective-C" language.languageImageString = "objc.png" try! realm.write{ realm.add(language) } self.myTableView.insertRows(at: [IndexPath.init(row: self.arrayOfLanguages.count-1, section: 0)], with: .automatic) } //MARK: TableView Methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arrayOfLanguages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell let language = self.arrayOfLanguages[indexPath.row] cell.cellImage.image = UIImage(named: language.languageImageString) cell.cellMainLabel.text = language.languageName cell.cellDateLabel.text = Date().description return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } // [2] func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == .delete){ let item = arrayOfLanguages[indexPath.row] try! self.realm.write({ self.realm.delete(item) }) tableView.deleteRows(at:[indexPath], with: .automatic) } } }
// // ContactViewModel.swift // Agenda // // Created by Jorge Mayta Guillermo on 7/4/20. // Copyright © 2020 Cibertec. All rights reserved. // import CoreData import SwiftUI class ContactViewModel: ObservableObject { @Published var contacts = [Contact]() let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext func getContacts(){ let request = Contact.getAllContactRequest() do { contacts = try context.fetch(request) } catch (let error){ print(error) } } func addContact(name: String){ let contact = Contact(context: context) contact.name = name saveContext() } func deleteContact(index: Int){ let contact = contacts[index] context.delete(contact) saveContext() } func saveContext(){ if context.hasChanges { do{ try context.save() getContacts() } catch (let error){ print(error) } } } }
// // Notification.Name+CustomNames.swift // WorkAndAnalyse // // Created by Ruslan Khanov on 26.05.2021. // import Foundation extension Notification.Name { static let didSignOut = Notification.Name("didSignOut") }
import AVFoundation import Foundation struct VideoSpec { var fps: Int32? var size: CGSize? } typealias ImageBufferHandler = ((_ imageBuffer: CMSampleBuffer) -> ()) typealias DepthDataHandler = ((_ depthData: AVDepthData) -> ()) class VideoCapture: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureDepthDataOutputDelegate, AVCaptureDataOutputSynchronizerDelegate { private let session = AVCaptureSession() private var videoDevice: AVCaptureDevice! private var videoConnection: AVCaptureConnection! private var depthConnection: AVCaptureConnection! private var audioConnection: AVCaptureConnection! private var previewLayer: AVCaptureVideoPreviewLayer? private let videoDeviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera, .builtInWideAngleCamera], mediaType: .video, position: .unspecified) private var outputSynchronizer: AVCaptureDataOutputSynchronizer? private let videoDataOutput = AVCaptureVideoDataOutput() private let depthDataOutput = AVCaptureDepthDataOutput() private var videoDeviceInput: AVCaptureDeviceInput! let videoDataQueue = DispatchQueue(label: "com.synesthesia.videosamplequeue") let depthDataQueue = DispatchQueue(label: "com.synesthesia.depthqueue") var imageBufferHandler: ImageBufferHandler? var depthDataHandler: DepthDataHandler? init(cameraType: CameraType, preferredSpec: VideoSpec?, previewContainer: CALayer?) { super.init() let defaultVideoDevice = videoDeviceDiscoverySession.devices.first guard let videoDevice = defaultVideoDevice else { print("Could not find any video device") fatalError() } videoDevice.updateFormatWithPreferredVideoSpec(preferredSpec: preferredSpec!) // get video-device do { videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice) } catch { print("Could not create video device input: \(error)") fatalError() } session.beginConfiguration() session.sessionPreset = AVCaptureSession.Preset.photo // Add a video input guard session.canAddInput(videoDeviceInput) else { print("Could not add video device input to the session") fatalError() } session.addInput(videoDeviceInput) // setup preview if let previewContainer = previewContainer { let previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.frame = previewContainer.bounds previewLayer.contentsGravity = kCAGravityResizeAspectFill previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill previewContainer.insertSublayer(previewLayer, at: 0) self.previewLayer = previewLayer } // setup video output videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String: NSNumber(value: kCVPixelFormatType_32BGRA)] videoDataOutput.setSampleBufferDelegate(self, queue: videoDataQueue) guard session.canAddOutput(videoDataOutput) else { fatalError() } session.addOutput(videoDataOutput) videoConnection = videoDataOutput.connection(with: AVMediaType.video) // setup depth output depthDataOutput.isFilteringEnabled = true depthDataOutput.alwaysDiscardsLateDepthData = true guard session.canAddOutput(depthDataOutput) else { fatalError() } session.addOutput(depthDataOutput) depthDataOutput.setDelegate(self, callbackQueue: videoDataQueue) depthConnection = depthDataOutput.connection(with: .depthData) depthConnection.isEnabled = true // setup the synchronizer outputSynchronizer = AVCaptureDataOutputSynchronizer(dataOutputs: [videoDataOutput, depthDataOutput]) outputSynchronizer!.setDelegate(self, queue: videoDataQueue) session.commitConfiguration() } func startCapture() { print("\(self.classForCoder)/" + #function) if session.isRunning { print("already running") return } session.startRunning() } func stopCapture() { print("\(self.classForCoder)/" + #function) if !session.isRunning { print("already stopped") return } session.stopRunning() } func resizePreview() { if let previewLayer = previewLayer { guard let superlayer = previewLayer.superlayer else {return} previewLayer.frame = superlayer.bounds } } // ========================================================================= // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { if connection.videoOrientation != .portrait { connection.videoOrientation = .portrait return } if let imageBufferHandler = imageBufferHandler { imageBufferHandler(sampleBuffer) } } func depthDataOutput(_ output: AVCaptureDepthDataOutput, didOutput depthData: AVDepthData, timestamp: CMTime, connection: AVCaptureConnection) { if let depthDataHandler = depthDataHandler { depthDataHandler(depthData) } } func dataOutputSynchronizer(_ synchronizer: AVCaptureDataOutputSynchronizer, didOutput synchronizedDataCollection: AVCaptureSynchronizedDataCollection) { if let syncedDepthData: AVCaptureSynchronizedDepthData = synchronizedDataCollection.synchronizedData(for: depthDataOutput) as? AVCaptureSynchronizedDepthData { if !syncedDepthData.depthDataWasDropped { let depthData = syncedDepthData.depthData processDepth(depthData: depthData) } } if let syncedVideoData: AVCaptureSynchronizedSampleBufferData = synchronizedDataCollection.synchronizedData(for: videoDataOutput) as? AVCaptureSynchronizedSampleBufferData { if !syncedVideoData.sampleBufferWasDropped { let videoSampleBuffer = syncedVideoData.sampleBuffer processVideo(sampleBuffer: videoSampleBuffer) } } } func processDepth(depthData: AVDepthData) { if let depthDataHandler = depthDataHandler { depthDataHandler(depthData) } } func processVideo(sampleBuffer: CMSampleBuffer) { if let imageBufferHandler = imageBufferHandler { imageBufferHandler(sampleBuffer) } } }
// // HomePageViewController.swift // // // Created by Акнур on 1/11/21. // import UIKit struct saveData { static let title = "" } class HomePageViewController: UIViewController { var data: Results? let titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.textColor = UIColor.black label.font = UIFont.boldSystemFont(ofSize: 20.0) label.backgroundColor = .white return label }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .red view.addSubview(titleLabel) titleLabel.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: nil, trailing: view.trailingAnchor, padding: .init(top: 50, left: 20, bottom: 0, right: 20), size: .init(width: 180, height: 180)) } }
// // Source.swift // TestTaskPecode // // Created by Petro on 16.09.2021. // import Foundation struct Source: Decodable, Equatable { let id: String let name: String let description: String let url: String let category: String let language: String let country: String }
// // AppDelegate.swift // Mini GitHub // // Created by Hady on 10/30/20. // Copyright © 2020 HadyOrg. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { } // Added Method // private func application(application: UIApplication, willChangeStatusBarFrame newStatusBarFrame: CGRect) { // let windows = UIApplication.shared.windows // // for window in windows { // window.removeConstraints(window.constraints) // } // } }
// // SCSortType.swift // ElsevierKit // // Created by Yuto Mizutani on 2018/09/18. // import Foundation /** Represents the sort field name and order. A plus in front of the sort field name indicates ascending order, a minus indicates descending order. If sort order is not specified (i.e. no + or -) then the order defaults to ascending (ASC). Up to three fields can be specified, each delimited by a comma. The precedence is determined by their order (i.e. first is primary, second is secondary, and third is tertiary). +/-{field name}[,+/-{field name} ex. sort=coverDate,-title - SeeAlso: https://dev.elsevier.com/documentation/ScopusSearchAPI.wadl */ public enum SCSortType: String { case artnumAscending = "+artnum" case artnumDescending = "-artnum" case citedByCountAscending = "+citedby-count" case citedByCountDescending = "-citedby-count" case coverDateAscending = "+coverDate" case coverDateDescending = "-coverDate" case creatorAscending = "+creator" case creatorDescending = "-creator" case origLoadDateAscending = "+orig-load-date" case origLoadDateDescending = "-orig-load-date" case pageCountAscending = "+pagecount" case pageCountDescending = "-pagecount" case pageFirstAscending = "+pagefirst" case pageFirstDescending = "-pagefirst" case pageRangeAscending = "+pageRange" case pageRangeDescending = "-pageRange" case publicationNameAscending = "+publicationName" case publicationNameDescending = "-publicationName" case pubYearAscending = "+pubyear" case pubYearDescending = "-pubyear" case relevancyAscending = "+relevancy" case relevancyDescending = "-relevancy" case volumeAscending = "+volume" case volumeDescending = "-volume" }
// // Space.swift // StudyUp // // Created by Mitchel Eppich on 2017-03-31. // Copyright © 2017 SFU Health++. All rights reserved. // import Foundation import Firebase var current_space : Space = Space() var space_list : [Space] = [Space]() class Space : NSObject { enum amount { case base case none case low case medium case high var text : String { switch self { case .none : return "None" case .low : return "Low" case .medium : return "Medium" case .high : return "High" default : return "None" } } func index (at : Int) -> String { switch at { case 0 : return "None" case 1 : return "Low" case 2 : return "Medium" case 3 : return "High" default : return "None" } } } enum temp { case base case cold case comfortable case warm case hot var text : String { switch self { case .cold : return "Cold" case .comfortable : return "Comfortable" case .warm : return "Warm" case .hot : return "Hot" default : return "None" } } func index (at : Int) -> String { switch at { case 0 : return "Cold" case 1 : return "Comfortable" case 2 : return "Warm" case 3 : return "Hot" default : return "None" } } } var location = CLLocation() var loc : [String : Any]? var id : String = FIRDatabase.database().reference().childByAutoId().key var name : String = "No Name" var desc : String = "There is no description for this space" var num_of_seats : String = amount.none.text var num_of_ports : String = amount.none.text var occupancy : String = amount.none.text var temperature : String = temp.comfortable.text var wifi_str : String = amount.none.text var noise_level : String = amount.none.text var food_allowed : String = "No" var image : UIImage = #imageLiteral(resourceName: "bg pattern dark") var icon : UIImage = #imageLiteral(resourceName: "study spaceeeee-1") var rating : Int = 0 var review : [Review] = [Review]() var temp_reviews : [[String : Any]]? // prep space info into a dictioanry func spaceInformationToDictionary() -> [String : Any] { var reviews : [[String : Any]] = [[String : Any]]() for r in review { reviews.append(r.toDictionary()) } let space = [ "id" : id as NSString, "name" : name as NSString, "desc" : desc as NSString, "num_of_seats" : num_of_seats, "num_of_ports" : num_of_ports, "occupancy" : occupancy, "temperature" : temperature, "wifi_str" : wifi_str, "noise_level" : noise_level, "food_allowed" : food_allowed, "rating" : rating, "temp_reviews" : reviews, "loc" : [ "coord" : [ "lon" : location.coordinate.longitude, "lat" : location.coordinate.latitude ] as NSDictionary ] as NSDictionary ] as [NSString : Any] return space as [String : Any] } // Set the current user object values to that of a passed in dictionary func loadDataToSpace (data : [String : Any]) { let space = self space.setValuesForKeys(data) loc = loc?["coord"] as? [String : Any] self.location = CLLocation(latitude: loc!["lat"] as! CLLocationDegrees, longitude: loc!["lon"] as! CLLocationDegrees) } // save space to the databse func saveSpaceToDatabase() { let space = self let space_id = space.id let path = "space/\(space_id)" let data = spaceInformationToDictionary() c_data.saveToDatabase(path: path, data: data) } // load all study spaces from the datasbe func loadAllStudySpaces(completion : @escaping (_ result : [Space]) -> Void) { // Initiate group list space_list.removeAll() let path = "space" var data : [String : Any]? c_data.loadFromDatabase(path: path, completion: { (result : [String : Any]) in let spaces = result for space_data in spaces { data = space_data.value as? [String : Any] let space = Space() space.loadDataToSpace(data: data!) // Create Individual Reviews if space.temp_reviews != nil { for r in space.temp_reviews! { let new_review : Review = Review() new_review.rating = r["rating"] as! Int new_review.user_id = r["user_id"] as! String new_review.review = r["review"] as! String space.review.append(new_review) } } space_list.append(space) // }) } completion(space_list) }) } func showSpaceOnMap(mapView : MKMapView) { for space in space_list { let anno = SpaceAnnotation(space : space) mapView.addAnnotation(anno) } } } class SpaceAnnotation : NSObject, MKAnnotation { var coordinate = CLLocationCoordinate2D() var title: String? var subtitle: String? var space : Space = Space() // Definition for a map annotation for our groups init(space : Space) { self.space = space self.coordinate = space.location.coordinate self.title = self.space.name self.subtitle = "" } } // Review class for spaces class Review : NSObject { var review : String = "" var rating : Int = 0 var user_id : String = "" var user : User? func toDictionary() -> [String : Any]{ return [ "user_id" : user_id, "rating" : rating, "review" : review ] as [String : Any] } func loadReviewUser() { var isLocal = false // Check if user is locally stored for user in user_list { if user.uid == self.user_id { self.user = user print("Found local ref of user review.") isLocal = true break } } if isLocal { return } // Load if user is not locally stored self.user?.loadUserFromDatabase(uid: self.user_id, completion: { (result : User) in self.user = result print("Loaded ref of user from database.") }) } }
// // StoreListRouter.swift // BGL // // Created by RAVI KUMAR on 21/04/19. // Copyright © 2019 RAVI KUMAR. All rights reserved. // import Foundation import UIKit class StoreListRouter: StoreListPresenterToRouter { static func createModule() -> UINavigationController { let viewController = self.createViewController() let navigation = UINavigationController(rootViewController: viewController) return navigation } static func createViewController() -> StoreListViewController { let storyboard = UIStoryboard(name: "MapContainer", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "StoreListViewController") as! StoreListViewController let model = StoreListModel() let router = StoreListRouter() vc.model = model return vc } }
// // TimeViewController.swift // ElsieApp // // Created by Ross Harding on 8/17/19. // Copyright © 2019 Harding LLC. All rights reserved. // import UIKit class TimeViewController: ParentViewController { @IBOutlet var timeLabel: UILabel! var timer = Timer() var startDate: Double = 1551592800 // Epoch time of beginning of relationship override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(calculateTime), userInfo: nil, repeats: true) timer.fire() } override func viewWillDisappear(_ animated: Bool) { timer.invalidate() } @objc func calculateTime() { let now = Date().timeIntervalSince1970 let total = now - startDate let years = floor(total / 31536000) let days = floor((total - (years * 31536000)) / 86400) let hours = floor((total - (years * 31536000) - (days * 86400)) / 3600) let minutes = floor((total - (years * 31536000) - (days * 86400) - (hours * 3600)) / 60) let seconds = floor((total - (years * 31536000) - (days * 86400) - (hours * 3600) - (minutes * 60))) let yearString = years.format(with: "year") let dayString = days.format(with: "day") let hourString = hours.format(with: "hour") let minuteString = minutes.format(with: "minute") let secondString = seconds.format(with: "second") let formattedString = yearString + dayString + hourString + minuteString + secondString timeLabel.text = formattedString } }
// // EmojTextView.swift // StoryReader // // Created by 020-YinTao on 2017/5/12. // Copyright © 2017年 020-YinTao. All rights reserved. // import UIKit class EmojTextView: PlaceholderTextView, ToolBarEvent, EmojiOperation, EmojiInputProtocol { private var oldFont: UIFont! private var emojiView: EmojView! private var emojiToolBar: EmjoToolBar! private var mediaView: MedieView! // 表情大小 public var e_emojiSize: CGSize! public var e_topInset: CGFloat = -4 weak var mediaDelegate: EmojTextViewDelegate? override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) _init() } override func awakeFromNib() { super.awakeFromNib() _init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func _init() { e_emojiSize = CGSize.init(width: e_font.lineHeight, height: e_font.lineHeight) oldFont = e_font super.font = oldFont setupView() } private func setupView() { emojiView = EmojView.init(emjos: (EmojImage.emjoSource(.custom) ?? [String]()), emjoType: .custom) emojiView.delegate = self mediaView = MedieView.init(datasource: ["chat_add_image"]) mediaView.delegate = self } private func setupEmojiToolBar() { if emojiToolBar == nil { emojiToolBar = EmjoToolBar.init(frame: CGRect.init(x: 0, y: 0, width: PPScreenW, height: 45)) emojiToolBar.delegate = self } if e_showToolBar == true { inputAccessoryView = emojiToolBar } else { inputAccessoryView = nil } } private func resetTextStyle() { let wholeRange = NSMakeRange(0, textStorage.length) textStorage.removeAttribute(NSAttributedString.Key.font, range: wholeRange) textStorage.addAttribute(NSAttributedString.Key.font, value: oldFont, range: wholeRange) font = oldFont } //MARK: //MARK: 属性设置 /// 字体 var e_font: UIFont = UIFont.systemFont(ofSize: 15) { didSet { oldFont = e_font super.font = e_font } } /// 是否显示键盘工具栏 var e_showToolBar: Bool = false { didSet { setupEmojiToolBar() } } //MARK: //MARK: EmojiInputProtocol func e_emojiShow() { inputView = emojiView reloadInputViews() if isFirstResponder == false { becomeFirstResponder() } } func e_emojiHidden(reload: Bool) { inputView = nil if reload == true { reloadInputViews() } } func e_deleteText() { if selectedRange.location > 0 { textStorage.replaceCharacters(in: NSMakeRange(selectedRange.location - 1, 1), with: "") } } func e_insertEmoji(emojName: String) { let emojiTextAttachment = EmojTextAttachment.init(EmojImage.removeSuffix(emojName), e_emojiSize, e_topInset) emojiTextAttachment.image = EmojImage.emojImage(emojName) //插入表情 textStorage.insert(NSAttributedString.init(attachment: emojiTextAttachment), at: selectedRange.location) //移动光标 selectedRange = NSMakeRange(selectedRange.location + 1, selectedRange.length) //插入表情之后需要重新设置字体样式,不然字体大小会改变 resetTextStyle() } var e_totleText: String? { let resultString = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if resultString.count == 0 { return nil }else { return textStorage.plainString() } } func mediaShow() { inputView = mediaView reloadInputViews() if isFirstResponder == false { becomeFirstResponder() } } func mediaHidden(reload: Bool) { inputView = nil if reload == true { reloadInputViews() } } //MARK: //MARK: ToolBarEvent func toolBarEevnt(eventType: ToolBarEventType, button: UIButton) { switch eventType { case .emoji: button.isSelected == true ? e_emojiShow() : e_emojiHidden(reload: true) break default: break } } //MARK: //MARK: EmojiOperation func inputEmoj(emojName: String) { e_insertEmoji(emojName: emojName) } func deleteEmoj(emojName: String) { e_deleteText() } } extension EmojTextView: MediaProtocol { func mediaItem(selected idx: Int) { mediaDelegate?.mediaSelected(idx: idx) } } protocol EmojTextViewDelegate: class { func mediaSelected(idx: Int) }
// // SideMenu+Animator.swift // Arsenal // // Created by Zhu Shengqi on 26/02/2017. // Copyright © 2017 Zhu Shengqi. All rights reserved. // #if os(iOS) import UIKit extension SideMenuTransitionContext { final class Animator: NSObject, UIViewControllerAnimatedTransitioning { // MARK: - Subtypes enum SlideDirection { case left case right } // MARK: - Properties var presenting: Bool var slideDirection: SlideDirection = .left // MARK: - Init & Deinit init(presenting: Bool) { self.presenting = presenting super.init() } // MARK: - Transition Duration func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { if transitionContext!.isInteractive { return 0.25 } else { return 0.5 } } // MARK: - Transition Animation func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView let containerBounds = containerView.frame let fromVC = transitionContext.viewController(forKey: .from)! let fromView = transitionContext.view(forKey: .from) ?? fromVC.view! let fromViewStartFrame = transitionContext.initialFrame(for: fromVC) var fromViewFinalFrame = transitionContext.finalFrame(for: fromVC) let toVC = transitionContext.viewController(forKey: .to)! let toView = transitionContext.view(forKey: .to) ?? toVC.view! var toViewStartFrame = transitionContext.initialFrame(for: toVC) let toViewFinalFrame = transitionContext.finalFrame(for: toVC) if presenting { switch slideDirection { case .left: toViewStartFrame.origin = CGPoint(x: containerBounds.width, y: 0) case .right: toViewStartFrame.origin = CGPoint(x: -toViewFinalFrame.width, y: 0) } toViewStartFrame.size = toViewFinalFrame.size toView.frame = toViewStartFrame containerView.addSubview(toView) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseInOut, animations: { toView.frame = toViewFinalFrame }, completion: { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } else { switch slideDirection { case .left: fromViewFinalFrame.origin = CGPoint(x: containerBounds.width, y: 0) case .right: fromViewFinalFrame.origin = CGPoint(x: -fromViewStartFrame.width, y: 0) } if transitionContext.isInteractive { UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveLinear, animations: { fromView.frame = fromViewFinalFrame }, completion: { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } else { UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseInOut, animations: { fromView.frame = fromViewFinalFrame }, completion: { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } } } } } #endif
/// Copyright (c) 2019 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import UIKit class MessagesViewController: UIViewController { private let defaultBackgroundColor = UIColor( red: 249/255.0, green: 249/255.0, blue: 249/255.0, alpha: 1) @IBOutlet weak var tableView: UITableView! private let toolbarView = ToolbarView() private var toolbarViewTopConstraint: NSLayoutConstraint! private var messages: [Message] = [] var contact: Contact? { didSet { loadViewIfNeeded() messages = contact?.messages() ?? [] tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = defaultBackgroundColor tableView.backgroundColor = defaultBackgroundColor setupToolbarView() let gesture = UITapGestureRecognizer(target: self, action: #selector(hideToolbarView)) gesture.numberOfTapsRequired = 1; gesture.delegate = self tableView.addGestureRecognizer(gesture) } private func setupToolbarView() { view.addSubview(toolbarView) toolbarViewTopConstraint = toolbarView.topAnchor.constraint( equalTo: view.safeAreaLayoutGuide.topAnchor, constant: -100) toolbarViewTopConstraint.isActive = true toolbarView.leadingAnchor.constraint( equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 30).isActive = true toolbarView.delegate = self } @objc func hideToolbarView() { toolbarViewTopConstraint.constant = -100 UIView.animate( withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 1, options: [], animations: { self.toolbarView.alpha = 0 self.view.layoutIfNeeded() },completion: nil) } } //MARK: - Toolbar View Delegate extension MessagesViewController: ToolbarViewDelegate { func toolbarView(_ toolbarView: ToolbarView, didFavoritedWith tag: Int) { messages[tag].isFavorited.toggle() } func toolbarView(_ toolbarView: ToolbarView, didLikedWith tag: Int) { messages[tag].isLiked.toggle() } } //MARK: - Gesture Delegate extension MessagesViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view == tableView } } //MARK: - UITableView Delegate & Data Source extension MessagesViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let message = messages[indexPath.row] let cellIdentifier = message.sentByMe ? "RightBubble" : "LeftBubble" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MessageBubbleTableViewCell cell.messageLabel.text = message.text cell.backgroundColor = defaultBackgroundColor if !message.sentByMe { cell.delegate = self } return cell } } //MARK: - Message Bubble Cell Delegate extension MessagesViewController: MessageBubbleTableViewCellDelegate { func doubleTapForCell(_ cell: MessageBubbleTableViewCell) { toolbarViewTopConstraint.constant = cell.frame.midY toolbarView.alpha = 0.95 if let indexPath = tableView.indexPath(for: cell) { let message = messages[indexPath.row] toolbarView.update(isLiked: message.isLiked, isFavorited: message.isFavorited) toolbarView.tag = indexPath.row } UIView.animate( withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 1, options: [], animations: { self.view.layoutIfNeeded() }, completion: nil) } } extension MessagesViewController: ContactListTableViewControllerDelegate { func contactListTableViewController( _ contactListTableViewController: ContactListTableViewController, didSelectContact selectedContact: Contact ) { contact = selectedContact } }
// // KUIDragStepperSlider.swift // KUIDragStepperSlider // // Created by kofktu on 2016. 12. 15.. // Copyright © 2016년 Kofktu. All rights reserved. // import UIKit @IBDesignable public class KUIDragStepperSlider: UIControl { @IBInspectable public var sliderHeight: CGFloat = 2.0 { didSet { setNeedsDisplay() } } @IBInspectable public var thumbCircleRadius: CGFloat = 8.0 { didSet { setNeedsDisplay() } } @IBInspectable public var thumbCircleColor: UIColor = UIColor.white { didSet { setNeedsDisplay() } } @IBInspectable public var thumbCircleShadowColor: UIColor? { didSet { setNeedsDisplay() } } @IBInspectable public var thumbCircleShadowRadius: CGFloat? { didSet { setNeedsDisplay() } } @IBInspectable public var thumbCircleShadowSize: CGSize? { didSet { setNeedsDisplay() } } @IBInspectable public var minimumTrackTintColor: UIColor = UIColor.blue { didSet { setNeedsDisplay() } } @IBInspectable public var maximumTrackTintColor: UIColor = UIColor.lightGray { didSet { setNeedsDisplay() } } @IBInspectable public var horizontalMargin: CGFloat = 15.0 { didSet { setNeedsDisplay() } } @IBInspectable public var minimumValue: CGFloat = 0 @IBInspectable public var maximumValue: CGFloat = 100 @IBInspectable public var value: CGFloat = 0.5 { didSet { if value < 0.0 { value = 0.0 } else if value > 1.0 { value = 1.0 } else { setNeedsDisplay() } } } @IBInspectable public var dragEnabledThreshold: CGFloat = 40.0 public var stepperMinimumValue: CGFloat { return min(minimumValue + (CGFloat(stepperIndex) * stepperRange), maximumValue) } public var stepperMaximumValue: CGFloat { return min(stepperMinimumValue + stepperRange, maximumValue) } public var stepperValue: CGFloat { return stepperMinimumValue + (stepperRange * value) } @IBInspectable public var stepperIndex = 0 @IBInspectable public var stepperRange: CGFloat = 20.0 @IBInspectable public var stepperThreshold: CGFloat = 0.7 public var onStepperValueRangeHandler: ((CGFloat, CGFloat) -> Void)? public override func draw(_ rect: CGRect) { guard let contextRef = UIGraphicsGetCurrentContext() else { super.draw(rect) return } let minX = horizontalMargin + thumbCircleRadius let maxX = rect.width - minX let midY = rect.height / 2.0 let width = maxX - minX // background contextRef.setFillColor(maximumTrackTintColor.cgColor) contextRef.fill(CGRect(origin: CGPoint(x: minX, y: midY - (sliderHeight / 2.0)), size: CGSize(width: width, height: sliderHeight))) // foreground contextRef.setFillColor(minimumTrackTintColor.cgColor) contextRef.fill(CGRect(origin: CGPoint(x: minX, y: midY - (sliderHeight / 2.0)), size: CGSize(width: width * value, height: sliderHeight))) // circle let cx = minX + (width * value) - thumbCircleRadius let cy = midY - thumbCircleRadius let circleRect = CGRect(origin: CGPoint(x: cx, y: cy), size: CGSize(width: thumbCircleRadius * 2.0, height: thumbCircleRadius * 2.0)) if let color = thumbCircleShadowColor { let radius = thumbCircleShadowRadius ?? 2.0 let size = thumbCircleShadowSize ?? CGSize(width: 0.0, height: 2.0) contextRef.saveGState() contextRef.setShadow(offset: size, blur: radius, color: color.cgColor) contextRef.fillEllipse(in: circleRect) contextRef.restoreGState() } contextRef.setFillColor(thumbCircleColor.cgColor) contextRef.fillEllipse(in: circleRect) } public override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { return offsetHandler(touch.previousLocation(in: self), offset: touch.location(in: self)) } public override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { return offsetHandler(touch.previousLocation(in: self), offset: touch.location(in: self)) } public override func endTracking(_ touch: UITouch?, with event: UIEvent?) { guard let touch = touch else { return } let _ = offsetHandler(touch.previousLocation(in: self), offset: touch.location(in: self)) } public override func cancelTracking(with event: UIEvent?) { } // MARK: - Private private func offsetHandler(_ prev: CGPoint, offset: CGPoint, stepper: Bool = true) -> Bool { let width = frame.width let sliderWidth = width - (horizontalMargin * 2.0) let minX = horizontalMargin + thumbCircleRadius let cx = minX + (sliderWidth * self.value) guard fabs(prev.x - cx) < dragEnabledThreshold else { return false } if stepper { let value = horizontalMargin * stepperThreshold if offset.x < value { if decrease() { return false } } else if offset.x > width - value { if increase() { return false } } } self.value = (offset.x - horizontalMargin) / sliderWidth sendActions(for: .valueChanged) return true } private func increase() -> Bool { let maxIndex = Int(maximumValue / stepperRange) guard stepperIndex + 1 < maxIndex else { return false } stepperIndex += 1 value = 0.5 onStepperValueRangeHandler?(stepperMinimumValue, stepperMaximumValue) return true } private func decrease() -> Bool { guard stepperIndex - 1 >= 0 else { return false } stepperIndex -= 1 value = 0.5 onStepperValueRangeHandler?(stepperMinimumValue, stepperMaximumValue) return true } }
// // ICSystemAlert.swift // ICMS // // Created by Adam on 2021/2/11. // import Foundation import UIKit //import SwiftMessages import PKHUD class ICSystemAlert { typealias CIAlertActionBlock = (_ idx: UInt, _ name: String) -> Void typealias CICancelActionBlock = () -> Void class func promptMessage(_ message: String, confirmHandler: @escaping CIAlertActionBlock) { ICSystemAlert.alertWith(titleArray: ["确定"], message: message, preferredStyle: .alert, confirmHandler: confirmHandler, cancelHandler: nil) } class func alertWith(title: String = "提示", titleArray: [String] = ["确定"], message: String, preferredStyle: UIAlertController.Style = .alert, confirmHandler: @escaping CIAlertActionBlock, cancelHandler: CICancelActionBlock?) { //创建用于显示alertController的UIViewController let alertVC = UIViewController.init() let alertController = UIAlertController(title: title, message: message, preferredStyle: preferredStyle) for i in 0..<titleArray.count { let title = titleArray[i] let confirmAction = UIAlertAction(title: title, style: .default) { (action) in alertVC.view.removeFromSuperview() if confirmHandler != nil { confirmHandler(UInt(i), title) } } alertController .addAction(confirmAction) } if preferredStyle == .actionSheet { let cancel = UIAlertAction(title: "取消", style: .cancel) { (canceAction) in alertVC.view.removeFromSuperview() if cancelHandler != nil { cancelHandler!() } } alertController .addAction(cancel) } UIApplication.shared.keyWindow?.addSubview(alertVC.view) alertVC.present(alertController, animated: true) { } } class func actionSheet(title: String = "提示", titleArray: [String], message: String, confirmHandler: @escaping CIAlertActionBlock) { ICSystemAlert.alertWith(title: title, titleArray: titleArray, message: message, preferredStyle: .actionSheet, confirmHandler: confirmHandler, cancelHandler: nil) } class func actionSheet(title: String = "提示", titleArray: [String], message: String, confirmHandler: @escaping CIAlertActionBlock, cancelHandler: @escaping CICancelActionBlock) { ICSystemAlert.alertWith(title: title, titleArray: titleArray, message: message, preferredStyle: .actionSheet, confirmHandler: confirmHandler, cancelHandler: cancelHandler) } // class func show(title: String = "提示", _ message: String, theme: Theme = .info) { // let alert = MessageView.viewFromNib(layout: .cardView) // alert.configureTheme(theme) // // alert.configureDropShadow() // alert.configureContent(title: title, body: message) // alert.button?.isHidden = true // var config = SwiftMessages.defaultConfig // config.presentationContext = .window(windowLevel: .alert) // SwiftMessages.show(config: config, view: alert) // // } } let kShowWarningDelayDurationD: Float = 0.15 extension UIView { typealias CIHUDCompleteHander = () -> Void func showBusy() { let hud = PKHUD.sharedHUD hud.contentView = PKHUDProgressView() hud.show() } func hideBusyHUD() { PKHUD.sharedHUD.hide() } func showProgress(_ word: String, completeHander: CIHUDCompleteHander?) { let hud = PKHUD.sharedHUD hud.contentView = PKHUDProgressView() hud.show() hud.hide(afterDelay: Double(kShowWarningDelayDurationD*Float(word.utf8.count))) { (success) in if completeHander != nil { completeHander!() } } } func showWarning(_ word: String, completeHander: CIHUDCompleteHander?) { let hud = PKHUD.sharedHUD hud.contentView = PKHUDProgressView() hud.show() hud.hide(afterDelay: Double(kShowWarningDelayDurationD*Float(word.utf8.count))) { (success) in if completeHander != nil { completeHander!() } } } func showSuccess(_ word: String, completeHander: CIHUDCompleteHander?) { let hud = PKHUD.sharedHUD hud.contentView = PKHUDSuccessView(subtitle: word) hud.show() hud.hide(afterDelay: Double(kShowWarningDelayDurationD*Float(word.utf8.count))) { (success) in if completeHander != nil { completeHander!() } } } func showError(_ word: String, completeHander: CIHUDCompleteHander?) { let hud = PKHUD.sharedHUD let view = PKHUDErrorView(subtitle: word) hud.contentView = view hud.show() hud.hide(afterDelay: Double(kShowWarningDelayDurationD*Float(word.utf8.count))) { (success) in if completeHander != nil { completeHander!() } } } }
// // DetailsVC.swift // iOSshopTestApp // // Created by Elias on 23/06/2019. // Copyright © 2019 Elias. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import SQLite class DetailsVC: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var shortDescription: UILabel! @IBOutlet weak var priceWithDisc: UILabel! @IBOutlet weak var price: UILabel! @IBOutlet weak var details: UITextView! @IBOutlet weak var favButton: UIButton! var element : Element? var resurs : JSON? var db : Connection! override func viewDidLoad() { super.viewDidLoad() db = DataBase.getDataConnection() setTitleLogo(navigationItem: navigationItem) getJson(id: element!.id) if(DataBase.checkIfFav(dataBase: db, id: element!.id)) { favButton.setImage(UIImage(named: "fav.png"), for: .normal) } } @IBAction func onFavButtonClickDo(_ sender: Any) { if(element?.fav == false) { element?.fav = true favButton.setImage(UIImage(named: "fav.png"), for: .normal) DataBase.addRow(dataBase: db, id: element!.id) } else { element?.fav = false favButton.setImage(UIImage(named: "empty_fav.png"), for: .normal) DataBase.deleteRow(dataBase: db, id: element!.id) } } func getJson(id: Int) { let parameters = "?id=\(id)" let urlStr = "http://185.181.231.32:5000/product"+parameters func getStrikeText(text : String) -> NSMutableAttributedString{ let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: text) attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: NSMakeRange(0, attributeString.length)) return attributeString } Alamofire.request(urlStr).responseJSON { (responseData) -> Void in if((responseData.result.value) != nil) { let swiftyJsonVar = JSON(responseData.result.value!) self.resurs = swiftyJsonVar let url = URL(string: swiftyJsonVar["image"].string!) let data = try? Data(contentsOf: url!) if(data != nil){ self.imageView.image = UIImage(data: data!)! self.titleLabel.text = swiftyJsonVar["title"].string! self.shortDescription.text = swiftyJsonVar["short_description"].string! let price = swiftyJsonVar["price"].double! let disc = swiftyJsonVar["sale_precent"].double! let discP = price-price/100*disc self.price.attributedText = getStrikeText(text: "$ "+String(price)) self.priceWithDisc.text = "$ "+String(format: "%.1f", ceil(discP*10)/10) self.details.text = swiftyJsonVar["details"].string! } } } } public func setTitleLogo( navigationItem : UINavigationItem ) { //Title View navigationItem.rightBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: self, action: nil) let imageView = UIImageView(image: UIImage(named: "logo_transp.png")) imageView.contentMode = .scaleAspectFit navigationItem.titleView = imageView } }
// // ContentView.swift // LoginRegister // // Created by Joker on 2020/4/15. // Copyright © 2020 ntoucs. All rights reserved. // import SwiftUI struct ContentView: View { @State private var un = "" @State private var pd = "" @State private var loginID = "" @State private var nowTimeHour = 0 @State private var weatherIcon = "sun.max" @State private var weatherUpdateTime = "" @State private var weatherlocationName = "" @State private var weatherTheDayHT = "" @State private var weatherTheDayLT = "" @State private var weatherTheDayT = "" @State private var weatherTheDayH = "" @State private var showAlert = false @State private var showView = false @State private var showProfileView = false @State private var showRegisterView = false @State private var showForgetPasswordView = false @State var usertokenID:String @State var userID:String @State var userConGetProfile:UGProfileDec var body: some View { NavigationView{ VStack{ VStack(alignment: .leading){ HStack{ Image(systemName: self.weatherIcon) .resizable() .scaledToFill() .frame(width: 55, height: 55) //.clipped() Text(weatherlocationName + "今日天氣") .font(.system(size: 25)) }.padding(.bottom, 30) Text("今日高溫:" + weatherTheDayHT + "°C") Text("今日低溫:" + weatherTheDayLT + "°C") Text("現在溫度:" + weatherTheDayT + "°C") Text("現在濕度:" + weatherTheDayH + "%") } .foregroundColor(Color(red: 195/255, green: 233/255, blue: 233/255)) .font(.system(size: 20)) .padding(.trailing, 150) HStack{ Image(systemName: "person") .foregroundColor(Color.white) Text("帳號") .foregroundColor(Color.white) TextField("", text: $un) .foregroundColor(Color.white) }.padding() .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(red: 231/255, green: 161/255, blue: 205/255), lineWidth: 2)) .padding() HStack{ Image(systemName: "lock") .foregroundColor(Color.white) Text("密碼") .foregroundColor(Color.white) SecureField("Password", text:$pd) .foregroundColor(Color.white) } .padding() .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(red: 231/255, green: 161/255, blue: 205/255), lineWidth: 2)) .padding() .padding(.bottom, 30) VStack{ Button(action: { ApiControl.shared.LoginAPI(LoginUserName: self.un, LoginPassWord: self.pd){ (result) in switch result { case .success(let userProfile): self.usertokenID = userProfile.sessionToken self.userID = userProfile._embedded.user.id userDefaults.set(userProfile._embedded.user.id, forKey: "userLoginAPPID") print("Loing Get the AppID:" + userDefaults.string(forKey: "userLoginAPPID")!) ApiControl.shared.GetProfileAPI(UserID: self.userID){ (result) in switch result{ case .success(let userGetProfile): self.userConGetProfile = userGetProfile self.showProfileView = true case .failure( _): break } } case .failure( _): self.showAlert = true } } }) { Text("登入") .font(.system(size: 30)) .frame(width:310) .padding(.all, 10) .foregroundColor(.white) .background(LinearGradient(gradient: Gradient(colors: [Color(red:91/255,green:191/255,blue:236/255), Color(red:250/255,green:191/255,blue:221/255)]), startPoint: .leading, endPoint: .trailing)) .cornerRadius(15) }.alert(isPresented: $showAlert){() -> Alert in return Alert(title: Text("帳號或密碼錯誤!!"))} .padding(.bottom, 20) NavigationLink(destination: ProfileView(userGetProfile: self.userConGetProfile), isActive: $showProfileView){ EmptyView() } Button(action:{ self.showRegisterView = true }){ Text("註冊") .font(.system(size: 30)) .frame(width:310) .padding(.all, 10) .foregroundColor(.white) .background(LinearGradient(gradient: Gradient(colors: [Color(red:91/255,green:191/255,blue:236/255), Color(red:250/255,green:191/255,blue:221/255)]), startPoint: .leading, endPoint: .trailing)) .cornerRadius(15) }.padding(.bottom, 20) .sheet(isPresented: $showRegisterView){RegisterView()} Button(action:{ self.showForgetPasswordView = true }){ Text("忘記密碼") .font(.system(size: 30)) .frame(width:310) .padding(.all, 10) .foregroundColor(.white) .background(LinearGradient(gradient: Gradient(colors: [Color(red:91/255,green:191/255,blue:236/255), Color(red:250/255,green:191/255,blue:221/255)]), startPoint: .leading, endPoint: .trailing)) .cornerRadius(15) }.padding(.bottom, 20) .sheet(isPresented: $showForgetPasswordView){ForgetPassword()} } }.background(Image("Background")) .navigationBarTitle(Text("專屬於你的-星座APP").bold()) }.onAppear{ UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor(red: 195/255, green: 233/255, blue: 233/255, alpha: 1)] self.AutoLogin() userDefaults.set("unknown", forKey: "userLoginAPPID") self.GetWeather() self.nowTimeHour = self.GetTime() self.weatherIcon = self.ShowTheWeatherIcon(nowTime: self.nowTimeHour) } } func GetWeather() -> Void{ ApiControl.shared.GetWeatherToday(locationName: "基隆"){ (result) in switch result{ case .success(let weatherDec): print("Get Weather!!") self.weatherlocationName = weatherDec.cwbopendata.location[0].locationName self.weatherTheDayHT = weatherDec.cwbopendata.location[0].weatherElement[14].elementValue.value self.weatherTheDayLT = weatherDec.cwbopendata.location[0].weatherElement[16].elementValue.value self.weatherTheDayT = weatherDec.cwbopendata.location[0].weatherElement[3].elementValue.value if(weatherDec.cwbopendata.location[0].weatherElement[4].elementValue.value == "1"){ self.weatherTheDayH = weatherDec.cwbopendata.location[0].weatherElement[4].elementValue.value + "00" } else{ self.weatherTheDayH = String(weatherDec.cwbopendata.location[0].weatherElement[4].elementValue.value.dropFirst(2)) } case .failure( _): print("ERROR") } } } func GetTime() -> Int{ let date = Date() let calendar = Calendar.current let hour = calendar.component(.hour, from: date) //let minutes = calendar.component(.minute, from: date) //print(minutes) return hour } func ShowTheWeatherIcon(nowTime:Int) -> String { if nowTime >= 6 && nowTime <= 18{ return "sun.max" } else{ return "moon.stars" } } func AutoLogin() -> Void { if userDefaults.string(forKey: "userLoginAPPID")! != "unknown" { ApiControl.shared.GetProfileAPI(UserID: userDefaults.string(forKey: "userLoginAPPID")!){ (result) in switch result{ case .success(let userGetProfile): self.userConGetProfile = userGetProfile self.showProfileView = true case .failure( _): break } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(usertokenID: "", userID: "", userConGetProfile: UGProfileDec(id: "", status: "", created: "", lastLogin: "", profile: ProfileUG(firstName: "", lastName: "", email: "", login: "", birthday: "", profileUrl: ""))) } }
// // Item.swift // Todos // // Created by Jia Lu on 2019-07-17. // Copyright © 2019 Jia Lu. All rights reserved. // import Foundation class Item { var title: String = "" var done: Bool = false }
// // FortuneViewController // BareBones // // Created by Edward Smith on 10/3/17. // Copyright © 2017 Branch. All rights reserved. // import UIKit import Branch class FortuneViewController: UIViewController, UITextViewDelegate { // MARK: - Member Variables @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var linkTextView: UITextView! @IBOutlet weak var shareButton: UIButton! var message: String? var branchURL : URL? { didSet { updateUI() } } var branchImage : UIImage? { didSet { updateUI() } } // MARK: - View Controller Lifecycle static func instantiate() -> FortuneViewController { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "FortuneViewController") return controller as! FortuneViewController } override func viewDidLoad() { super.viewDidLoad() self.imageView.layer.borderColor = UIColor.darkGray.cgColor self.imageView.layer.borderWidth = 0.5 self.imageView.layer.cornerRadius = 2.0 self.linkTextView.textContainer.maximumNumberOfLines = 1 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(_ : animated) updateUI() createLink() } func textViewDidChangeSelection(_ textView: UITextView) { if self.linkTextView.text.count > 0 { self.linkTextView.selectedRange = NSMakeRange(0, self.linkTextView.text.count) } } // MARK: - UI Updates func updateUI() { guard let messageLabel = self.messageLabel else { return } linkTextView.text = branchURL?.absoluteString ?? "" imageView.image = branchImage message = message ?? "" if let message = message { messageLabel.text = message + "”" } } func createLink() { if branchURL != nil { return } if message?.count == 0 { self.showAlert(title: "No message to send!", message: "") return } // Add some content to the Branch object: let buo = BranchUniversalObject.init() buo.title = "Bare Bones Branch Example" buo.contentDescription = "A mysterious fortune." buo.contentMetadata.customMetadata["message"] = self.message ?? "" buo.contentMetadata.customMetadata["name"] = UIDevice.current.name // Set some link properties: let linkProperties = BranchLinkProperties.init() linkProperties.channel = "Bare Bones Example" // Generate the link asynchronously: WaitingViewController.showWithMessage( message: "Getting link...", activityIndicator: true, disableTouches: true ) buo.getShortUrl(with: linkProperties) { (urlString: String?, error: Error?) in WaitingViewController.hide() if let s = urlString { self.branchURL = URL.init(string: s) AppData.shared.linksCreated += 1 self.generateQR() } else if let error = error { self.showAlert(title: "Can't create link!", message: error.localizedDescription) } else { self.showAlert(title: "Can't creat link!", message: "") } } } func generateQR() { guard let url = self.branchURL else { return } // Make the QR code: let data = url.absoluteString.data( using: String.Encoding.isoLatin1, allowLossyConversion: false ) let filter = CIFilter(name: "CIQRCodeGenerator") filter?.setValue(data, forKey: "inputMessage") filter?.setValue("H", forKey: "inputCorrectionLevel") guard var qrImage = filter?.outputImage else { return } // We could stop here with the qrImage. But let's scale it up and add a logo. // Scale: let scaleX = 210 * UIScreen.main.scale let transformScale = scaleX/qrImage.extent.size.width let transform = CGAffineTransform(scaleX: transformScale, y: transformScale) let scaleFilter = CIFilter(name: "CIAffineTransform") scaleFilter?.setValue(qrImage, forKey: "inputImage") scaleFilter?.setValue(transform, forKey: "inputTransform") qrImage = (scaleFilter?.outputImage)! // Add a logo: UIGraphicsBeginImageContext(CGSize(width: scaleX, height: scaleX)) let rect = CGRect(x: 0, y: 0, width: scaleX, height: scaleX) let image = UIImage.init(ciImage: qrImage) image.draw(in:rect); var centerRect = CGRect(x: 0, y: 0, width: scaleX/2.5, height: scaleX/2.5) centerRect.origin.x = (rect.width - centerRect.width) / 2.0 centerRect.origin.y = (rect.height - centerRect.height) / 2.0 let branchLogo = UIImage.init(named: "BranchLogo") branchLogo?.draw(in:centerRect) self.branchImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } func shareLink() { guard let url = self.branchURL, let cgImage = self.branchImage?.cgImage, let imagePNG = UIImage.init(cgImage: cgImage).pngData() else { return } let text = "Follow this link to reveal the mystic fortune enclosed..." let activityController = UIActivityViewController.init( activityItems: [text, url, imagePNG], applicationActivities: [] ) activityController.title = "Share Your Fortune" activityController.popoverPresentationController?.sourceView = shareButton activityController.popoverPresentationController?.sourceRect = shareButton.bounds activityController.setValue("My Fortune", forKey: "subject") present(activityController, animated: true, completion: nil) } @IBAction func shareLinkAction(_ sender: Any) { self.shareLink() } }
// // LabelProviding.swift // Transitions // // Created by Ilgar Ilyasov on 1/31/19. // Copyright © 2019 Lambda School. All rights reserved. // import UIKit protocol LabelProviding { var label: UILabel! { get } }
// // EventsViewController.swift // LPFeatures // // Created by Milos Jakovljevic on 18/03/2020. // Copyright © 2020 Leanplum. All rights reserved. // import UIKit import Eureka import Leanplum class EventsViewController: FormViewController { private let segmentedControl = UISegmentedControl(items: ["Events", "Triggers"]) override func viewDidLoad() { super.viewDidLoad() LabelRow.defaultCellSetup = { cell, row in cell.selectionStyle = .default } LabelRow.defaultCellUpdate = { cell, row in row.deselect(animated: true) } addSegmentedControl() buildEvents() } func addSegmentedControl() { segmentedControl.addTarget(self, action: #selector(EventsViewController.didChangeSegment), for: .valueChanged) segmentedControl.selectedSegmentIndex = 0; segmentedControl.sizeToFit() navigationItem.titleView = segmentedControl } @objc func didChangeSegment() { title = segmentedControl.titleForSegment(at: segmentedControl.selectedSegmentIndex) if segmentedControl.selectedSegmentIndex == 0 { buildEvents() } else { buildTriggers() } } } // MARK: - Events extension EventsViewController { func buildEvents() { form.removeAll() buildTrack() buildAdvance() buildUserId() buildUserAttributes() buildDeviceId() buildForceContentUpdate() } func buildTrack() { let section = Section("Track") section <<< AccountRow { $0.title = "Event name" $0.placeholder = "enter name" } section <<< KeyValueRow { $0.value = KeyValue() let deleteAction = SwipeAction(style: .destructive, title: "Delete") { (action, row, completionHandler) in completionHandler?(true) } $0.trailingSwipe.actions = [deleteAction] } section <<< ButtonRow { $0.title = "Add param" }.onCellSelection { (cell, row) in let kvrow = KeyValueRow { $0.value = KeyValue() let deleteAction = SwipeAction(style: .destructive, title: "Delete") { (action, row, completionHandler) in completionHandler?(true) } $0.trailingSwipe.actions = [deleteAction] } try? section.insert(row: kvrow, after: section.allRows[section.allRows.count - 3]) } section <<< ButtonRow { $0.title = "Send event" }.onCellSelection { (cell, row) in var event: String? var params: [String: Any] = [:] for row in section.allRows { if let row = row as? AccountRow { event = row.value } if let row = row as? KeyValueRow { if let key = row.cell.keyTextField.text, key != "", // Do not allow empty parameter names let value = row.cell.valueTextField.text { params[key] = value } } } guard let _event = event else { return } if params.isEmpty { Leanplum.track(_event) } else { Leanplum.track(_event, params: params) } } form +++ section } func buildAdvance() { let section = Section("Advance to state") section <<< AccountRow { $0.title = "State" $0.placeholder = "enter state" $0.tag = "state" } section <<< KeyValueRow { $0.value = KeyValue() let deleteAction = SwipeAction(style: .destructive, title: "Delete") { (action, row, completionHandler) in completionHandler?(true) } $0.trailingSwipe.actions = [deleteAction] } section <<< ButtonRow { $0.title = "Add param" }.onCellSelection { (cell, row) in let kvrow = KeyValueRow { $0.value = KeyValue() let deleteAction = SwipeAction(style: .destructive, title: "Delete") { (action, row, completionHandler) in completionHandler?(true) } $0.trailingSwipe.actions = [deleteAction] } try? section.insert(row: kvrow, after: section.allRows[section.allRows.count - 3]) } section <<< ButtonRow { $0.title = "Send state" }.onCellSelection { (cell, row) in var state: String? var params: [String: Any] = [:] for row in section.allRows { if let row = row as? AccountRow { state = row.value } if let row = row as? KeyValueRow { if let key = row.cell.keyTextField.text, key != "", // Do not allow empty parameter names let value = row.cell.valueTextField.text { params[key] = value } } } guard let _state = state else { return } if params.isEmpty { Leanplum.advance(state: _state) } else { Leanplum.advance(state: _state, params: params) } } form +++ section } func buildUserId() { let section = Section("User ID") section <<< AccountRow { $0.title = "User ID" $0.placeholder = "enter id" $0.tag = "userid" } section <<< ButtonRow { $0.title = "Set UserID" }.onCellSelection { (cell, row) in let accountRow: AccountRow? = section.rowBy(tag: "userid") if let value = accountRow?.value { Leanplum.setUserId(value) } } form +++ section } func buildUserAttributes() { let section = Section("User Attributes") section <<< AccountRow { $0.tag = "user_attribute_key" $0.title = "Key" $0.placeholder = "enter key" } section <<< AccountRow { $0.tag = "user_attribute_value" $0.title = "Value" $0.placeholder = "enter value" } section <<< ButtonRow { $0.title = "Set user attributes" }.onCellSelection { cell, row in let keyRow: AccountRow? = section.rowBy(tag: "user_attribute_key") let valueRow: AccountRow? = section.rowBy(tag: "user_attribute_value") if let key = keyRow?.value, let value = valueRow?.value { let attributes: [String : Any] = [key : value] Leanplum.setUserAttributes(attributes) } } form +++ section } func buildDeviceId() { let section = Section("Device ID") section <<< AccountRow { $0.title = "Device ID" $0.placeholder = "enter id" $0.tag = "deviceId" } section <<< ButtonRow { $0.title = "Set DeviceID" }.onCellSelection { (cell, row) in let accountRow: AccountRow? = section.rowBy(tag: "deviceId") if let value = accountRow?.value { Leanplum.setDeviceId(value) } } section <<< ButtonRow { $0.title = "Set IDFA" }.onCellSelection { (cell, row) in AdsTrackingManager.showNativeAdsPrompt() } form +++ section } func buildForceContentUpdate() { let section = Section("Force content update") section <<< ButtonRow { $0.title = "Force Content Update" }.onCellSelection({ (cell, row) in Leanplum.forceContentUpdate({ }) }) form +++ section } } // MARK: - Triggers extension EventsViewController { func buildTriggers() { form.removeAll() let section = Section("Triggers") section <<< LabelRow { $0.title = "Track" $0.value = "testEvent" }.onCellSelection { row, cell in Leanplum.track(cell.value!) } section <<< LabelRow { $0.title = "Advance" $0.value = "testState" }.onCellSelection { row, cell in Leanplum.advance(state: cell.value!) } section <<< LabelRow { $0.title = "SetUserAttribute" $0.value = "{ age: \"(random)\" }" }.onCellSelection { row, cell in Leanplum.setUserAttributes(["age": String(arc4random())]) } form +++ section buildLimits() buildChains() buildPriorities() } func buildLimits() { let section = Section(header: "Limits", footer: "Limited by set amount per session or lifetime") section <<< LabelRow { $0.title = "Session Limit" $0.value = "3" }.onCellSelection { row, cell in Leanplum.advance(state: "sessionLimit") } section <<< LabelRow { $0.title = "Lifetime Limit" $0.value = "3" }.onCellSelection { row, cell in Leanplum.advance(state: "lifetimeLimit") } form +++ section } func buildChains() { let section = Section(header: "Chained messages", footer: "Messages that are chained one to another") section <<< LabelRow { $0.title = "Chained message" $0.value = "chainedInApp" }.onCellSelection { row, cell in Leanplum.track(cell.value!) } form +++ section } func buildPriorities() { let section = Section(header: "Priorities", footer: "Messages that have different priorities") section <<< LabelRow { $0.title = "Track" $0.value = "DifferentPrioritySameTime" }.onCellSelection { row, cell in Leanplum.track(cell.value!) } form +++ section } }
// // XHDataMacroDefinition.swift // ObjcTools // // Created by douhuo on 2021/2/18. // Copyright © 2021 wangergang. All rights reserved. // //MARK: - UserDefaults let userDefaults = UserDefaults.standard
// // GameDetailTableDelegate.swift // Teachify // // Created by Christian Pfeiffer on 24.06.18. // Copyright © 2018 Christian Pfeiffer. All rights reserved. // import UIKit class GameDetailTableDelegate: NSObject,UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedExercise :[Int : Int] = [0:indexPath.row] NotificationCenter.default.post(name: .setDetailedExercise, object: nil, userInfo: selectedExercise) } }
// // Adapter+Logging.swift // CodableStore // // Created by Jakub Knejzlik on 21/03/2018. // import Foundation final public class CodableStoreLoggingAdapter<E: CodableStoreEnvironment>: CodableStoreAdapter<E> { public typealias LoggingFn = (_ items: Any...) -> Void public var loggingFn: LoggingFn public init(loggingFn: LoggingFn? = nil) { self.loggingFn = loggingFn ?? { (items: Any...) in print(items) } } override public func transform(request: Provider.RequestType) -> Provider.RequestType { self.loggingFn("[CodableStore:request]", request.debugDescription) return request } override public func transform(response: Provider.ResponseType) -> Provider.ResponseType { self.loggingFn("[CodableStore:response]", response.debugDescription) return response } override public func handle<T: Decodable>(error: Error) throws -> T? { self.loggingFn("[CodableStore:error]", error.localizedDescription) return nil } }
// // ReminderController.swift // ReminderApp // // Created by Michael Flowers on 1/30/20. // Copyright © 2020 Michael Flowers. All rights reserved. // import Foundation import CoreData //class ReminderController { // static let shared = ReminderController() // var fetchedResultsController: NSFetchedResultsController<Reminder> // // init(){ // //initialize an instance of fetchedResultsController and assign it to the variable // let fetchRequest: NSFetchRequest<Reminder> = Reminder.fetchRequest() // let sortDesriptors = [NSSortDescriptor(key: "radius", ascending: true), NSSortDescriptor(key: "wantsAlertOnEntrance", ascending: true)] // fetchRequest.sortDescriptors = sortDesriptors // let nsfr = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.shared.mainContext, sectionNameKeyPath: "radius", cacheName: nil) // self.fetchedResultsController = nsfr // do { // try self.fetchedResultsController.performFetch() // } catch { // print("Error in: \(#function)\n Readable Error: \(error.localizedDescription)\n Technical Error: \(error)") // } // } // // //MARK: - CRUD FUNCTIONS // func createReminder(withNote note: String, wantsAlertOnEntrance: Bool, wantsAlertOnExit: Bool, longitude: Double, latitude: Double, radius: Double) -> Reminder { // let reminder = Reminder(note: note, wantsAlertOnEntrance: wantsAlertOnEntrance, wantsAlertOnExit: wantsAlertOnExit, longitude: longitude, latitude: latitude, radius: radius) // saveToPersistentStore() // return reminder // } // // func update(reminder: Reminder, with newNote: String, newRadius: Double, newExit: Bool, newEntrance: Bool){ // reminder.note = newNote // reminder.radius = newRadius // reminder.wantsAlertOnEntrance = newEntrance // reminder.wantsAlertOnExit = newExit // saveToPersistentStore() // } // // func delete(reminder: Reminder){ // CoreDataStack.shared.mainContext.delete(reminder) // saveToPersistentStore() // } // // // func saveToPersistentStore(){ // do { // try CoreDataStack.shared.mainContext.save() // } catch { // print("Error in: \(#function)\n Readable Error: \(error.localizedDescription)\n Technical Error: \(error)") // } // } // // // // // // // // //}
// // Schuylkill_AppApp.swift // Schuylkill-App // // Created by Sam Hicks on 2/5/21. // import SwiftUI import Amplify import AWSS3 import AmplifyPlugins import Resolver import Foundation import UIKit import WatchConnectivity import RxSwift import RxCocoa import CoreMotion import SwiftyBeaver @main struct Shredded: App { // var firstView = try! ApplicationLoadFactory.getFirstView() @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { OnboardingView() } } public init() {} }
// // ViewController.swift // Filetener // // Created by Alexander Larionov on 14.11.15. // Copyright © 2015 Alexander Larionov. All rights reserved. // import UIKit class Stage { var filters : [String : Double] var currentStage : String init(){ self.filters = ["greyScale":0,"negative":0,"magicTool":0,"sepia":0,"contrast":0] self.currentStage = "" } } class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var image : UIImage? var photo : ImageProcessor? let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let transitionLeft : CATransition = CATransition() var isFiltered : Bool = false let returnButImage : UIImage = UIImage(named: "return")! let cancelButImage : UIImage = UIImage(named: "back_icon")! var filterStage : Stage = Stage() @IBOutlet weak var originalImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() image = UIImage(named:"soup") photo = ImageProcessor(photo:image!) SecondaryMenu.translatesAutoresizingMaskIntoConstraints = false SecondaryMenu.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.9) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } // Seconadary Menu @IBOutlet weak var cancelFilterBut: UIButton! @IBOutlet weak var topMenu: UIView! @IBOutlet var SecondaryMenu: UIView! @IBOutlet weak var SepiaBut: UIButton! @IBOutlet weak var ImageToggle: UIButton! @IBOutlet weak var NegativeBut: UIButton! @IBOutlet weak var MagicTool: UIButton! @IBOutlet weak var GreyScale: UIButton! @IBOutlet weak var filterSlider: UISlider! @IBAction func CancelAllFilters(sender: AnyObject) { self.ImageView.image = photo!.applyFilter("cancel", value: 2).toUIImage() filterStage = Stage.init() self.isFiltered = false self.CancelBut.enabled = false self.cancelFilterBut.enabled = false filterSlider.maximumValue = 3 filterSlider.minimumValue = 1 filterSlider.value = 1 } @IBAction func GreyScaleAction(sender: UIButton) { tapOnFilterBut("greyScale") } @IBAction func NegativeButAction(sender: UIButton) { tapOnFilterBut("negative") } @IBAction func MagicToolAction(sender: UIButton) { tapOnFilterBut("magicTool") } @IBAction func ButToSepia(sender: UIButton) { tapOnFilterBut("sepia") } @IBAction func ContrastAction(sender: AnyObject) { tapOnFilterBut("contrast") } @IBAction func slideFilter(sender: AnyObject) { let slidervalue = Double(filterSlider.value) self.ImageView.image = photo!.applyFilter(filterStage.currentStage, value: slidervalue).toUIImage() filterStage.filters[filterStage.currentStage] = Double(filterSlider.value) } //FilterStaging func tapOnFilterBut(filter : String){ if (filter != "sepia"){ if(filterStage.filters[filter]==0){ self.ImageView.image = photo!.applyFilter(filter, value: 1).toUIImage() filterStage.filters[filter] = 1.0 filterSlider.maximumValue = 3 filterSlider.minimumValue = 1 }else{ filterSlider.maximumValue = 3 filterSlider.minimumValue = 1 } }else{ if(filterStage.filters[filter]==0){ self.ImageView.image = photo!.applyFilter(filter, value: 0.1).toUIImage() filterStage.filters[filter] = 0.1 filterSlider.maximumValue = 0.3 filterSlider.minimumValue = 0.1 }else{ filterSlider.maximumValue = 0.3 filterSlider.minimumValue = 0.1 } } self.isFiltered = true self.CancelBut.enabled = true self.cancelFilterBut.enabled = true filterStage.currentStage = filter filterSlider.setValue(Float(filterStage.filters[filter]!), animated: true) } // Nav Bar //Main Scene @IBOutlet weak var ImageView: UIImageView! @IBOutlet weak var CancelBut: UIButton! @IBOutlet weak var FilterBut: UIButton! @IBOutlet weak var MainMenu: UIView! // Main Menu // Photo Button Action Sheet @IBAction func onNewPhoto(sender: AnyObject) { let actionSheet = UIAlertController(title: "New Photo", message: nil, preferredStyle: .ActionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .Default, handler: { action in self.showCamera() })) actionSheet.addAction(UIAlertAction(title: "Album", style: .Default, handler: { action in self.showAlbum() })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self.presentViewController(actionSheet, animated: true, completion: nil) } func showCamera() { let cameraPicker = UIImagePickerController() cameraPicker.delegate = self cameraPicker.sourceType = .Camera self.presentViewController(cameraPicker, animated: true, completion: nil) } func showAlbum() { let albumPicker = UIImagePickerController() albumPicker.delegate = self albumPicker.sourceType = .PhotoLibrary self.presentViewController(albumPicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { dismissViewControllerAnimated(true, completion: nil) if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { var size = CGSize(width: 200, height: 200) var imageIcon = RBSquareImageTo(image, size: size) var smallIcon = ImageProcessor(photo: imageIcon) let sepiaPhoto = smallIcon.applyFilter("sepia", value: 0.1).toUIImage() smallIcon = ImageProcessor(photo: imageIcon) let negativePhoto = smallIcon.applyFilter("negative", value: 2).toUIImage() smallIcon = ImageProcessor(photo: imageIcon) let greyScalePhoto = smallIcon.applyFilter("greyScale", value: 2).toUIImage() smallIcon = ImageProcessor(photo: imageIcon) let magicPhoto = smallIcon.applyFilter("magicTool", value: 2).toUIImage() smallIcon = ImageProcessor(photo: imageIcon) let contrastPhoto = smallIcon.applyFilter("contrast", value: 1).toUIImage() self.SepiaBut.setImage(sepiaPhoto, forState: .Normal) self.NegativeBut.setImage(negativePhoto, forState: .Normal) self.GreyScale.setImage(greyScalePhoto, forState: .Normal) self.MagicTool.setImage(magicPhoto, forState: .Normal) self.ImageToggle.setImage(contrastPhoto, forState: .Normal) size = CGSize(width: 600, height: 600) imageIcon = RBSquareImageTo(image, size: size) self.originalImage.image = imageIcon self.photo = ImageProcessor(photo: imageIcon) ImageView.image = imageIcon } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } //Share Button @IBAction func onShare(sender: AnyObject) { let activitySheet = UIActivityViewController(activityItems: [ImageView.image!], applicationActivities: nil) self.presentViewController(activitySheet, animated: true, completion: nil) } //Cancel Button @IBAction func CancelAction(sender: UIButton) { if isFiltered{ showOriginalImage() self.CancelBut.setImage(self.returnButImage, forState: .Normal) self.isFiltered = false }else{ showFiltredImage() self.CancelBut.setImage(self.cancelButImage, forState: .Normal) self.isFiltered = true } } @IBAction func onFilterTap(sender: UIButton) { if (sender.selected){ hideSecondaryMenu() sender.selected = false }else{ ShowSecondaryMenu() sender.selected = true } } func ShowSecondaryMenu(){ self.SecondaryMenu.hidden = false self.topMenu.hidden = false self.SecondaryMenu.alpha = 0 UIView.animateWithDuration(0.4) { self.SecondaryMenu.alpha = 1 self.topMenu.alpha = 1 } } func hideSecondaryMenu(){ UIView.animateWithDuration(0.4, animations: { self.SecondaryMenu.alpha = 0 self.topMenu.alpha = 0 } ){ completed in if completed == true{ self.SecondaryMenu.hidden = true self.topMenu.hidden = true } } } //Image Toggling @IBAction func holdImage(sender: AnyObject) { if isFiltered{ showOriginalImage() }else{ showFiltredImage() } } @IBAction func upImage(sender: AnyObject) { if isFiltered{ showFiltredImage() }else{ showOriginalImage() } } func showOriginalImage () { self.originalImage.hidden = false UIView.animateWithDuration(0.7) { self.ImageView.alpha = 0 } } func showFiltredImage(){ UIView.animateWithDuration(0.7, animations: { self.ImageView.alpha = 1 } ){ completed in if completed == true{ self.originalImage.hidden = true } } } }
// // UINavigationBarAppearanceExtensions.swift // UsersApp-SwiftUI // // Created by Jorge Luis Rivera Ladino on 4/09/21. // import UIKit extension UINavigationBarAppearance { func setup(backgroundColor: UIColor) -> UINavigationBarAppearance { let apperance = UINavigationBarAppearance() apperance.largeTitleTextAttributes = [ .foregroundColor: UIColor.white ] apperance.titleTextAttributes = [ .foregroundColor: UIColor.white ] apperance.backgroundColor = backgroundColor return apperance } }
// // ViewController.swift // SImageHandler // // Created by SkaCoder on 08/26/2021. // Copyright (c) 2021 SkaCoder. All rights reserved. // import UIKit import SImageHandler class ViewController: UIViewController { @IBOutlet weak var myImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() myImageView.applyBorder(color: .green, width: 5.0) // Do any additional setup after loading the view, typically from a nib. myImageView.corner(corner: 20.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // CustomAlertViewController.swift // Mirchi // // Created by Raj Kadiyala on 24/01/2018. // Copyright © 2018 Raj Kadiyala. All rights reserved. // import UIKit class CustomAlertViewController: BaseAlertViewController{ @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var debugMessageLabel: UILabel! @IBOutlet weak var destructiveButton: ShapeButton! @IBOutlet weak var primaryButton: ShapeButton! @IBOutlet weak var cancelButton: ShapeButton! var destructiveAction:(()->Void)? var primaryAction:(()->Void)? var cancelAction:(()->Void)? var destructiveEnabled = false var primaryEnabled = false var cancelEnabled = false static func instantiate(title:String?, message:String?) -> CustomAlertViewController{ /*let alert = UIStoryboard(name: "CustomAlert", bundle: nil).instantiateViewController(withIdentifier: "AlertViewController") as! CustomAlertViewController alert.configureAlert(title: title, message: message, debugMessage: nil) return alert*/ return instantiate(title: title, message: message, debugMessage: nil) } static func instantiate(title:String?, message:String?, debugMessage:String?) -> CustomAlertViewController{ let alert = UIStoryboard(name: "CustomAlert", bundle: nil).instantiateViewController(withIdentifier: "AlertViewController") as! CustomAlertViewController alert.configureAlert(title: title, message: message, debugMessage: debugMessage) return alert } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureForDisplay() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func configureForDisplay(){ destructiveButton.isHidden = !destructiveEnabled primaryButton.isHidden = !primaryEnabled cancelButton.isHidden = !cancelEnabled if (titleLabel.text ?? "").isEmpty{ titleLabel.isHidden = true } if (messageLabel.text ?? "").isEmpty{ messageLabel.isHidden = true } } func configureAlert(title:String?, message:String?){ configureAlert(title: title, message: message, debugMessage: nil) } func configureAlert(title:String?, message:String?, debugMessage:String?){ loadViewIfNeeded() titleLabel.text = title messageLabel.text = message debugMessageLabel.isHidden = (debugMessage == nil) debugMessageLabel.text = debugMessage } func addAction(title:String, style:UIAlertAction.Style, handler:(()->Void)?){ loadViewIfNeeded() switch(style){ case .cancel: cancelButton.setTitle(title, for: .normal) cancelEnabled = true cancelAction = handler case .default: primaryButton.setTitle(title, for: .normal) primaryEnabled = true primaryAction = handler case .destructive: destructiveButton.setTitle(title, for: .normal) destructiveEnabled = true destructiveAction = handler } } @IBAction func onTapPrimary(_ sender: Any) { presentingViewController?.dismiss(animated: true, completion: primaryAction) } @IBAction func onTapDestructive(_ sender: Any) { presentingViewController?.dismiss(animated: true, completion: destructiveAction) } @IBAction func onTapCancel(_ sender: Any) { presentingViewController?.dismiss(animated: true, completion: cancelAction) } @IBAction func onTapBackground(_ sender: UIGestureRecognizer) { let view = sender.view let loc = sender.location(in: view) if view?.hitTest(loc, with: nil) == sender.view{ presentingViewController?.dismiss(animated: true, completion: cancelAction) } } }
// // QuestionProvider.swift // TrueFalseStarter // // Created by Beatty Jamieson on 8/19/18. // Copyright © 2018 Treehouse. All rights reserved. // import Foundation import GameKit struct QuestionsObject { var question: String = "" var answers: [String] = [""] var correctAnswer: Int = 0 } // Can you have 'correctAnswer' pull index from answer, rather than me retyping a string of what the answer should be? struct QuestionsBank { var questions: [QuestionsObject] = [ QuestionsObject(question: "This was the only US President to serve more than two consecutive terms.", answers: ["George Washington", "Franklin D. Roosevelt", "Woodrow Wilson", "Andrew Jackson"], correctAnswer: 2), QuestionsObject(question: "Which of the following countries has the most residents?", answers: ["Nigeria", "Russia", "Iran", "Vietnam"], correctAnswer: 2), QuestionsObject(question: "In what year was the United Nations Founded?", answers: ["1918", "1919", "1945", "1954"], correctAnswer: 3), QuestionsObject(question: "The Titanic departed from the United Kingdom, where was it supposed to arrive?", answers: ["Paris", "Washington D.C", "New York City", "Boston"], correctAnswer: 3), QuestionsObject(question: "Which nation produces the most oil?", answers: ["Iran", "Iraq", "Brazil", "Canada"], correctAnswer: 4), QuestionsObject(question: "Which country has most recently won consecutive World Cups in Soccer?", answers: ["Italy", "Brazil", "Argentina", "Spain"], correctAnswer: 2), QuestionsObject(question: "Which of the following rivers is longest?", answers: ["Yangtze", "Mississippi", "Congo", "Mekong"], correctAnswer: 2), QuestionsObject(question: "Which city is the oldest?", answers: ["Mexico City", "Cape Town", "San Juan", "Sydney"], correctAnswer: 1), QuestionsObject(question: "Which country was the first to allow women to vote in national elections?", answers: ["Poland", "United States", "Sweden", "Senegal"], correctAnswer: 1), QuestionsObject(question: "Which of these countries won the most medals in the 2012 Summer Games?", answers: ["France", "Germany", "Japan", "Great Britan"], correctAnswer: 4) ] /* func randomFact() -> String { let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: questions.count) return questions[randomNumber] } */ // create a random number in order to store a random fact index func randomNumber() -> Int { let randomFactIndex = GKRandomSource.sharedRandom().nextInt(upperBound: questions.count) - 1 // let randomFactIndex = randomNumber - 1 return randomFactIndex } // provides a random fact based off the random fact index generated func provideRF(from randomFactIndex: Int) -> String { let randomFact = questions[randomFactIndex] return randomFact.question } // provides answers for the random fact provided func provideRFAnswers(from randomFactIndex: Int) -> [String] { let randomFact = questions[randomFactIndex] return randomFact.answers } // provides correct answer index and pulls correct answer func provideCAOIndex(from randomFactIndex: Int) -> String { let randomFact = questions[randomFactIndex] let correctAnswerIndex = randomFact.correctAnswer let correctAnswerString = randomFact.answers[correctAnswerIndex] return correctAnswerString } // may need function to check and see if questions have been asked. could store array of ints so all we need to check is if the randomfactindex is already on the array }
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// Represents a single action which can be executed following the successful /// match of a lexer rule. Lexer actions are used for both embedded action syntax /// and ANTLR 4's new lexer command syntax. /// /// - Sam Harwell /// - 4.2 /// public class LexerAction: Hashable { /// /// Gets the serialization type of the lexer action. /// /// - returns: The serialization type of the lexer action. /// public func getActionType() -> LexerActionType { fatalError(#function + " must be overridden") } /// /// Gets whether the lexer action is position-dependent. Position-dependent /// actions may have different semantics depending on the _org.antlr.v4.runtime.CharStream_ /// index at the time the action is executed. /// /// Many lexer commands, including `type`, `skip`, and /// `more`, do not check the input index during their execution. /// Actions like this are position-independent, and may be stored more /// efficiently as part of the _org.antlr.v4.runtime.atn.LexerATNConfig#lexerActionExecutor_. /// /// - returns: `true` if the lexer action semantics can be affected by the /// position of the input _org.antlr.v4.runtime.CharStream_ at the time it is executed; /// otherwise, `false`. /// public func isPositionDependent() -> Bool { fatalError(#function + " must be overridden") } /// /// Execute the lexer action in the context of the specified _org.antlr.v4.runtime.Lexer_. /// /// For position-dependent actions, the input stream must already be /// positioned correctly prior to calling this method. /// /// - parameter lexer: The lexer instance. /// public func execute(_ lexer: Lexer) throws { fatalError(#function + " must be overridden") } public func hash(into hasher: inout Hasher) { fatalError(#function + " must be overridden") } } public func ==(lhs: LexerAction, rhs: LexerAction) -> Bool { if lhs === rhs { return true } if (lhs is LexerChannelAction) && (rhs is LexerChannelAction) { return (lhs as! LexerChannelAction) == (rhs as! LexerChannelAction) } else if (lhs is LexerCustomAction) && (rhs is LexerCustomAction) { return (lhs as! LexerCustomAction) == (rhs as! LexerCustomAction) } else if (lhs is LexerIndexedCustomAction) && (rhs is LexerIndexedCustomAction) { return (lhs as! LexerIndexedCustomAction) == (rhs as! LexerIndexedCustomAction) } else if (lhs is LexerModeAction) && (rhs is LexerModeAction) { return (lhs as! LexerModeAction) == (rhs as! LexerModeAction) } else if (lhs is LexerMoreAction) && (rhs is LexerMoreAction) { return (lhs as! LexerMoreAction) == (rhs as! LexerMoreAction) } else if (lhs is LexerPopModeAction) && (rhs is LexerPopModeAction) { return (lhs as! LexerPopModeAction) == (rhs as! LexerPopModeAction) } else if (lhs is LexerPushModeAction) && (rhs is LexerPushModeAction) { return (lhs as! LexerPushModeAction) == (rhs as! LexerPushModeAction) } else if (lhs is LexerSkipAction) && (rhs is LexerSkipAction) { return (lhs as! LexerSkipAction) == (rhs as! LexerSkipAction) } else if (lhs is LexerTypeAction) && (rhs is LexerTypeAction) { return (lhs as! LexerTypeAction) == (rhs as! LexerTypeAction) } return false }
// // LogModel.swift // DeliriumOver // // Created by mate.redecsi on 2020. 09. 08.. // Copyright © 2020. rmatesz. All rights reserved. // import Foundation struct LogModel: Codable { let timestamp: Double let category: String? let level: LogLevel let message: String? let error: String? }
// // RequestEditAttendance.swift // EditTimesheets // // Created by Nguyen Vinh on 1/29/19. // Copyright © 2019 Nguyen Vinh. All rights reserved. // import Foundation enum RequestAttendanceType: String { case none = "RC_NONE" case overtime = "RC_OVERTIME" case research = "RC_RESEARCH" case dayOff = "RC_DAYOFF" case watch = "RC_WATCH" case dayoffWorking = "RC_DAYOFF_WORKING" var content: String { switch self { case .none: return "" case .overtime: return "overtime" case .research: return "research" case .dayOff: return "dayyOff" case .watch: return "watch" case .dayoffWorking: return "day off" } } } enum RequestAttendanceStatus: String { case none = "RS_NONE" case new = "RS_NEW" case accepted = "RS_ACCEPTED" case rejected = "RS_REJECTED" var content: String { switch self { case .none: return "none" case .new: return "new" case .accepted: return "accepted" case .rejected: return "rejected" } } } class RequestEditAttendance { var id: String? var startTime: String? var endTime: String? var reasonId: String? var reasonCategories: RequestAttendanceType? var requestStatus: RequestAttendanceStatus? var comment: String? // TODO: Change to attachment var attachmentList: [String]? init(dict: NSDictionary) { self.id = dict["id"] as? String self.startTime = dict["startTime"] as? String self.endTime = dict["endTime"] as? String self.reasonId = dict["reasonId"] as? String if let reasonCategories = dict["reasonCategories"] as? String { self.reasonCategories = RequestAttendanceType(rawValue: reasonCategories) } if let requestStatus = dict["requestStatus"] as? String { self.requestStatus = RequestAttendanceStatus(rawValue: requestStatus) } self.comment = dict["comment"] as? String self.attachmentList = dict["attachmentList"] as? [String] } init() { } static func createDummyData() -> [RequestEditAttendance] { var results: [RequestEditAttendance] = [] let requestOne = RequestEditAttendance() requestOne.startTime = "07:00" requestOne.endTime = "08:00" requestOne.reasonCategories = RequestAttendanceType(rawValue: "RC_OVERTIME") requestOne.requestStatus = RequestAttendanceStatus(rawValue: "RS_NEW") results.append(requestOne) let requestTwo = RequestEditAttendance() requestTwo.startTime = "08:00" requestTwo.endTime = "09:00" requestTwo.reasonCategories = RequestAttendanceType(rawValue: "RC_OVERTIME") requestTwo.requestStatus = RequestAttendanceStatus(rawValue: "RS_NEW") results.append(requestTwo) let requestThree = RequestEditAttendance() requestThree.startTime = "09:00" requestThree.endTime = "10:00" requestThree.reasonCategories = RequestAttendanceType(rawValue: "RC_OVERTIME") requestThree.requestStatus = RequestAttendanceStatus(rawValue: "RS_NEW") results.append(requestThree) return results } }
// // DatabaseUtil.swift // DejaFashion // // Created by DanyChen on 21/12/15. // Copyright © 2015 Mozat. All rights reserved. // import UIKit import FMDB private var databaseMap = [String : Database]() private struct BaseColumns { static let id = "id" static let rawData = "raw_data" } func TableWith<T : NSObject>(_ tableName : String?, type : T.Type, primaryKey : String?, dbName : String = "Default") -> Table<T> { return Table<T>(name: (tableName == nil ? NSStringFromClass(T):tableName!), primaryKey : primaryKey, dbName : dbName) } func TableWith<T : NSObject>(_ tableName : String?, type : T.Type, primaryKey : String?, dbName : String = "Default", columns : [String]? = nil) -> Table<T> { return Table<T>(name: (tableName == nil ? NSStringFromClass(T):tableName!), primaryKey : primaryKey, dbName : dbName, columns : columns) } class Table<T : NSObject> { var name : String fileprivate var dbName : String fileprivate var primaryKey : String? fileprivate var database : Database? fileprivate var normalColumns : [String]? fileprivate var columns : [String]? fileprivate var queue : FMDatabaseQueue? //primaryKey should be one of the property name, columns should be the sublist of all properties fileprivate init(name : String, primaryKey : String?, dbName : String, columns : [String]? = nil) { self.name = name self.dbName = dbName self.primaryKey = primaryKey self.columns = columns if self.columns == nil { self.columns = getPropertyList() } setupDatabase() if database != nil { queue = FMDatabaseQueue(path: database!.fmDatabase.databasePath()) } } fileprivate func getPropertyList() -> [String] { let t = T() return Mirror(reflecting: t).children.filter { $0.label != nil }.map { $0.label! } } fileprivate func setupDatabase() -> Bool { if database == nil { if let db = databaseMap[dbName] { let setupSuccess = db.setupTable(name, primaryKey: primaryKey, columns: getNormalColumns()) if setupSuccess { database = db }else { return false } }else { let database = Database(name: dbName) let setupSuccess = database.setupTable(name, primaryKey: primaryKey, columns: getNormalColumns()) if setupSuccess { self.database = database databaseMap[dbName] = database }else { return false } } } return true } func getNormalColumns() -> [String] { if normalColumns == nil { normalColumns = self.columns!.filter( { $0 != primaryKey} ) } return normalColumns! } func parseResultSetToObj(_ resultSet : FMResultSet) -> T? { let obj = T() for key in columns! { let value = resultSet.object(forColumnName: key) if !(value is NSNull) { obj.setValue(value, forKey: key) } } return obj } func convertObjToValue(_ obj : T) -> [Any?] { return columns!.map { obj.value(forKey: $0)} } func save(_ obj : T) { if database == nil { return } queue?.inDatabase({(db : FMDatabase?) -> Void in self.database!.insert(self.name, columns: self.columns!, values: self.convertObjToValue(obj)) }) } func saveAll(_ objs : [T]){ if database == nil { return } queue?.inDatabase({(db : FMDatabase?) -> Void in self.database!.bulkInsert(self.name, columns: self.columns!, valuesList: objs.map({ (obj : T) -> [Any?] in self.convertObjToValue(obj) })) }) } func query(_ columnNames : [String], values : [AnyObject?], orderBy : String = "", handler : @escaping ([T]) -> Void) { if database == nil { handler([]) } queue?.inDatabase({(db : FMDatabase?) -> Void in var array = [T]() if let rs = self.database!.query(self.name, columns: columnNames, values: values, orderBy: orderBy) { while rs.next() { if let t = self.parseResultSetToObj(rs) { array.append(t) } } } handler(array) }) } func querySingle(_ columnNames : [String], values : [AnyObject?], handler : @escaping (T?) -> Void){ if database == nil { handler(nil)} queue?.inDatabase({(db : FMDatabase?) -> Void in if let rs = self.database!.query(self.name, columns: columnNames, values: values) { while rs.next() { handler(self.parseResultSetToObj(rs)) break } } }) } func queryAll(_ orderby : String = "", handler : @escaping ([T]) -> Void){ if database == nil { handler([]) } queue?.inDatabase({(db : FMDatabase?) -> Void in var array = [T]() if let rs = self.database!.query(self.name, columns: nil, values: nil, orderBy: orderby) { while rs.next() { if let t = self.parseResultSetToObj(rs) { array.append(t) } } } handler(array) }) } func delete(_ columnNames : [String], values : [AnyObject?]) { if database == nil { return } queue?.inDatabase({(db : FMDatabase?) -> Void in self.database!.delete(self.name, columns: columnNames, values: values) }) } func deleteAll() { if database == nil { return } queue?.inDatabase({(db : FMDatabase?) -> Void in self.database!.delete(self.name, columns: nil, values: nil) }) } func executeUpdates(_ sqls : [String]) { if database == nil { return } queue?.inDatabase({(db : FMDatabase?) -> Void in self.database!.executeUpdates(sqls) }) } } private class Database : NSObject { var fmDatabase : FMDatabase init(name : String) { let fileManager = FileManager.default let documents = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let fileURL = documents.appendingPathComponent(name + ".db") let urlPath = fileURL.path fmDatabase = FMDatabase(path: urlPath) if !fmDatabase.open() { print("Unable to open database") fmDatabase.close() do { try fileManager.removeItem(atPath: urlPath) print("delete database file success") }catch { print("Unable to delete database") } } } func setupTable(_ name : String, primaryKey : String?, columns : [String]) -> Bool { if fmDatabase.open() && columns.count > 0 { if let existingColumns = getExistingColumnsOfTable(name) { return updateTableStructure(name ,columns: columns, originColumnNames: existingColumns) }else { return createTable(name, primaryKey: primaryKey, columns: columns) } }else { return false } } func getExistingColumnsOfTable(_ tableName : String) -> Set<String>? { guard let rs = fmDatabase.executeQuery("PRAGMA table_info(\(tableName))", withArgumentsIn: nil) else {return nil} var result = Set<String>() while rs.next() { if let columnName = rs.string(forColumn: "name") { result.insert(columnName) } } return result.count > 0 ? result : nil } func updateTableStructure(_ tableName : String, columns : [String], originColumnNames : Set<String>) -> Bool{ var columnsNeedToAdd = [String]() var result = true for column in columns { if !originColumnNames.contains(column) { columnsNeedToAdd.append(column) } } if columnsNeedToAdd.count == 0 { return true } for column in columnsNeedToAdd { let sql = "alter table " + tableName + " add column " + column + " TEXT" result = fmDatabase.executeUpdate(sql, withArgumentsIn: nil) } return result } func createTable(_ tableName : String, primaryKey : String?, columns : [String]) -> Bool { var sql = "create table " + tableName + "(" if let primaryColumn = primaryKey { sql += primaryColumn + " TEXT primary key" }else { sql += "id INTEGER primary key autoincrement" } for column in columns { sql += ", " + column + " TEXT" } sql += ")" return fmDatabase.executeUpdate(sql, withArgumentsIn: nil) } func insert(_ tableName : String, columns : [String], values : [Any?]) -> Bool { return insertWithPreparedSql(prepareSqlForInsertColumns(tableName, columns: columns), valueCount: columns.count, values: values) } fileprivate func insertWithPreparedSql(_ sql : String, valueCount : Int, values : [Any?]) -> Bool { if valueCount == 0 || valueCount != values.count { return false } return fmDatabase.executeUpdate(sql, withArgumentsIn: convertNullObjects(valueCount, values: values)) } fileprivate func convertNullObjects(_ count : Int, values : [Any?]) -> [Any] { var objects = [Any]() for i in 0..<count { if values[i] == nil { objects.append(NSNull()) }else { objects.append(values[i]!) } } return objects } func prepareSqlForInsertColumns(_ tableName : String, columns : [String]) -> String { var combineColumnString = "" var questioMarks = "" for i in 0..<columns.count { if i == 0 { combineColumnString += columns[0] questioMarks += "?" }else { combineColumnString += "," + columns[i] questioMarks += ",?" } } return "insert or replace into " + tableName + "(" + combineColumnString + ") values(" + questioMarks + ")"; } func bulkInsert(_ tableName : String, columns : [String], valuesList : [[Any?]]) -> Bool { fmDatabase.beginTransaction() var success = true let sql = prepareSqlForInsertColumns(tableName, columns: columns) for values in valuesList { if !insertWithPreparedSql(sql, valueCount: columns.count, values: values) { success = false break } } if !success { fmDatabase.rollback() }else { fmDatabase.commit() } return success } func executeUpdates(_ sqls : [String]) -> Bool{ fmDatabase.beginTransaction() var success = true for sql in sqls { if !fmDatabase.executeUpdate(sql, withArgumentsIn: nil) { success = false break } } if !success { fmDatabase.rollback() }else { fmDatabase.commit() } return success } func query(_ tableName : String, columns : [String]?, values : [AnyObject?]?, orderBy : String = "") -> FMResultSet? { var orderBySuffix = "" if orderBy.characters.count > 0 { orderBySuffix = "order by " + orderBy } if columns == nil || columns?.count == 0 { return fmDatabase.executeQuery("select * from " + tableName + " " + orderBySuffix, withArgumentsIn: nil) }else if columns?.count == values?.count { var condition = " where " var i = 0 for column in columns! { if i == 0 { condition += column + "=?" }else { condition += "and " + column + "=? " } i += 1 } return fmDatabase.executeQuery("select * from " + tableName + condition + " " + orderBySuffix, withArgumentsIn: convertNullObjects(columns!.count, values: values!)) } return nil } func delete(_ tableName : String, columns : [String]?, values : [AnyObject?]?) -> Bool { if columns == nil || columns?.count == 0 { return fmDatabase.executeUpdate("delete from " + tableName, withArgumentsIn: nil) }else if columns?.count == values?.count { var condition = " where " var i = 0 for column in columns! { if i == 0 { condition += column + "=?" }else { condition += "and " + column + "=? " } i += 1 } return fmDatabase.executeUpdate("delete from " + tableName + condition, withArgumentsIn: convertNullObjects(columns!.count, values: values!)) } return false } }
// // TransactionInputModel.swift // MMWallet // // Created by Dmitry Muravev on 08.09.2018. // Copyright © 2018 micromoney. All rights reserved. // import Foundation import RealmSwift import ObjectMapper class TransactionInputModel: Object, Mappable { @objc dynamic var transactionId = 0 @objc dynamic var data = "" @objc dynamic var tokenAmount = 0.0 @objc dynamic var tokenRate: RateModel? @objc dynamic var token: TransactionDirectionModel? @objc dynamic var tokenTo: TransactionDirectionModel? override class func primaryKey() -> String? { return "transactionId" } required convenience init?(map: Map) { self.init() } func mapping(map: Map) { data <- map["data"] tokenAmount <- map["tokenAmount"] tokenRate <- map["tokenRate"] token <- map["token"] tokenTo <- map["tokenTo"] } }
// // UIColor+.swift // BaseProjectRxSwift // // Created by Kiều anh Đào on 5/29/20. // Copyright © 2020 Anhdk. All rights reserved. // import Foundation import UIKit extension UIColor { var image: UIImage? { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.setFillColor(self.cgColor) context.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } convenience init(rgbValue: UInt) { self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: 1.0) } convenience init(rgbValue: UInt, alpha: CGFloat) { self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: alpha) } func convertToRGB() -> UInt { let components = self.cgColor.components! let red: UInt = UInt(components[0] * 255) << 16 let green: UInt = UInt(components[1] * 255) << 8 let blue: UInt = UInt(components[2] * 255) return red | green | blue } }
// // RocketDetailsCell.swift // SpaceX_Fan // // Created by YeshwantSatya on 04/08/21. // import UIKit class RocketDetailsCell: UICollectionViewCell { @IBOutlet weak var imgVw: UIImageView! }
// // Outside+Animations.swift // Calm Cloud // // Created by Kate Duncan-Welke on 5/22/20. // Copyright © 2020 Kate Duncan-Welke. All rights reserved. // import Foundation import UIKit extension OutsideViewController { // MARK: Animation control functions func randomRepeatCount() -> Int { // random repeat for animations var randomRepeatCount = Int.random(in: 4...8) print("repeat \(randomRepeatCount) times") return randomRepeatCount } // MARK: Animations func floatUp() { print("float") cloudKitty.animationImages = AnimationManager.bouncingAnimation cloudKitty.startAnimating() let ceilingDestination = CGPoint(x: container.frame.width/2, y: container.frame.height/6) cloudKitty.outsideMove(to: ceilingDestination, duration: 3.0, options: UIView.AnimationOptions.curveEaseOut) } // left movement func floatLeft() { print("float left") cloudKitty.animationImages = AnimationManager.upsideDownLeft cloudKitty.startAnimating() let ceilingDestination = CGPoint(x: container.frame.width/8, y: container.frame.height/6) cloudKitty.outsideMove(to: ceilingDestination, duration: 4.0, options: UIView.AnimationOptions.curveEaseOut) } func moveLeftToBack() { print("left to back") cloudKitty.animationImages = AnimationManager.movingLeftAnimation cloudKitty.startAnimating() let centerDestination = CGPoint(x: container.frame.width/2.67, y: (container.frame.height/3)*1.52) cloudKitty.outsideMove(to: centerDestination, duration: 2, options: UIView.AnimationOptions.curveEaseOut) } func moveLeftToPlanter() { print("left to planter") cloudKitty.animationImages = AnimationManager.movingLeftAnimation cloudKitty.startAnimating() let planterDestination = CGPoint(x: container.frame.width/5.33, y: (container.frame.height/3)*2) cloudKitty.outsideMove(to: planterDestination, duration: 3.0, options: UIView.AnimationOptions.curveEaseOut) } func moveLeftToWidePot() { print("left to wide pot") cloudKitty.animationImages = AnimationManager.movingLeftAnimation cloudKitty.startAnimating() let potDestination = CGPoint(x: container.frame.width/5.33, y: (container.frame.height/3)*2.4) cloudKitty.outsideMove(to: potDestination, duration: 3.0, options: UIView.AnimationOptions.curveEaseOut) } func moveLeftToCenter() { print("left to center") cloudKitty.animationImages = AnimationManager.movingLeftAnimation cloudKitty.startAnimating() let centerDestination = CGPoint(x: container.frame.width/4, y: (container.frame.height/3)*2.35) cloudKitty.outsideMove(to: centerDestination, duration: 2, options: UIView.AnimationOptions.curveEaseOut) } // right movement func floatRight() { print("float right") cloudKitty.animationImages = AnimationManager.upsideDownRight cloudKitty.startAnimating() let ceilingDestination = CGPoint(x: container.frame.width/1.49, y: container.frame.height/6) cloudKitty.outsideMove(to: ceilingDestination, duration: 4.0, options: UIView.AnimationOptions.curveEaseOut) } func moveRightToBack() { print("right to back") cloudKitty.animationImages = AnimationManager.movingRightAnimation cloudKitty.startAnimating() let centerDestination = CGPoint(x: container.frame.width/2.67, y: (container.frame.height/3)*1.52) cloudKitty.outsideMove(to: centerDestination, duration: 2, options: UIView.AnimationOptions.curveEaseOut) } func moveRightToGate() { print("right to gate") cloudKitty.animationImages = AnimationManager.movingRightAnimation cloudKitty.startAnimating() let gateDestination = CGPoint(x: container.frame.width/1.57, y: (container.frame.height/3)*1.5) cloudKitty.outsideMove(to: gateDestination, duration: 2, options: UIView.AnimationOptions.curveEaseOut) } func moveRightToCenter() { print("right to center") cloudKitty.animationImages = AnimationManager.movingRightAnimation cloudKitty.startAnimating() let centerDestination = CGPoint(x: container.frame.width/4, y: (container.frame.height/3)*2.35) cloudKitty.outsideMove(to: centerDestination, duration: 2, options: UIView.AnimationOptions.curveEaseOut) } func moveRightToPath() { print("right to pots") cloudKitty.animationImages = AnimationManager.movingRightAnimation cloudKitty.startAnimating() let pathDestination = CGPoint(x: container.frame.width/1.57, y: (container.frame.height/3)*2.35) cloudKitty.outsideMove(to: pathDestination, duration: 3.0, options: UIView.AnimationOptions.curveEaseOut) } func moveRightToPots() { print("right to pots") cloudKitty.animationImages = AnimationManager.movingRightAnimation cloudKitty.startAnimating() let potsDestination = CGPoint(x: container.frame.width/1.12, y: (container.frame.height/3)*2.4) cloudKitty.outsideMove(to: potsDestination, duration: 3.0, options: UIView.AnimationOptions.curveEaseOut) } // sleep animations func sleep() { print("sleep") cloudKitty.animationImages = AnimationManager.sleepAnimation cloudKitty.animationDuration = 2.0 cloudKitty.animationRepeatCount = 0 cloudKitty.startAnimating() AnimationTimer.beginTimer(repeatCount: randomRepeatCount()) } func floatSleep() { print("float sleep") cloudKitty.animationImages = AnimationManager.sleepAnimation cloudKitty.animationDuration = 2.0 cloudKitty.animationRepeatCount = 0 cloudKitty.startAnimating() let destination = CGPoint(x: container.frame.width/2, y: container.frame.height/6) let floatDestination = CGPoint(x: destination.x, y: destination.y-20) cloudKitty.floatMoveOutside(to: floatDestination, returnTo: destination, duration: 2.0, options: [UIView.AnimationOptions.curveLinear]) } // place non-specific animations func bounce() { print("bounce") cloudKitty.animationImages = AnimationManager.bouncingAnimation cloudKitty.animationDuration = 2.0 cloudKitty.startAnimating() let destination: CGPoint switch AnimationManager.outsideLocation { case .ceiling: destination = CGPoint(x: container.frame.width/2, y: container.frame.height/6) case .back: destination = CGPoint(x: container.frame.width/2.67, y: (container.frame.height/3)*1.52) case .front: destination = CGPoint(x: container.frame.width/4, y: (container.frame.height/3)*2.35) case .gate: destination = CGPoint(x: container.frame.width/1.57, y: (container.frame.height/3)*1.5) case .path: destination = CGPoint(x: container.frame.width/1.12, y: (container.frame.height/3)*2.4) case .planter: destination = CGPoint(x: container.frame.width/5.33, y: (container.frame.height/3)*2) case .pot: destination = CGPoint(x: container.frame.width/5.33, y: (container.frame.height/3)*2.4) case .pots: destination = CGPoint(x: container.frame.width/1.57, y: (container.frame.height/3)*2.4) } let floatDestination = CGPoint(x: destination.x, y: destination.y-20) cloudKitty.floatMoveOutside(to: floatDestination, returnTo: destination, duration: 2.0, options: [UIView.AnimationOptions.curveLinear]) } func pause() { cloudKitty.image = AnimationManager.startImage AnimationTimer.beginTimer(repeatCount: randomRepeatCount()) } }
// // StatusNotification.swift // Apple Juice // https://github.com/raphaelhanneken/apple-juice // import Foundation /// Posts user notifications about the current charging status. struct StatusNotification { /// The current notification's key. private let notificationKey: NotificationKey /// The notification title. private var title: String? /// The notification text. private var text: String? // MARK: - Methods /// Initializes a new StatusNotification. /// /// - parameter key: The notification key which to display a user notification for. /// - returns: An optional StatusNotification; Return nil when the notificationKey /// is invalid or nil. init?(forState state: BatteryState?) { guard let state = state, let key = NotificationKey(rawValue: state.percentage), !(state == BatteryState.charging(percentage: 0)) else { // print("Not a valid percentage: \(state.percentage)") return nil } notificationKey = key setNotificationTitleAndText() } /// Checks if the user wants to get notified about the current charging status. func notifyUser() { // Assure the user didn't already receive a notification about the current percentage and that // the user is actually interested in the current charging status. if notificationKey != UserPreferences.lastNotified && UserPreferences.notifications.contains(notificationKey) { post() } } /// Delivers a NSUserNotification to the user. /// /// - returns: The NotificationKey for the delivered notification. private func post() { // Create a new user notification object. let notification = NSUserNotification() // Configure the new user notification. notification.title = title notification.informativeText = text // Deliver the notification. NSUserNotificationCenter.default.deliver(notification) // Update the last notified preference. UserPreferences.lastNotified = notificationKey } // MARK: - Private /// Sets the user notifications informative text and title. private mutating func setNotificationTitleAndText() { switch notificationKey { case .invalid: return case .hundredPercent: title = NSLocalizedString("Charged Notification Title", comment: "Translate the banner title for the charged / 100 % notification.") text = NSLocalizedString("Charged Notification Message", comment: "Translate the informative text for the charged / 100% notification.") default: title = String.localizedStringWithFormat(NSLocalizedString("Low Battery Notification Title", comment: "Notification title: Low Battery."), notificationKey.rawValue) text = NSLocalizedString("Low Battery Notification Message", comment: "Translate the informative text for the low battery notification.") } } }
// // FlashpileController.swift // flashcards // // Created by Bryan Workman on 7/19/20. // Copyright © 2020 Bryan Workman. All rights reserved. // import UIKit import CloudKit class FlashpileController { //MARK: - Properties static let shared = FlashpileController() var totalFlashpiles: [Flashpile] = [] var fauxFlashpiles: [Flashpile] = [] var fauxFlashpileIDs: [CKRecord.ID] = [] let privateDB = CKContainer.default().privateCloudDatabase //MARK: - CRUD //Create func createFlashpile(subject: String, completion: @escaping (Result<Flashpile, FlashError>) -> Void) { let newFlashpile = Flashpile(subject: subject) let newFlashRecord = CKRecord(flashpile: newFlashpile) privateDB.save(newFlashRecord) { (record, error) in if let error = error { print("There was an error saving the flashpile -- \(error) -- \(error.localizedDescription)") return completion(.failure(.ckError(error))) } guard let record = record, let savedFlashpile = Flashpile(ckRecord: record) else {return completion(.failure(.couldNotUnwrap))} self.totalFlashpiles.append(savedFlashpile) completion(.success(savedFlashpile)) } } //Read(Fetch) func fetchAllFlashpiles(completion: @escaping (Result<Bool, FlashError>) -> Void) { let predicate = NSPredicate(value: true) let query = CKQuery(recordType: FlashStrings.recordTypeKey, predicate: predicate) privateDB.perform(query, inZoneWith: nil) { (records, error) in if let error = error { print("There was an error fetching flashpile -- \(error) -- \(error.localizedDescription)") return completion(.failure(.ckError(error))) } guard let records = records else {return completion(.failure(.couldNotUnwrap))} let fetchedFlashpiles: [Flashpile] = records.compactMap { Flashpile(ckRecord: $0) } let sortedFlashpiles = fetchedFlashpiles.sorted(by: { $0.timestamp > $1.timestamp }) //self.totalFlashpiles.append(contentsOf: sortedFlashpiles) self.totalFlashpiles = sortedFlashpiles + self.fauxFlashpiles completion(.success(true)) } } //Update func updateFlashpile(flashpile: Flashpile, completion: @escaping (Result<Flashpile, FlashError>) -> Void) { let record = CKRecord(flashpile: flashpile) let operation = CKModifyRecordsOperation(recordsToSave: [record], recordIDsToDelete: nil) operation.savePolicy = .changedKeys operation.qualityOfService = .userInteractive operation.modifyRecordsCompletionBlock = {(records, _, error) in if let error = error { print("There was an error updating the flashpile -- \(error) -- \(error.localizedDescription)") return completion(.failure(.ckError(error))) } guard let record = records?.first, let updatedFlashpile = Flashpile(ckRecord: record) else {return completion(.failure(.couldNotUnwrap))} print("Successfully updated the flashpile") completion(.success(updatedFlashpile)) } privateDB.add(operation) } //Delete func deleteFlashpile(flashpile: Flashpile, completion: @escaping (Result<Bool, FlashError>) -> Void) { let operation = CKModifyRecordsOperation(recordsToSave: nil, recordIDsToDelete: [flashpile.recordID]) operation.qualityOfService = .userInteractive operation.modifyRecordsCompletionBlock = {(_, recordIDs, error) in if let error = error { print("There was an error deleting the flashpile -- \(error) -- \(error.localizedDescription)") return completion(.failure(.ckError(error))) } guard let recordIDs = recordIDs else { return completion(.failure(.couldNotUnwrap))} if recordIDs.count > 0 { print("Successfully deleted flashpile from CloudKit.") completion(.success(true)) } else { return completion(.failure(.unableToDeleteRecord)) } } privateDB.add(operation) } //MARK: - PreLoaded Piles func createMultPile(completion: @escaping (Result<Flashpile, Error>) -> Void) { let newFlashpile = Flashpile(subject: "Multiplication") for prompt in MultiplicationTables.prompts { guard let index = MultiplicationTables.prompts.firstIndex(of: prompt) else {return} let answer = MultiplicationTables.answers[index] let newFlashcard = Flashcard(frontString: prompt, backString: answer, frontIsPKImage: false, backIsPKImage: false, frontPhoto: nil, backPhoto: nil, pileReference: nil) newFlashpile.flashcards.append(newFlashcard) } self.totalFlashpiles.append(newFlashpile) self.fauxFlashpiles.append(newFlashpile) self.fauxFlashpileIDs.append(newFlashpile.recordID) } func createElementPile(completion: @escaping (Result<Flashpile, Error>) -> Void) { let newFlashpile = Flashpile(subject: "Periodic Table") for symbol in PeriodicTable.symbols { guard let index = PeriodicTable.symbols.firstIndex(of: symbol) else {return} let numAndName = PeriodicTable.numberAndName[index] let newFlashcard = Flashcard(frontString: symbol, backString: numAndName, frontIsPKImage: false, backIsPKImage: false, frontPhoto: nil, backPhoto: nil, pileReference: nil) newFlashpile.flashcards.append(newFlashcard) } self.totalFlashpiles.append(newFlashpile) self.fauxFlashpiles.append(newFlashpile) self.fauxFlashpileIDs.append(newFlashpile.recordID) } func createCapitalsPile(completion: @escaping (Result<Flashpile, Error>) -> Void) { let newFlashpile = Flashpile(subject: "States and Capitals") for state in StatesAndCapitals.states { guard let index = StatesAndCapitals.states.firstIndex(of: state) else {return} let capital = StatesAndCapitals.capitals[index] let newFlashcard = Flashcard(frontString: state, backString: capital, frontIsPKImage: false, backIsPKImage: false, frontPhoto: nil, backPhoto: nil, pileReference: nil) newFlashpile.flashcards.append(newFlashcard) } self.totalFlashpiles.append(newFlashpile) self.fauxFlashpiles.append(newFlashpile) self.fauxFlashpileIDs.append(newFlashpile.recordID) } } // End of class
// // WeatherData.swift // yumemiWeatherApp // // import Foundation import UIKit struct WeatherData: Codable { // let weather: String let weather: Weather let max_temp: Int let min_temp: Int let date: String func getImageColor() -> UIColor { switch self.weather { case .sunny: return UIColor.red case .cloudy: return UIColor.gray case .rainy: return UIColor.blue } } } enum Weather: String, Codable { case sunny case cloudy case rainy }
// // WebViewController.swift // Supreme Bot // // Created by Даниил Чемеркин on 15.04.17. // Copyright © 2017 Daniil Chemerkin. All rights reserved. // import UIKit import WebKit class WebViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView(frame: CGRect(x: 0, y: 20, width: view.bounds.width, height: CGFloat(643)).integral) print("view.h \(view.bounds.height)") webView.navigationDelegate = self view.addSubview(webView) let url = URL(string: "http://www.supremenewyork.com/mobile/")! webView.load(URLRequest(url: url)) webView.allowsBackForwardNavigationGestures = true bot(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func bot() -> Void { DispatchQueue.global(qos: .background).async { self.webView.evaluateJavaScript("document.getElementById('new-category').click()") var w = true while w { self.webView.evaluateJavaScript("document.getElementsByClassName('name')[12].click()") self.webView.evaluateJavaScript("document.location.href") { (result, error) in if error == nil { print(result!) let res = result! as? String if res != "http://www.supremenewyork.com/mobile/" && res != "http://www.supremenewyork.com/mobile/#categories/new" { w = false } } } } } } @IBAction func item(_ sender: UIButton) { bot() } @IBAction func color(_ sender: UIButton) { self.webView.evaluateJavaScript("var cA = document.getElementById('style-selector').getElementsByTagName('img');for (var i = 0; i < cA.length; i++) {cA[i].click();if (document.getElementById('style-name').innerText.toLowerCase() == 'black') {break;}}var b = document.getElementsByClassName('cart-button')[0];b.click();") } }
import Foundation import GPUImage class ChamferFilter : GPUImageFilter { var depth : Float = 2.0 var radius : Float = 20.0 var shape : Float = 0.0 override init() { super.init(fragmentShaderFromFile: "Chamfer") } convenience init(radius: Float, depth: Float, shape: Float) { self.init() self.depth = depth self.radius = radius self.shape = shape } override init!(fragmentShaderFromString fragmentShaderString: String!) { super.init(fragmentShaderFromString: fragmentShaderString) } override init!(vertexShaderFromString vertexShaderString: String!, fragmentShaderFromString fragmentShaderString: String!) { super.init(vertexShaderFromString: vertexShaderString, fragmentShaderFromString: fragmentShaderString) } override func setupFilterForSize(filterFrameSize: CGSize) { super.setupFilterForSize(filterFrameSize) runSynchronouslyOnVideoProcessingQueue { GPUImageContext.setActiveShaderProgram(self.valueForKey("filterProgram") as GLProgram!) self.setFloat(GLfloat(1.0/filterFrameSize.height), forUniformName: "texelHeight") self.setFloat(GLfloat(1.0/filterFrameSize.width), forUniformName: "texelWidth") self.setFloat(GLfloat(self.depth), forUniformName: "depth") self.setFloat(GLfloat(self.radius), forUniformName: "radius") self.setFloat(GLfloat(self.shape), forUniformName: "shape") } } }
// // NSObject.swift // womenfreebies // // Created by Alexey Sklyarenko on 27.02.16. // Copyright © 2016 com.pureconcepts. All rights reserved. // import UIKit public extension NSObject{ public class var classNameToString: String{ return NSStringFromClass(self).components(separatedBy: ".").last! } public var classNameToString: String{ return NSStringFromClass(type(of: self)).components(separatedBy: ".").last! } }
// // RecipeCoreDataProtocol.swift // FoodCourt // // Created by Максим Бойчук on 01.06.2020. // Copyright © 2020 Maksim Boichuk. All rights reserved. // import Foundation protocol RecipeCoreDataProtocol { func create(recipe: Recipe, completion: ((ErrorModel?) -> Void)?) func createMany(recipes: [Recipe], completion: ((ErrorModel?) -> Void)?) func get(id: String, complition: ((ErrorModel?) -> Void)?) func getAll(completion: (([Recipe]?, ErrorModel?) -> Void)?) func update(recipe: Recipe, completion: ((ErrorModel?) -> Void)?) func delete(id: String, completion: ((ErrorModel?) -> Void)?) }
import Foundation public struct CreateToDoRequestModel: JSONRepresentable { let title: String let descritpion: String }
// // ViewController.swift // CustomUIAlertWithHtml // // Created by ShaoJen Chen on 2020/8/21. // Copyright © 2020 ShaoJen Chen. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } @IBAction func WebViewAlertTap() { let ok_button = ButtonPayload(title: "OK", titleColor: .systemBlue, backgroundColor: .white, action: { (isChecked) in print("isChecked \(isChecked)") }) let alertPayload = AlertPayload(title: nil, titleColor: nil, backgroundColor: .white, buttonPayload: ok_button, completion: { print("completion") }) UIAlertController.showCustomAlertWebView(payload: alertPayload, parentViewController: self) } }
// // DeatailNewsViewController.swift // Scoops // // Created by Izabela on 06/03/16. // Copyright © 2016 Izabela. All rights reserved. // import UIKit class DeatailNewsViewController: UIViewController { var model : AnyObject? var client : MSClient? var nameFile : String = "" var id : String = "" var delegate : NewsTableDelegate? = nil @IBOutlet weak var titleField: UITextField! @IBOutlet weak var indicator: UIActivityIndicatorView! @IBOutlet weak var latitudeLabel: UILabel! @IBOutlet weak var longitudeLabel: UILabel! @IBOutlet weak var pushSwitch: UISwitch! @IBOutlet weak var authorField: UITextField! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var newsField: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func saveChanges(sender: AnyObject) { if isUserLoged(){ if let usrlogin = loadUserAuth(){ client!.currentUser = MSUser(userId: usrlogin.usr) client!.currentUser.mobileServiceAuthenticationToken = usrlogin.tok let tabla = client?.tableWithName("news") var publishValue = false if pushSwitch.on{ publishValue = true } tabla?.update(["id": self.id ,"title": titleField.text!, "news": newsField.text! , "photo": nameFile, "longitud": latitudeLabel.text!, "latitude" : latitudeLabel.text!, "published" : publishValue], completion: { (inserted, error:NSError?) -> Void in //tablaVideos?.insert(["title": titleText.text!], completion: { (inserted, error:NSError? ) -> Void in if error != nil{ print ("Error: \(error?.userInfo["NSLocalizedDescription"]!)") let alert = UIAlertView(title: "Error", message: "\(error?.userInfo["NSLocalizedDescription"]!)", delegate: nil, cancelButtonTitle: "Ok") alert.show() } else { print( "Register saved in the DB") self.delegate?.addedNewValues() } }) } }else { //user not logged: client!.loginWithProvider("facebook", controller: self, animated: true, completion: { (user: MSUser?, error: NSError?) -> Void in if (error != nil){ print("There is a probelm with user login") } else{ saveAuthInfo(user) } }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewDidAppear(animated) titleField.text = model!["title"] as? String; authorField.text = model!["userName"] as? String; self.id = (model!["id"] as? String)!; self.indicator.hidden = true takeRestData() } func takeRestData(){ let table = client?.tableWithName("news") //let usrlogin = loadUserAuth() let stringQuery = model!["id"]! let predicate = NSPredicate(format: "id = '\(stringQuery!)'", []) let query = MSQuery(table: table, predicate:predicate) query.readWithCompletion{(result:MSQueryResult?, error:NSError?) -> Void in if error == nil { self.newsField.text=result?.items[0]["news"] as? String; self.latitudeLabel.text = result?.items[0]["latitude"] as? String; self.longitudeLabel.text = result?.items[0]["longitud"] as? String; self.pushSwitch.setOn((result?.items[0]["published"] as? Bool)!, animated: false); //self.model = result?.items let blobName = result?.items[0]["photo"] as? String; if (blobName != ""){ self.indicator.hidden=false self.indicator.startAnimating() var image : UIImage? //check if saved in dhe caache: let cachePath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as String self.nameFile = blobName! let strFilePath = cachePath.stringByAppendingString("/\(self.nameFile)") let manager = NSFileManager.defaultManager() if (manager.fileExistsAtPath(strFilePath)) { //get it from cache let data = NSData(contentsOfFile: strFilePath) image = UIImage(data : data!) self.imageView.image = image self.indicator.stopAnimating() self.indicator.hidden=true }else{ //Download and save it: let containerName = "photos" self.client?.invokeAPI("urlsastoblobandcontainer", body: nil, HTTPMethod: "GET", parameters: ["photoName" : blobName!, "ContainerName" : containerName], headers: nil, completion: { (result : AnyObject?, response : NSHTTPURLResponse?, error: NSError?) -> Void in if error == nil{ let sasURL = result!["sasURL"] as? String var endPoint = "https://scoopsizabela.blob.core.windows.net" endPoint += sasURL! let url = NSURL(string: endPoint)! let download = dispatch_queue_create(blobName!, nil); dispatch_async(download){ let data = NSData(contentsOfURL:url) //var image : UIImage? if data != nil{ dispatch_async(dispatch_get_main_queue(), { () -> Void in image = UIImage(data : data!) self.imageView.image = image self.indicator.stopAnimating() self.indicator.hidden=true //save it: let image = UIImage(data: data!) UIImageJPEGRepresentation(image!, 100)!.writeToFile(strFilePath, atomically: true) }) } } } }) } } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // RectangleLayer.swift // Swift_Animation // // Created by coder on 16/2/16. // Copyright © 2016年 coder. All rights reserved. // import UIKit class RectangleLayer: CAShapeLayer { var parentBounds:CGRect = CGRectZero let rectLineWidth:CGFloat = 7 let startColor:CGColorRef = UIColor.redColor().CGColor let endColor:CGColorRef = UIColor(red: 60.0/255.0, green: 115.0/255.0, blue: 146.0/255.0, alpha: 1.0).CGColor let animationDuration:NSTimeInterval = 1.0 var redCompleteHandler:((flag:Bool) -> Void)? var blueCompleteHandler:((flag:Bool) -> Void)? init(bounds:CGRect) { super.init(); self.lineWidth = rectLineWidth self.parentBounds = bounds; self.strokeStart = 0.0 self.strokeEnd = 1.0 self.fillColor = UIColor.whiteColor().CGColor self.strokeColor = self.startColor self.path = rectangleLagerPath.CGPath } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var rectangleLagerPath: UIBezierPath { let bezierPath = UIBezierPath(); bezierPath.moveToPoint(CGPoint(x: 0, y: self.parentBounds.height)) bezierPath.addLineToPoint(CGPoint(x: 0, y: 0)) bezierPath.moveToPoint(CGPoint(x: 0, y: 0)) bezierPath.addLineToPoint(CGPoint(x: self.parentBounds.width, y: 0)) bezierPath.moveToPoint(CGPoint(x: self.parentBounds.width, y: 0)) bezierPath.addLineToPoint(CGPoint(x: self.parentBounds.width, y: self.parentBounds.height)) bezierPath.moveToPoint(CGPoint(x: self.parentBounds.width, y: self.parentBounds.height)) bezierPath.addLineToPoint(CGPoint(x: -self.rectLineWidth / 2, y: self.parentBounds.height)) return bezierPath; } func drawRedLine(complete:(flag:Bool) -> Void) { let animation:CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = CGFloat(0.0) animation.toValue = CGFloat(1.0) animation.duration = animationDuration animation.cumulative = true animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false addAnimation(animation, forKey: nil) self.redCompleteHandler = complete; NSTimer.scheduledTimerWithTimeInterval(animationDuration / 4, target: self, selector: "animationDidStart", userInfo: nil, repeats: false) } func drawBlueLine(complete:(flag:Bool) -> Void) { let strokeColor:CABasicAnimation = CABasicAnimation(keyPath: "strokeColor") strokeColor.fromValue = self.startColor strokeColor.toValue = self.endColor let strokeEnd:CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeEnd.fromValue = CGFloat(0.0) strokeEnd.toValue = CGFloat(1.0) let animationGroup = CAAnimationGroup() animationGroup.animations = [strokeColor,strokeEnd] animationGroup.beginTime = CACurrentMediaTime() animationGroup.fillMode = kCAFillModeForwards animationGroup.duration = animationDuration animationGroup.removedOnCompletion = false animationGroup.delegate = self addAnimation(animationGroup, forKey: nil) self.blueCompleteHandler = complete } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if self.blueCompleteHandler != nil { self.blueCompleteHandler!(flag: true) } } func animationDidStart() { if self.redCompleteHandler != nil { self.redCompleteHandler!(flag: true) } } }
// // FeedView.swift // AC-iOS-Final // // Created by C4Q on 2/26/18. // Copyright © 2018 C4Q . All rights reserved. // import UIKit class FeedView: UIView { lazy var feedTableView: UITableView = { let table = UITableView() table.register(FeedTableViewCell.self, forCellReuseIdentifier: "PostCell") return table }() override init(frame: CGRect) { super.init(frame: frame) setupInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupInit() { addSubview(feedTableView) feedTableView.translatesAutoresizingMaskIntoConstraints = false feedTableView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true feedTableView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true feedTableView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true feedTableView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true } }
// // FirebaseInteractor.swift // OptimoveSDK // // Created by Mobile Developer Optimove on 26/09/2017. // Copyright © 2017 Optimove. All rights reserved. // import Foundation import Firebase protocol MessageHandleProtocol { func handleRegistrationTokenRefresh(token:String) } class FirebaseInteractor:NSObject { //MARK: - Properties let delegate: MessageHandleProtocol! //MARK: Constructors init(messageHandler:MessageHandleProtocol) { delegate = messageHandler } //MARK: - static methods func setupFirebase(from firebaMetaData: FirebaseMetaData, clientFirebaseMetaData:FirebaseMetaData, clientHasFirebase:Bool) { DispatchQueue.main.async { guard let secondaryOptions = self.generateOptimoveSecondaryOptions(from: firebaMetaData), let clientServiceOptions = self.generateOptimoveSecondaryOptions(from: clientFirebaseMetaData) else {return} if !clientHasFirebase { FirebaseApp.configure(options: secondaryOptions) } else { FirebaseApp.configure(name: "appController", options: secondaryOptions) } FirebaseApp.configure(name: "sdkController", options:clientServiceOptions) } } private func generateOptimoveSecondaryOptions(from firebaseKeys: FirebaseMetaData) -> FirebaseOptions? { guard let webApiKey = firebaseKeys.webApiKey, let appId = firebaseKeys.appId, let dbUrl = firebaseKeys.dbUrl, let senderId = firebaseKeys.senderId, let storageBucket = firebaseKeys.storageBucket, let projectId = firebaseKeys.projectId else { return nil } let appControllerOptions = FirebaseOptions.init(googleAppID: appId, gcmSenderID: senderId) appControllerOptions.bundleID = Bundle.main.bundleIdentifier! appControllerOptions.apiKey = webApiKey appControllerOptions.databaseURL = dbUrl appControllerOptions.storageBucket = storageBucket appControllerOptions.deepLinkURLScheme = appControllerOptions.bundleID appControllerOptions.projectID = projectId appControllerOptions.clientID = "gibrish-firebase" return appControllerOptions } func getDynamicLinks(from shortUrl:URL?, completionHandler:@escaping (DynamicLinkComponents?) -> Void) { guard let dynamicLinks = DynamicLinks.dynamicLinks(), let shortUrl = shortUrl else { completionHandler(nil) return } dynamicLinks.handleUniversalLink(shortUrl) { (deepLink, error) in guard let screenName = deepLink?.url?.lastPathComponent, let query = deepLink?.url?.queryParameters else { completionHandler(nil) return } completionHandler(DynamicLinkComponents(screenName: screenName, query: query)) } } } extension FirebaseInteractor:MessagingDelegate { func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) { delegate.handleRegistrationTokenRefresh(token:fcmToken) } fileprivate func getMongoTypeBundleId() -> String { return Bundle.main.bundleIdentifier?.setAsMongoKey() ?? "" } fileprivate func subscribeToTopics() { Messaging.messaging().subscribe(toTopic: "optipush_general") Messaging.messaging().subscribe(toTopic: "ios") Messaging.messaging().subscribe(toTopic: getMongoTypeBundleId() ) } func subscribeTestMode() { if let bundleID = Bundle.main.bundleIdentifier { Messaging.messaging().subscribe(toTopic: "test_" + bundleID) } } func unsubscribeTestMode() { if let bundleID = Bundle.main.bundleIdentifier { Messaging.messaging().unsubscribe(fromTopic: "test_" + bundleID) } } func handleRegistration(token:Data) { Messaging.messaging().delegate = self Messaging.messaging().apnsToken = token subscribeToTopics() } }
import XCTest @testable import CircuitKit final class CircuitTests: XCTestCase { func testCircuit1() { let a = Node("A") let b = Node("B") let g = Node.ground // R1 and R2 _ = Resistor(resistance: 10.ohms, between: a, and: b) _ = Resistor(resistance: 10.ohms, between: b, and: g) let e0 = IdealVoltageGenerator(voltage: Voltage(peak: 50.volts, phase: 0.degrees, omega: 0.hertz), between: a, and: g) let circuit = Circuit(autoDiscoverFromNode: g) circuit.solve() XCTAssertEqual(g.voltage?.value, .zero) XCTAssertEqual(b.voltage?.value, e0.fixedVoltage.value/2) } func testCircuit2() { let a = Node("A") let b = Node("B") let g = Node.ground let r1 = Resistor(resistance: 1000.ohms, between: a, and: g) let c = Capacitor(capacitance: 1e-6.farads, between: b, and: a) let e = IdealVoltageGenerator(voltage: Voltage(peak: 5.volts, phase: 0.degrees, omega: 1000.hertz), between: b, and: g) let circuit = Circuit(autoDiscoverFromNode: g) XCTAssertEqual(r1.voltage?.value, e.fixedVoltage.value / (c.impedance(1000.hertz).value + r1.impedance(1000.hertz).value) * r1.impedance(1000.hertz).value) } func testCircuit3() { let a = Node("A") let g = Node.ground let c1 = Capacitor(capacitance: 0.1e-6.farads, between: a) let e = IdealVoltageGenerator(voltage: Voltage(rms: 12.volts, phase: 0.degrees, omega: 15000.hertz), between: c1.nodeB, and: g) let c2 = Capacitor(capacitance: 0.05e-6.farads, between: a, and: g) let c3 = Capacitor(capacitance: 0.22e-6.farads, between: a, and: g) // R1 and R2 let r1 = Resistor(resistance: 330.ohms, between: a) _ = Resistor(resistance: 180.ohms, between: r1.nodeB, and: g) let circuit = Circuit(autoDiscoverFromNode: g) // Tolerance is 6.2 due to potential rounding in exercises XCTAssertEqual((e.current?.rms.converted(to: .milliamperes).value)!, 82.7, accuracy: 0.2) XCTAssertEqual((c2.current?.rms.converted(to: .milliamperes).value)!, 15.3, accuracy: 0.2) XCTAssertEqual((c3.current?.rms.converted(to: .milliamperes).value)!, 67.3, accuracy: 0.2) XCTAssertEqual((r1.current?.rms.converted(to: .milliamperes).value)!, 6.37, accuracy: 0.2) } static var allTests = [ ("Circuit test 1", testCircuit1), ("Circuit test 2", testCircuit2), ("Circuit test 3", testCircuit3) ] }
// // workOutController.swift // fitBit // // Created by KAIZER WEB DESIGN on 05/11/2019. // Copyright © 2019 kaizer. All rights reserved. // import UIKit import CoreLocation import SQLite3 import HealthKit class workOutController: UIViewController, CLLocationManagerDelegate { let locationManager:CLLocationManager = CLLocationManager() var time: Int = 0 var timer = Timer() var healthStore = HKHealthStore() /******UI ELEMENTS*********/ @IBOutlet weak var metersLab: UITextView! @IBOutlet weak var saveBut: UIButton! @IBOutlet weak var startBut: UIButton! @IBOutlet weak var resumeBut: UIButton! @IBOutlet weak var stopBut: UIButton! @IBOutlet weak var hoursLab: UITextView! @IBOutlet weak var minutesLab: UITextView! @IBOutlet weak var secondsLab: UITextView! @IBOutlet weak var cancelBut: UIButton! var db : OpaquePointer? var allLocations: Array<CLLocation> = Array() var test = 0 override func viewDidLoad() { super.viewDidLoad() saveBut.isHidden=true resumeBut.isHidden=true locationManager.delegate = self locationManager.requestWhenInUseAuthorization() allLocations.removeAll() allLocations.removeAll() allLocations.removeAll() allLocations.removeAll() authorizeHealthKit() loadDB() //var stmt2 : OpaquePointer? // let select = "SELECT * FROM fitBit" // let truncate = "DELETE FROM fitBit" // let drop2 = "ALTER TABLE fitBit ADD COLUMN sourLat DOUBLE NOT NULL, ADD COLUMN sourLong DOUBLE NOT NULL, ADD COLUMN destLat DOUBLE NOT NULL, ADD COLUMN destLong DOUBLE NOT NULL" //let drop = "DROP TABLE IF EXISTS fitBit" /*if sqlite3_prepare(db, truncate, -1, &stmt2, nil) == SQLITE_OK { sqlite3_step(stmt2) /*while sqlite3_step(stmt2) == SQLITE_ROW { let date = UnsafePointer<UInt8>(sqlite3_column_text(stmt2, 2))! let start = String(cString: date) let duration = sqlite3_column_int(stmt2, 3) let distance = sqlite3_column_double(stmt2, 4) let sour = sqlite3_column_double(stmt2, 6) print("Date: "+start+" - "+"Duration: "+String(duration)+" - "+"Distance: "+String(distance)+" - "+"sourLat: "+String(sour)) }*/ }else{ print(String.init(cString: sqlite3_errmsg(db))) }*/ } func saveWorkoutToHealthKit(_ workout: workoutSession) { let distanceQuantity = HKQuantity(unit: HKUnit.meter(), doubleValue: workout.distance) let df = DateFormatter() df.dateFormat = "yyyy-MM-dd HH:mm:ss" let startTime = df.date(from: workout.startTime) let endTime = df.date(from: workout.endTime) let hours2 : Double = Double(workout.duration)/3600.0 let caloriesperHour : Double = 480 let totalCaloriesBurnt : Double = hours2*caloriesperHour print("Calories bruler"+String(totalCaloriesBurnt)) let unit = HKUnit.kilocalorie() let quantity = HKQuantity(unit: unit, doubleValue: totalCaloriesBurnt) let workoutObject = HKWorkout(activityType: HKWorkoutActivityType.running, start: startTime!, end: endTime!, duration: TimeInterval(workout.duration), totalEnergyBurned: quantity, totalDistance: distanceQuantity, metadata: nil) healthStore.save(workoutObject, withCompletion: { (completed, error) in if let error = error { print("Error creating workout") } else { self.addSamples(hkWorkout: workoutObject, workoutData: workout) } }) } func addSamples(hkWorkout: HKWorkout, workoutData: workoutSession) { var samples = [HKSample]() guard let runningDistanceType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning) else { return } let distanceUnit = HKUnit.meter() let distanceQuantity = HKQuantity(unit: distanceUnit, doubleValue: workoutData.distance) let df = DateFormatter() df.dateFormat = "yyyy-MM-dd HH:mm:ss" let startTime = df.date(from: workoutData.startTime) let endTime = df.date(from: workoutData.endTime) let distanceSample = HKQuantitySample(type: runningDistanceType, quantity: distanceQuantity, start: startTime!, end: endTime!) samples.append(distanceSample) healthStore.add(samples, to: hkWorkout, completion: { (completed, error) in if let error = error { print("Error adding workout samples") } else { print("Workout samples added successfully") } }) } func loadDB(){ let fileUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("fitbit.sqlite") if sqlite3_open(fileUrl.path, &db) != SQLITE_OK{ print("Error opening file") } let createTableQuery = "CREATE TABLE IF NOT EXISTS fitBit ( id INTEGER PRIMARY KEY AUTOINCREMENT , startTime DATETIME NOT NULL , EndTime DATETIME NOT NULL , duration INTEGER NOT NULL , distance DOUBLE NOT NULL, sourLat DOUBLE NOT NULL, sourLong DOUBLE NOT NULL, destLat DOUBLE NOT NULL, destLong DOUBLE NOT NULL)" let createTrack = "CREATE TABLE IF NOT EXISTS tracks (session_id INTEGER, latitude DOUBLE NOT NULL, longitude DOUBLE NOT NULL)" if sqlite3_exec(db, createTableQuery, nil, nil, nil) != SQLITE_OK{ print("Error initialising the file") }else{ print("Sessions File succesfully initialised !") } if sqlite3_exec(db, createTrack, nil, nil, nil) != SQLITE_OK{ print("Error initialising the file") }else{ print("Track File succesfully initialised !") } } @IBAction func chrono_start(_ sender: Any) { stopBut.isHidden = false; /*saveBut.isHidden=false resumeBut.isHidden=false*/ startBut.isHidden=true timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ended), userInfo: nil, repeats: true) locationManager.startUpdatingLocation() locationManager.distanceFilter = 10 } @IBAction func chrono_stop(_ sender: Any) { saveBut.isHidden=false resumeBut.isHidden=false cancelBut.isHidden=false startBut.isHidden=true stopBut.isHidden=true timer.invalidate(); locationManager.stopUpdatingLocation() } @IBAction func resume_chrono(_ sender: Any) { resumeBut.isHidden = true saveBut.isHidden = true cancelBut.isHidden = true stopBut.isHidden = false timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ended), userInfo: nil, repeats: true) locationManager.startUpdatingLocation() } func saveTracks(lastInserted : Int32 ){ var stmt : OpaquePointer? let insert = "INSERT INTO tracks (session_id, latitude, longitude) VALUES (?, ?, ?)" for location in allLocations{ if sqlite3_prepare(db, insert, -1, &stmt, nil) != SQLITE_OK { print("ERROR BINDING QUERY") } if sqlite3_bind_int(stmt, 1, lastInserted) != SQLITE_OK{ print("Error binding track") } if sqlite3_bind_double(stmt, 2, location.coordinate.latitude) != SQLITE_OK{ print("Error binding track") } if sqlite3_bind_double(stmt, 3, location.coordinate.longitude) != SQLITE_OK{ print("Error binding track") } if sqlite3_step(stmt) == SQLITE_DONE{ //print("Track saved sucessfully ! !") }else{ print(String.init(cString: sqlite3_errmsg(db))) } } } private func authorizeHealthKit() { HealthKitSetupAssistant.authorizeHealthKit { (authorized, error) in guard authorized else { let baseMessage = "HealthKit Authorization Failed" if let error = error { print("\(baseMessage). Reason: \(error.localizedDescription)") } else { print(baseMessage) } return } print("HealthKit Successfully Authorized.") } } @IBAction func cancel_chrono(_ sender: Any) { saveBut.isHidden = true resumeBut.isHidden = true cancelBut.isHidden = true cancelBut.isHidden=true startBut.isHidden=false time=0; updateUI(); metersLab.text = "0.00 metres" allLocations.removeAll() test = 0 } @IBAction func save_chrono(_ sender: Any) { saveBut.isHidden = true resumeBut.isHidden = true cancelBut.isHidden = true startBut.isHidden=false var stmt : OpaquePointer? let insert = "INSERT INTO fitBit (startTime, EndTime,duration,distance,sourLat,sourLong,destLat,destLong) VALUES (?, ?, ?, ?, ?, ?, ?, ?)" if sqlite3_prepare(db, insert, -1, &stmt, nil) != SQLITE_OK { print("ERROR BINDING QUERY") } let first : CLLocation = allLocations.first! let last : CLLocation = allLocations.last! let df = DateFormatter() df.dateFormat = "yyyy-MM-dd HH:mm:ss" let date = df.string(from: first.timestamp) if sqlite3_bind_text(stmt, 1, date, -1, nil) != SQLITE_OK{ print("Binding value exception") } let df2 = DateFormatter() df2.dateFormat = "yyyy-MM-dd HH:mm:ss" let date2 = df2.string(from: last.timestamp) if sqlite3_bind_text(stmt, 2, date2, -1, nil) != SQLITE_OK{ print("Binding value exception") } if sqlite3_bind_int(stmt, 3, Int32(time)) != SQLITE_OK{ print("Error binding duration") } var distance: CLLocationDistance = 0.0 distance = first.distance(from: last) if sqlite3_bind_double(stmt, 4, distance) != SQLITE_OK{ print("Error binding duration") } if sqlite3_bind_double(stmt, 5, first.coordinate.latitude) != SQLITE_OK{ print("Error binding duration") } if sqlite3_bind_double(stmt, 6, first.coordinate.longitude) != SQLITE_OK{ print("Error binding duration") } if sqlite3_bind_double(stmt, 7, last.coordinate.latitude) != SQLITE_OK{ print("Error binding duration") } if sqlite3_bind_double(stmt, 8, last.coordinate.longitude) != SQLITE_OK{ print("Error binding duration") } if sqlite3_step(stmt) == SQLITE_DONE{ print("Workout succesfully saved !") }else{ print("Error writing data to disk !") } let lastId = "SELECT last_insert_rowid()" if sqlite3_prepare(db, lastId, -1, &stmt, nil) != SQLITE_OK { print("ERROR BINDING QUERY") } var lastInsert : Int32 while sqlite3_step(stmt) == SQLITE_ROW { lastInsert = sqlite3_column_int(stmt, 0) print(lastInsert) saveTracks(lastInserted: lastInsert) } let workout = workoutSession(id: 12,startTime: date,endTime: date2,duration: time,distance: distance,sourLat: first.coordinate.latitude,sourLong: first.coordinate.longitude,destLat: last.coordinate.latitude,destLong: last.coordinate.longitude) saveWorkoutToHealthKit(workout) time=0; updateUI(); metersLab.text = "0.00 metres" displayTrack() allLocations.removeAll() test = 0 self.tabBarController?.selectedIndex = 3 } func displayTrack(){ var tracks : [Track] = [] let first = allLocations.first let last = allLocations.last for location in allLocations{ let track = Track(latitude: location.coordinate.latitude,longitude: location.coordinate.longitude) tracks.append(track) } let vc = self.tabBarController?.viewControllers![3] as! mapViewController vc.sourLat = (first?.coordinate.latitude)! vc.sourLong = (first?.coordinate.longitude)! vc.destLat = (last?.coordinate.latitude)! vc.destLong = (last?.coordinate.longitude)! vc.tracks = tracks } @objc private func ended(){ time += 1; updateUI(); } private func updateUI(){ var hours: Int var min: Int var sec: Int hours = time / (60*60) min = (time/60)%60 sec = time % 60 hoursLab.text = String(hours) if(min < 10){ minutesLab.text = "0"+String(min) }else{ minutesLab.text = String(min) } if(sec < 10){ secondsLab.text = "0"+String(sec) }else{ secondsLab.text = String(sec) } if(test > 1){ if(allLocations.first != nil && allLocations != nil){ let first : CLLocation = allLocations.first! let last : CLLocation = allLocations.last! var distance: CLLocationDistance = 0.0 distance = first.distance(from: last) metersLab.text = String(format: "%.2f",distance)+" metres" } } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //print(locations[0]) if(test > 1){ allLocations.append(locations[0]) }else{ // allLocations.removeAll() test+=1 } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // BreedImagesAPI.swift // Breeds // // Created by erick.lozano.borges on 06/08/20. // Copyright © 2020 borges.erick. All rights reserved. // import Foundation class BreedImagesAPI { private let manager: RequestManager init(manager: RequestManager = RequestManagerFactory.create()) { self.manager = manager } func fetchImages(limit: Int, page: Int, completion: @escaping(Result<[BreedImage], Error>) -> Void) { let url = TheDogAPISources.baseUrl.appendingPathComponent("/v1/images/search") let headers = TheDogAPISources.authHeader let parameters: [String: Any] = [ "order": "Asc", "limit": limit, "page": page ] manager.request(url: url, method: .get, parameters: parameters, headers: headers, completion: completion) } func fetchImage(by id: String, completion: @escaping(Result<BreedImage, Error>) -> Void) { let url = TheDogAPISources.baseUrl.appendingPathComponent("/v1/images/\(id)") let headers = TheDogAPISources.authHeader manager.request(url: url, method: .get, parameters: [:], headers: headers, completion: completion) } }
// // NotificationItem.swift // BumbleBeezy // // Created by Аня on 18.11.19. // Copyright © 2019 An. All rights reserved. // import Foundation struct NotificationItem { let type: NotificationType let title: String let message: String let date: Date init(type: NotificationType, title: String, message: String, date: Date) { self.type = type self.title = title self.message = message self.date = date } } extension NotificationItem { static var stubItems: [NotificationItem] { return [ NotificationItem(type: .alert, title: "Hey", message: "Don't forget to check your duties", date: Date()), NotificationItem(type: .notify, title: "Car service", message: "Check oil level", date: Date().addingTimeInterval(15)), NotificationItem(type: .calendar, title: "Ann's birthday is coming", message: "Next week Ann's birthday party! Don't forget to bring your present. 22 December 16:00", date: Date().addingTimeInterval(24)) ] } }
// // singleton.swift // transinfoFinal // // Created by Pedro Santiago on 4/30/17. // Copyright © 2017 Universidad de puerto rico-Mayaguez. All rights reserved. // import Foundation extension ForeignKeyVars{ }
// // StarWarsCharacter.swift // StarWarsSwift // // Created by Jose Manuel Franco on 16/5/15. // Copyright (c) 2015 Jose Manuel Franco. All rights reserved. // import UIKit class StarWarsCharacter: NSObject { var name:String var alias:String var wikiURL:NSURL var photo:UIImage var sound:NSURL? init(name: String,alias: String,wikiURL:NSURL,photo:UIImage,sound:NSURL) { self.name=name self.alias=alias self.wikiURL=wikiURL; //self.soundData=soundData self.photo=photo self.sound = sound } }
// Copyright (c) 2020 Razeware LLC // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // Notwithstanding the foregoing, you may not use, copy, modify, // merge, publish, distribute, sublicense, create a derivative work, // and/or sell copies of the Software in any work that is designed, // intended, or marketed for pedagogical or instructional purposes // related to programming, coding, application development, or // information technology. Permission for such use, copying, // modification, merger, publication, distribution, sublicensing, // creation of derivative works, or sale is expressly withheld. // // This project and source code may use libraries or frameworks // that are released under various Open-Source licenses. Use of // those libraries and frameworks are governed by their own // individual licenses. // // 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 Vapor import Leaf import MongoKitten // MARK: - App. public func makeApp() throws -> Application { let app = Application() // Use leaf view rendering // Views are stored in Resources/Views as .leaf files app.views.use(.leaf) guard let connectionString = Environment.get("MONGODB") else { fatalError("No MongoDB connection string is available in .env") } // connectionString should be MONGODB=mongodb://localhost:27017,localhost:27018,localhost:27019/social-messaging-server try app.initializeMongoDB(connectionString: connectionString) // Refer: /Users/vudat81299/Desktop/DiplomaProject/Server/Sources/App/routes.swift registerRoutes(to: app) // Uncomment to run this service. try createTestingUsers(inDatabase: app.mongoDB) return app } // MARK: - Context. struct HomepageContext: Codable { let posts: [ResolvedTimelinePost] let suggestedUsers: [UserMongoDB] } // MARK: - Route. func registerRoutes(to app: Application) { app.get { request -> EventLoopFuture<View> in // Get the "server" cookie's string value guard let token = request.cookies["server"]?.string else { return request.view.render("MongoDB/loginMongoDB") } let accessToken = try request.application.jwt.verify(token, as: AccessToken.self) let posts = Repository.getFeed( forUser: accessToken.subject, inDatabase: request.mongoDB ) let suggestedUsers = Repository.findSuggestedUsers( forUser: accessToken.subject, inDatabase: request.mongoDB ) return posts.and(suggestedUsers).flatMap { posts, suggestedUsers in let context = HomepageContext( posts: posts, suggestedUsers: suggestedUsers ) return request.view.render("MongoDB/indexMongoDB", context) } } app.post("login") { request -> EventLoopFuture<Response> in let credentials = try request.content.decode(Credentials.self) return Repository.findUser( byUsername: credentials.username, inDatabase: request.mongoDB ).flatMap { user -> EventLoopFuture<Response> in do { guard let user = user, try user.credentials.matchesPassword(credentials.password) else { return request.view.render("MongoDB/loginMongoDB", [ "error": "Incorrect credentials" ]).flatMap { view in return view.encodeResponse(for: request) } } let accessToken = AccessToken(subject: user) let token = try request.application.jwt.sign(accessToken) let response = request.redirect(to: "/") var cookie = HTTPCookies.Value(string: token) cookie.expires = accessToken.expiration.value response.cookies["server"] = cookie return request.eventLoop.makeSucceededFuture(response) } catch { return request.eventLoop.makeFailedFuture(error) } } } func listFileStructure (_ currentPath: String, _ path: String = "") { let fm = FileManager.default var fullPath = currentPath + path var a = fullPath.last! if a == Character("/") { } else { fullPath += "/" } print("---") // print(currentPath) // print(path) do { let items = try fm.contentsOfDirectory(atPath: fullPath) print("\(currentPath)\(path)") for item in items { // let isDir = (try URL(fileURLWithPath: fullPath).resourceValues(forKeys: [.isDirectoryKey])).isDirectory listFileStructure(fullPath, item) } } catch { // failed to read directory – bad permissions, perhaps? print("\(fullPath)") } } // func listDir(dir: String) { // // Create a FileManager instance // let contentsOfCurrentWorkingDirectory = try?FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: dir), includingPropertiesForKeys: nil, options: []) // // // process files // contentsOfCurrentWorkingDirectory?.forEach() { url in // // contentsOfCurrentWorkingDirectory?.forEach() { url2 in // print(url2) // } // } // } app.group(AuthenticationMiddleware()) { authenticated in authenticated.on(.POST, "post", body: .collect(maxSize: "5mb")) { request -> EventLoopFuture<Response> in listFileStructure(app.directory.publicDirectory) // listDir(dir: app.directory.publicDirectory) guard let accessToken = request.accessToken else { return request.eventLoop.makeSucceededFuture(request.redirect(to: "/")) } let createdPost = try request.content.decode(CreatePost.self) let fileId: EventLoopFuture<ObjectId?> if let file = createdPost.file, !file.isEmpty { // Upload the attached file to GridFS fileId = Repository.uploadFile(file, inDatabase: request.mongoDB).map { fileId in // This is needed to map the EventLoopFuture from `ObjectId` to `ObjectId?` return fileId } } else { fileId = request.eventLoop.makeSucceededFuture(nil) } return fileId.flatMap { fileId in let post = TimelinePost( _id: ObjectId(), text: createdPost.text, creationDate: Date(), fileId: fileId, creator: accessToken.subject ) // Insert the newly created post into MongoDB return Repository.createPost(post, inDatabase: request.mongoDB).map { return request.redirect(to: "/") } } } authenticated.get("follow", ":userId") { request -> EventLoopFuture<Response> in guard let userId = request.parameters.get("userId", as: ObjectId.self), let accessToken = request.accessToken, userId != accessToken.subject else { return request.eventLoop.makeSucceededFuture(request.redirect(to: "/")) } return Repository.findUser(byId: userId, inDatabase: request.mongoDB).flatMap { otherUser in return Repository.findUser(byId: accessToken.subject, inDatabase: request.mongoDB).flatMap { currentUser in return Repository.followUser(otherUser, fromAccount: currentUser, inDatabase: request.mongoDB) } }.map { _ in return request.redirect(to: "/") } } authenticated.get("images", ":fileId") { request -> EventLoopFuture<Response> in guard let fileId = request.parameters.get("fileId", as: ObjectId.self) else { throw Abort(.notFound) } return Repository.readFile(byId: fileId, inDatabase: request.mongoDB).map { data in return Response(body: Response.Body(data: data)) } } } }
// // ClientHomeViewController.swift // Heracles // // Created by Raghav Sreeram on 11/16/19. // Copyright © 2019 Shivam Desai. All rights reserved. // import UIKit import FirebaseDatabase import FirebaseAuth import FBSDKLoginKit import Gradients class ClientHomeViewController: UIViewController, AddedCalories, signOutProt { @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var weightTF: UITextField! @IBOutlet weak var caloriesTF: UITextField! @IBOutlet weak var workoutTF: UITextField! @IBOutlet weak var logsButton: UIButton! @IBOutlet weak var settingsButton: UIButton! @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var cameraButton: UIButton! var ref: DatabaseReference! var user: NSDictionary? override func viewDidLoad() { super.viewDidLoad() activityIndicator.hidesWhenStopped = true //setUpGradient() setUpView() } func setUpView(){ logsButton.setImage(UIImage(named: "bar-chart.png"), for: UIControl.State.normal) settingsButton.setImage(UIImage(named: "settings.png"), for: UIControl.State.normal) cameraButton.setImage(UIImage(named: "photo-camera.png"), for: UIControl.State.normal) saveButton.layer.cornerRadius = 10 weightTF.setUnderLine() caloriesTF.setUnderLine() workoutTF.setUnderLine() } func setUpGradient(){ let firstColor = UIColor(red: CGFloat(182/255.0), green: CGFloat(251/255.0), blue: CGFloat(255/255.0), alpha: 1.0) let secondColor = UIColor(red: CGFloat(131/255.0), green: CGFloat(164/255.0), blue: CGFloat(212/255.0), alpha: 1.0) let gradientLayer = CAGradientLayer() gradientLayer.frame = self.view.bounds gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor] self.view.layer.insertSublayer(gradientLayer, at: 0) } override func viewWillAppear(_ animated: Bool) { let formattedDate = getDate() setDateLabel(date: formattedDate) ref = Database.database().reference() let userID = Auth.auth().currentUser?.uid guard let userId = userID else{ return } activityIndicator.startAnimating() ref.child("user").child(userId).observeSingleEvent(of: .value, with: { (snapshot) in // Get user value let value = snapshot.value as? NSDictionary self.user = value let firstName = value?["firstName"] as? String ?? "" let lastName = value?["lastName"] as? String ?? "" self.userNameLabel.text = "Welcome, \(firstName) \(lastName)" let logs_ = value?["logs"] as? NSDictionary guard let logs = logs_ else{ print("no logs available") self.activityIndicator.stopAnimating() return } guard let log_today = logs[formattedDate] as? NSDictionary else{ print("no logs for \(formattedDate)date") self.activityIndicator.stopAnimating() return } let calorie = log_today["calorie"] as? String ?? "" let weight = log_today["weight"] as? String ?? "" let workout = log_today["workout"] as? String ?? "" self.caloriesTF.text = calorie self.weightTF.text = weight self.workoutTF.text = workout self.activityIndicator.stopAnimating() }) { (error) in print(error.localizedDescription) self.activityIndicator.stopAnimating() self.showNetworkError() } } // MARK: Logs button /// - Parameter sender: <#sender description#> @IBAction func logsButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle:nil) let vc = storyboard.instantiateViewController(withIdentifier: "pageViewController") let pgVC = vc as! PageViewController guard let user_ = self.user else{ print("no user") return } pgVC.clientID = Auth.auth().currentUser!.uid logClient = Auth.auth().currentUser!.uid pgVC.modalPresentationStyle = .fullScreen self.present(pgVC, animated: true) } func getDate() -> String { let date = Date() let format = DateFormatter() format.dateFormat = "MM-dd-yyyy" let formattedDate = format.string(from: date) return formattedDate } func setDateLabel(date: String) { self.dateLabel.text = "\(date)" } //Pass in firstName, lastName, height, accountType @IBAction func settingsPage(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle:nil) let vc = storyboard.instantiateViewController(withIdentifier: "Settings") let setVC = vc as! Settings guard let user_ = self.user else{ print("no user") return } setVC.firstName_input = user_["firstName"] as? String ?? "" setVC.lastName_input = user_["lastName"] as? String ?? "" setVC.height_ = user_["height"] as? String ?? "" setVC.clientCode = user_["clientID"] as? String ?? "" setVC.delegate = self setVC.modalPresentationStyle = .fullScreen self.present(setVC, animated: true) } @IBAction func cameraButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle:nil) let vc = storyboard.instantiateViewController(withIdentifier: "nutriVC") let nutriVC = vc as! NutritionViewController nutriVC.delegate = self nutriVC.modalPresentationStyle = .overFullScreen self.present(nutriVC, animated: true) } func userDidAddCalories(newCalories: String) { let curCalories = caloriesTF.text ?? "0" let cur = Double(curCalories) ?? 0 let new = Double(newCalories) ?? 0 let total = cur + new caloriesTF.text = "\(total)" } @IBAction func saveButton(_ sender: Any) { let userID = Auth.auth().currentUser?.uid guard let userId = userID else{ return } activityIndicator.startAnimating() ref.child("user").child(userId).child("logs").child(dateLabel.text ?? "").setValue(["calorie": caloriesTF.text ?? "", "weight": weightTF.text ?? "", "workout": workoutTF.text ?? ""]) { (error:Error?, ref:DatabaseReference) in if let error = error { print("Data could not be saved: \(error).") self.activityIndicator.stopAnimating() self.showNetworkError() } else { print("Data saved successfully!") self.showSaved() self.activityIndicator.stopAnimating() } } } /* Function to show generic network error alert */ func showNetworkError() { let alert = UIAlertController(title: "Network Error", message: "Unable to establish network connection! Please try again later.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in alert.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } /* Function to show information was saved */ func showSaved() { let alert = UIAlertController(title: "Success", message: "Your daily log was updated successfully!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in alert.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } //added UITapGestureRecognizer to View through interface builder @IBAction func handleTap(recognizer: UITapGestureRecognizer) { hideKeyboard() } @objc func hideKeyboard(){ view.endEditing(true) } func pressedSignOut() { print("pressed sign out protocol shud work!") self.dismiss(animated: false) { return } } }
/* * Copyright 2020 Coodly LLC * * 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 internal class RecordZoneChangesRequest: Request<Raw.ZoneChangesList> { private let zone: Raw.Zone private let token: String? internal init(zone: Raw.Zone, token: String?, variables: Variables) { self.zone = zone self.token = token super.init(variables: variables) } override func performRequest() { let body = Raw.Request().query(in: zone, since: token) post(to: "/changes/zone", body: body, in: .private) } }
// // Push.swift // AblySpec // // Created by Ricardo Pereira on 04/05/2018. // Copyright © 2018 Ably. All rights reserved. // import Ably import Nimble import Quick class Push : QuickSpec { struct TestDeviceToken { static let tokenBase64 = "HYRXxPSQdt1pnxqtDAvc6PTTLH7N6okiBhYyLClJdmQ=" static let tokenData = Data(base64Encoded: tokenBase64, options: [])! static let tokenString = tokenData.map { String(format: "%02x", $0) }.joined() } override func spec() { var rest: ARTRest! var mockHttpExecutor: MockHTTPExecutor! var storage: MockDeviceStorage! var stateMachineDelegate: StateMachineDelegate! beforeEach { rest = ARTRest(key: "xxxx:xxxx") rest.internal.resetDeviceSingleton() mockHttpExecutor = MockHTTPExecutor() rest.internal.httpExecutor = mockHttpExecutor storage = MockDeviceStorage() rest.internal.storage = storage stateMachineDelegate = StateMachineDelegate() rest.push.internal.createActivationStateMachine(withDelegate: stateMachineDelegate!) } // RSH2 describe("activation") { // RSH2a it("activate method should send a CalledActivate event to the state machine") { defer { rest.push.internal.activationMachine.transitions = nil } waitUntil(timeout: testTimeout) { done in rest.push.internal.activationMachine.transitions = { event, _, _ in if event is ARTPushActivationEventCalledActivate { done() } } rest.push.activate() } } // RSH2b it("deactivate method should send a CalledDeactivate event to the state machine") { defer { rest.push.internal.activationMachine.transitions = nil } waitUntil(timeout: testTimeout) { done in rest.push.internal.activationMachine.transitions = { event, _, _ in if event is ARTPushActivationEventCalledDeactivate { done() } } rest.push.deactivate() } } // RSH2c / RSH8g it("should handle GotPushDeviceDetails event when platform’s APIs sends the details for push notifications") { let stateMachine = rest.push.internal.activationMachine let testDeviceToken = "xxxx-xxxx-xxxx-xxxx-xxxx" stateMachine.rest.device.setAndPersistDeviceToken(testDeviceToken) let stateMachineDelegate = StateMachineDelegate() stateMachine.delegate = stateMachineDelegate defer { stateMachine.transitions = nil stateMachine.delegate = nil stateMachine.rest.device.setAndPersistDeviceToken(nil) } waitUntil(timeout: testTimeout) { done in stateMachine.transitions = { event, _, _ in if event is ARTPushActivationEventGotPushDeviceDetails { done() } } rest.push.activate() } } // RSH2d / RSH8h it("sends GettingPushDeviceDetailsFailed when push registration fails") { let stateMachine = rest.push.internal.activationMachine defer { stateMachine.transitions = nil } waitUntil(timeout: testTimeout) { done in stateMachine.transitions = { event, _, _ in if event is ARTPushActivationEventGettingPushDeviceDetailsFailed { done() } } rest.push.activate() let error = NSError(domain: ARTAblyErrorDomain, code: 42, userInfo: nil) ARTPush.didFailToRegisterForRemoteNotificationsWithError(error, rest: rest) } } // https://github.com/ably/ably-cocoa/issues/877 it("should update LocalDevice.clientId when it's null with auth.clientId") { let expectedClientId = "foo" let options = AblyTests.clientOptions() options.authCallback = { tokenParams, completion in getTestTokenDetails(clientId: expectedClientId, completion: { tokenDetails, error in expect(error).to(beNil()) guard let tokenDetails = tokenDetails else { fail("TokenDetails are missing"); return } expect(tokenDetails.clientId) == expectedClientId completion(tokenDetails, error) }) } let rest = ARTRest(options: options) let mockHttpExecutor = MockHTTPExecutor() rest.internal.httpExecutor = mockHttpExecutor let storage = MockDeviceStorage() rest.internal.storage = storage rest.internal.resetDeviceSingleton() var stateMachine: ARTPushActivationStateMachine! waitUntil(timeout: testTimeout) { done in rest.push.internal.getActivationMachine { machine in stateMachine = machine done() } } let testDeviceToken = "xxxx-xxxx-xxxx-xxxx-xxxx" stateMachine.rest.device.setAndPersistDeviceToken(testDeviceToken) let stateMachineDelegate = StateMachineDelegate() stateMachine.delegate = stateMachineDelegate defer { stateMachine.transitions = nil stateMachine.delegate = nil stateMachine.rest.device.setAndPersistDeviceToken(nil) } expect(rest.device.clientId).to(beNil()) expect(rest.auth.clientId).to(beNil()) waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) stateMachine.transitions = { event, _, _ in if event is ARTPushActivationEventGotPushDeviceDetails { partialDone() } else if event is ARTPushActivationEventGotDeviceRegistration { stateMachine.transitions = nil partialDone() } } rest.push.activate() } expect(rest.device.clientId) == expectedClientId expect(rest.auth.clientId) == expectedClientId let registerRequest = mockHttpExecutor.requests.filter { req in req.httpMethod == "POST" && req.url?.path == "/push/deviceRegistrations" }.first switch extractBodyAsMsgPack(registerRequest) { case .failure(let error): fail(error) case .success(let httpBody): guard let requestedClientId = httpBody.unbox["clientId"] as? String else { fail("No clientId field in HTTPBody"); return } expect(requestedClientId).to(equal(expectedClientId)) } } // https://github.com/ably/ably-cocoa/issues/889 it("should store the device token data as string") { let expectedDeviceToken = TestDeviceToken.tokenString defer { rest.push.internal.activationMachine.transitions = nil } waitUntil(timeout: testTimeout) { done in rest.push.internal.activationMachine.onEvent = { event, _ in if event is ARTPushActivationEventGotPushDeviceDetails { done() } } ARTPush.didRegisterForRemoteNotifications(withDeviceToken: TestDeviceToken.tokenData, rest: rest) } expect(storage.keysWritten.keys).to(contain(["ARTDeviceToken"])) expect(storage.keysWritten.at("ARTDeviceToken")?.value as? String).to(equal(expectedDeviceToken)) } // https://github.com/ably/ably-cocoa/issues/888 it("should not sync the local device dispatched in internal queue") { expect { ARTPush.didRegisterForRemoteNotifications(withDeviceToken: TestDeviceToken.tokenData, rest: rest) }.toNot(raiseException()) } } context("LocalDevice") { // RSH8 it("has a device method that returns a LocalDevice") { let _: ARTLocalDevice = ARTRest(key: "fake:key").device let _: ARTLocalDevice = ARTRealtime(key: "fake:key").device } // RSH8a it("the device is lazily populated from the persisted state") { let testToken = "testDeviceToken" let testIdentity = ARTDeviceIdentityTokenDetails( token: "123456", issued: Date(), expires: Date.distantFuture, capability: "", clientId: "" ) let rest = ARTRest(key: "fake:key") rest.internal.storage = storage storage.simulateOnNextRead(string: testToken, for: ARTDeviceTokenKey) storage.simulateOnNextRead(data: testIdentity.archive(), for: ARTDeviceIdentityTokenKey) let device = rest.device expect(device.deviceToken()).to(equal(testToken)) expect(device.identityTokenDetails?.token).to(equal(testIdentity.token)) } // RSH8d context("when using token authentication") { it("new clientID is set") { let options = ARTClientOptions(key: "fake:key") options.autoConnect = false options.authCallback = { _, callback in delay(0.1) { callback(ARTTokenDetails(token: "fake:token", expires: nil, issued: nil, capability: nil, clientId: "testClient"), nil) } } let realtime = ARTRealtime(options: options) expect(realtime.device.clientId).to(beNil()) waitUntil(timeout: testTimeout) { done in realtime.auth.authorize { _, _ in done() } } expect(realtime.device.clientId).to(equal("testClient")) } } // RSH8d context("when getting a client ID from CONNECTED message") { it("new clientID is set") { let options = ARTClientOptions(key: "fake:key") options.autoConnect = false let realtime = ARTRealtime(options: options) expect(realtime.device.clientId).to(beNil()) realtime.internal.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in realtime.connection.once(.connected) { _ in done() } realtime.connect() let transport = realtime.internal.transport as! TestProxyTransport transport.actionsIgnored += [.error] transport.simulateTransportSuccess(clientId: "testClient") } expect(realtime.device.clientId).to(equal("testClient")) } } // RSH8e it("authentication on registered device sends a GotPushDeviceDetails with new clientID") { let testToken = "testDeviceToken" let testIdentity = ARTDeviceIdentityTokenDetails( token: "123456", issued: Date(), expires: Date.distantFuture, capability: "", clientId: "" ) let options = ARTClientOptions(key: "fake:key") options.autoConnect = false options.authCallback = { _, callback in delay(0.1) { callback(ARTTokenDetails(token: "fake:token", expires: nil, issued: nil, capability: nil, clientId: "testClient"), nil) } } let realtime = ARTRealtime(options: options) let storage = MockDeviceStorage( startWith: ARTPushActivationStateWaitingForNewPushDeviceDetails( machine: ARTPushActivationStateMachine(rest: rest.internal, delegate: StateMachineDelegate()) ) ) realtime.internal.rest.storage = storage var stateMachine: ARTPushActivationStateMachine! waitUntil(timeout: testTimeout) { done in realtime.internal.rest.push.getActivationMachine { machine in stateMachine = machine done() } } let delegate = StateMachineDelegate() stateMachine.delegate = delegate storage.simulateOnNextRead(string: testToken, for: ARTDeviceTokenKey) storage.simulateOnNextRead(data: testIdentity.archive(), for: ARTDeviceIdentityTokenKey) waitUntil(timeout: testTimeout) { done in stateMachine.transitions = { event, _, _ in if event is ARTPushActivationEventGotPushDeviceDetails { done() } } realtime.auth.authorize { _, _ in } } expect(realtime.device.clientId).to(equal("testClient")) } // RSH8f it("sets device's client ID from registration response") { let expectedClientId = "testClientId" let stateMachineDelegate = StateMachineDelegateCustomCallbacks() stateMachineDelegate.onPushCustomRegisterIdentity = { _, _ in return ARTDeviceIdentityTokenDetails( token: "123456", issued: Date(), expires: Date.distantFuture, capability: "", clientId: expectedClientId ) } rest.push.internal.activationMachine.delegate = stateMachineDelegate expect(rest.device.clientId).to(beNil()) waitUntil(timeout: testTimeout) { done in stateMachineDelegate.onDidActivateAblyPush = { _ in done() } rest.push.activate() ARTPush.didRegisterForRemoteNotifications(withDeviceToken: "testDeviceToken".data(using: .utf8)!, rest: rest) } expect(rest.device.clientId).to(equal(expectedClientId)) } } context("Registerer Delegate option") { it("a successful activation should call the correct registerer delegate method") { let options = AblyTests.commonAppSetup() options.key = "xxxx:xxxx" let pushRegistererDelegate = StateMachineDelegate() options.pushRegistererDelegate = pushRegistererDelegate let rest = ARTRest(options: options) waitUntil(timeout: testTimeout) { done in pushRegistererDelegate.onDidActivateAblyPush = { _ in done() } pushRegistererDelegate.onDidDeactivateAblyPush = { _ in fail("should not be called") } rest.push.activate() ARTPush.didRegisterForRemoteNotifications(withDeviceToken: TestDeviceToken.tokenData, rest: rest) } } it("registerer delegate should not hold a strong instance reference") { let options = AblyTests.commonAppSetup() options.key = "xxxx:xxxx" var pushRegistererDelegate: StateMachineDelegate? = StateMachineDelegate() options.pushRegistererDelegate = pushRegistererDelegate let rest = ARTRest(options: options) expect(rest.internal.options.pushRegistererDelegate).toNot(beNil()) pushRegistererDelegate = nil expect(rest.internal.options.pushRegistererDelegate).to(beNil()) } } } }
// // UIViewController.swift // PracticeIGListKit // // Created by 松尾淳平 on 2021/03/27. // import UIKit class UIViewController3: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let col = UICollectionView(frame: CGRect(x: 100, y: 0, width: 1000, height: 100), collectionViewLayout: UICollectionViewLayout()) view.addSubview(col) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
/* * Fluxor * Copyright (c) Morten Bjerg Gregersen 2020 * MIT license, see LICENSE file for details */ import Combine /** A side effect that happens as a response to a dispatched `Action`. An `Effect` can: - give a new `Action` to dispatch (a `dispatchingOne` effect) - give an array of new `Action`s to dispatch (a `dispatchingMultiple` effect) - give nothing (a `nonDispatching` effect) */ public enum Effect<Environment> { /// An `Effect` that publishes an `Action` to dispatch. case dispatchingOne(_ publisher: (AnyPublisher<Action, Never>, Environment) -> AnyPublisher<Action, Never>) /// An `Effect` that publishes multiple `Action`s to dispatch. case dispatchingMultiple(_ publisher: (AnyPublisher<Action, Never>, Environment) -> AnyPublisher<[Action], Never>) /// An `Effect` that handles the action but doesn't publish a new `Action`. case nonDispatching(_ cancellable: (AnyPublisher<Action, Never>, Environment) -> AnyCancellable) } /// A collection of `Effect`s. public protocol Effects { /// The environment set up in the `Store` passed to every `Effect`. associatedtype Environment /// The `Effect`s to register on the `Store`. var enabledEffects: [Effect<Environment>] { get } /// The identifier for the `Effects` static var id: String { get } } public extension Effects { var enabledEffects: [Effect<Environment>] { Mirror(reflecting: self).children.compactMap { $0.value as? Effect<Environment> } } static var id: String { .init(describing: Self.self) } }
// // PartnerCell.swift // GardenCoceral // // Created by shiliuhua on 2018/5/22. // Copyright © 2018年 tongna. All rights reserved. // import UIKit class PartnerCell: UITableViewCell { @IBOutlet var bigImageView: UIImageView! @IBOutlet var titleLabel: UILabel! @IBOutlet var descLabel: UILabel! @IBOutlet var dateLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configure(with vm:PartnerRepresentable) -> Void { bigImageView.sd_setImage(with: URL.init(string: vm.headImageStr), placeholderImage: UIImage.init(named: "加载图片"), options: .retryFailed, progress: nil, completed: nil) titleLabel.text = vm.titleStr descLabel.text = vm.descStr dateLabel.text = vm.dateStr } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // GameState+Extensions.swift // HiveMindCore // // Created by Joseph Roque on 2019-03-03. // Copyright © 2019 Joseph Roque. All rights reserved. // import Foundation import HiveEngine extension GameState { /// Get all units with available movements /// /// - Parameters: /// - player: player to get moveable units for func moveableUnits(for player: Player) -> [HiveEngine.Unit] { guard let units = unitsInPlay[player] else { return [] } return units.keys.filter { $0.availableMoves(in: self).count > 0 } } /// Count the number of sides of a unit that are empty /// /// - Parameters: /// - unit: the unitt to count sides of func exposedSides(of unit: HiveEngine.Unit) -> Int { return 6 - units(adjacentTo: unit).count } // API /// Get all available moves, sorted based on their estimated value /// /// - Parameters: /// - evaluator: to evaluate elements of the movement func sortMoves(evaluator: Evaluator, with support: GameStateSupport) -> [Movement] { return availableMoves.sorted(by: { return evaluator.eval(movement: $0, in: self, with: support) < evaluator.eval(movement: $1, in: self, with: support) }) } /// Convert the state to a JSON string func json() -> String { let encoder = JSONEncoder() guard let data = try? encoder.encode(self) else { return "" } return String(data: data, encoding: .utf8) ?? "" } }
import UIKit import Charts import Alamofire class StationDetailsViewController: UIViewController { var station: Station? @IBOutlet weak var barChart: BarChartView! override func viewDidLoad() { super.viewDidLoad() if let station = station { title = station.name configureChartData() configureChartView() } } @IBAction func showPage() { if let url = URL(string: "https://powietrze.gios.gov.pl/pjp/content/measuring_air_assessment_rating_info") { UIApplication.shared.open(url, options: [:]) } } //MARK: - chart func getData() -> [ChartDataEntry] { var data = [ChartDataEntry]() data.append(BarChartDataEntry(x: 0, y: getMeasurement(quality: station?.condition!.so2))) data.append(BarChartDataEntry(x: 1, y: getMeasurement(quality: station?.condition!.no2))) data.append(BarChartDataEntry(x: 2, y: getMeasurement(quality: station?.condition!.co))) data.append(BarChartDataEntry(x: 3, y: getMeasurement(quality: station?.condition!.pm10))) data.append(BarChartDataEntry(x: 4, y: getMeasurement(quality: station?.condition!.pm25))) data.append(BarChartDataEntry(x: 5, y: getMeasurement(quality: station?.condition!.o3))) data.append(BarChartDataEntry(x: 6, y: getMeasurement(quality: station?.condition!.c6h6))) return data } func configureChartData() { let data = getData() let chartDataSet = BarChartDataSet(values: data, label: "Quality") chartDataSet.colors = [data[0].getColor(), data[1].getColor(), data[2].getColor(), data[3].getColor(), data[4].getColor(), data[5].getColor(), data[6].getColor()] let chartData = BarChartData(dataSet: chartDataSet) barChart.data = chartData } func configureChartView() { barChart.leftAxis.axisMinimum = 0 barChart.leftAxis.axisMaximum = 6 let measurementNames = ["so2", "no2", "co", "pm10", "pm25", "o3", "c6h6"] barChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: measurementNames) barChart.chartDescription?.text = "" barChart.borderLineWidth = 2 barChart.xAxis.granularity = 1 barChart.highlighter = nil barChart.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInCirc) barChart.xAxis.labelPosition = XAxis.LabelPosition.bottom barChart.drawValueAboveBarEnabled = false barChart.scaleYEnabled = false barChart.scaleXEnabled = false barChart.pinchZoomEnabled = false barChart.doubleTapToZoomEnabled = false barChart.legend.enabled = false barChart.data?.setDrawValues(false) barChart.rightAxis.enabled = false barChart.xAxis.drawGridLinesEnabled = false } func getMeasurement(quality: String?) -> Double { if let quality = quality { switch quality { case "Bardzo dobry": return 6 case "Dobry": return 5 case "Umiarkowany": return 4 case "Dostateczny": return 3 case "Zły": return 2 case "Bardzo zły": return 1 default: return 0 } } return 0 } }
// // DrawingPad.swift // DrawingPadSwiftUI // // Created by Martin Mitrevski on 20.07.19. // Copyright © 2019 Mitrevski. All rights reserved. // import SwiftUI struct DrawingPad: View { @Binding var currentDrawing: ListDrawing @Binding var drawings: [ListDrawing] @Binding var color: Color @Binding var lineWidth: CGFloat var previousColor: Color = Color.black var body: some View { GeometryReader { geometry in ZStack { ForEach((0..<drawings.count), id: \.self) { index in let drawing = drawings[index] self.add(drawing: drawing) } self.add(drawing: self.currentDrawing) } .background(Color(white: 0.95)) .gesture( DragGesture(minimumDistance: 0.1) .onChanged({ (value) in let currentPoint = value.location if currentPoint.y >= 0 && currentPoint.y < geometry.size.height { let currentDrawingPoint = DrawingObject(point: currentPoint, colorPoint: color) self.currentDrawing.points.append(currentDrawingPoint) } }) .onEnded({ (value) in self.drawings.append(self.currentDrawing) self.currentDrawing = ListDrawing() }) ) } .frame(maxHeight: .infinity) } private func add(drawing: ListDrawing, toPath path: inout Path) { let points = drawing.points if points.count > 1 { for i in 0..<points.count-1 { let current = points[i] let next = points[i+1] path.move(to: current.point) path.addLine(to: next.point) } } } private func add(drawing: ListDrawing) -> some View { let points = drawing.points var currentColor = Color.black let mainPath = Path { path in if points.count > 1 { for i in 0..<points.count-1 { let current = points[i] let next = points[i+1] path.move(to: current.point) path.addLine(to: next.point) currentColor = current.colorPoint } } }.stroke(currentColor, lineWidth: self.lineWidth) return mainPath } }
// // PlanetsModel.swift // Planets // // Created by Andrew Kealy on 17/11/2021. // import Foundation struct PlanetsModel { var index = 0 var nextIsAvailable: Bool = true var previousIsAvailable: Bool = false var models = [ Model(id: 0, name: "Mercury", modelName: "Mercury.usdz", details: "Mercury is the smallest planet in the Solar System and the closest to the Sun. Its orbit around the Sun takes 87.97 Earth days, the shortest of all the Sun's planets. It is named after the Roman god Mercurius (Mercury), god of commerce, messenger of the gods, and mediator between gods and mortals, corresponding to the Greek god Hermes (Ἑρμῆς). "), Model(id: 1, name: "Venus", modelName: "Venus.usdz", details: "Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty. As the brightest natural object in Earth's night sky after the Moon, Venus can cast shadows and can be, on rare occasions, visible to the naked eye in broad daylight. Venus lies within Earth's orbit, and so never appears to venture far from the Sun, either setting in the west just after dusk or rising in the east a little while before dawn."), Model(id: 2, name: "Earth", modelName: "Earth.usdz", details: "Earth is the third planet from the Sun and the only astronomical object known to harbour and support life. According to radiometric dating estimation and other evidence, Earth formed over 4.5 billion years ago. Three-quarters of the atmosphere's mass is contained within the first 11 km (6.8 mi) of the surface. This lowest layer is "), Model(id: 3, name: "Moon", modelName: "Moon.usdz", details: "The Moon is Earth's only natural satellite. At about one-quarter the diameter of Earth (comparable to the width of Australia), it is the largest natural satellite in the Solar System relative to the size of its planet, the fifth largest satellite in the Solar System overall, and is larger than any known dwarf planet." ), Model(id: 4, name: "Mars", modelName: "Mars.usdz", details: "Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System, being larger than only Mercury. In English, Mars carries the name of the Roman god of war and is often referred to as the Red Planet. The latter refers to the effect of the iron oxide prevalent on Mars's surface, which gives it a reddish appearance (as shown), that is distinctive among the astronomical bodies visible to the naked eye."), Model(id: 5, name: "Jupiter", modelName: "Jupiter.usdz", details: "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass more than two and a half times that of all the other planets in the Solar System combined, but slightly less than one-thousandth the mass of the Sun. Jupiter is the third-brightest natural object in the Earth's night sky after the Moon and Venus. It has been observed since pre-historic times and is named after the Roman god Jupiter, the king of the gods, because of its observed size."), Model(id: 6, name: "Saturn", modelName: "Saturn.usdz", details: "Saturn is the sixth planet from the Sun and the second-largest in the Solar System, after Jupiter. It is a gas giant with an average radius of about nine and a half times that of Earth. It only has one-eighth the average density of Earth; however, with its larger volume, Saturn is over 95 times more massive."), Model(id: 7, name: "Uranus", modelName: "Uranus.usdz", details: "Uranus is the seventh planet from the Sun. Its name is a reference to the Greek god of the sky, Uranus, who, according to Greek mythology, was the great-grandfather of Ares (Mars), grandfather of Zeus (Jupiter) and father of Cronus (Saturn). It has the third-largest planetary radius and fourth-largest planetary mass in the Solar System. Uranus is similar in composition to Neptune, and both have bulk chemical compositions which differ from that of the larger gas giants Jupiter and Saturn."), Model(id: 8, name: "Neptune", modelName: "Neptune.usdz", details: "Neptune is the eighth and farthest-known Solar planet from the Sun. In the Solar System, it is the fourth-largest planet by diameter, the third-most-massive planet, and the densest giant planet. It is 17 times the mass of Earth, slightly more massive than its near-twin Uranus. Neptune is denser and physically smaller than Uranus because its greater mass causes more gravitational compression of its atmosphere."), Model(id: 9, name: "Pluto", modelName: "Pluto.usdz", details: "Pluto (is a dwarf planet in the Kuiper belt, a ring of bodies beyond the orbit of Neptune. It was the first and the largest Kuiper belt object to be discovered. After Pluto was discovered in 1930, it was declared to be the ninth planet from the Sun. Beginning in the 1990s, its status as a planet was questioned following the discovery of several objects of similar size in the Kuiper belt and the scattered disc, including the dwarf planet Eris. This led the International Astronomical Union (IAU) in 2006 to formally define the term planet — excluding Pluto and reclassifying it as a dwarf planet.") ] var currentModel: Model = Model(id: 0, name: "Mercury", modelName: "Mercury.usdz", details: "Mercury is the smallest planet in the Solar System and the closest to the Sun. Its orbit around the Sun takes 87.97 Earth days, the shortest of all the Sun's planets. It is named after the Roman god Mercurius (Mercury), god of commerce, messenger of the gods, and mediator between gods and mortals, corresponding to the Greek god Hermes (Ἑρμῆς). ") mutating func getNextModel() -> Model { if nextIsAvailable { index += 1 } if (index == models.count - 1) { nextIsAvailable = false } if (!previousIsAvailable) { previousIsAvailable.toggle() } return models[index] } mutating func getPreviousModel() -> Model { if previousIsAvailable { index -= 1 } if(index == 0) { previousIsAvailable = false } if(!nextIsAvailable) { nextIsAvailable.toggle() } return models[index] } } struct Model: Identifiable { var id: Int var name: String var modelName: String var details: String }
// // ViewController.swift // UiPickerView Test // // Created by 김종현 on 2018. 4. 14.. // Copyright © 2018년 김종현. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var myPickerView: UIPickerView! @IBOutlet weak var col0Label: UILabel! @IBOutlet weak var col1Label: UILabel! override func viewDidLoad() { super.viewDidLoad() myPickerView.delegate = self myPickerView.dataSource = self } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 0 { return 10 } else { return 50 } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0 { return "1st component \(row)" } else { return "2nd component \(row)" } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { col0Label.text = "comp = \(component+1) row = \(row)" } }
// // NTWTagCollectionViewCell.swift // Networkd // // Created by CloudStream on 5/4/17. // Copyright © 2017 CloudStream LLC. All rights reserved. // import UIKit class NTWTagCollectionViewCell: UICollectionViewCell { @IBOutlet weak var tagButton: UIButton! }
// // ViewController.swift // Replica IMDb // // Created by Harshad Sahu on 18/01/21. // import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { //MARK: Outlet Connections @IBOutlet weak var trailerCollectionView: UICollectionView! @IBOutlet weak var featureCollectionView: UICollectionView! @IBOutlet weak var fansCollectionView: UICollectionView! @IBOutlet weak var exploreCollectionView: UICollectionView! @IBOutlet weak var segments: UISegmentedControl! @IBOutlet weak var bornToday: UICollectionView! //MARK: Declaration var trailerArray = [UIImage(named: "21"), UIImage(named: "22"), UIImage(named: "23"), UIImage(named: "24"), UIImage(named: "25"), UIImage(named: "26"), UIImage(named: "27"), UIImage(named: "28"), UIImage(named: "29"), UIImage(named: "30")] var featureTodayArray = [UIImage(named: "1"), UIImage(named: "2"), UIImage(named: "3"), UIImage(named: "4"), UIImage(named: "5"), UIImage(named: "6"), UIImage(named: "7"), UIImage(named: "8"), UIImage(named: "9"), UIImage(named: "10")] var featureLabel = ["Meet the 'LUPIN' Cast", "Meet One Night in Miami Cast", "Photos We Love", "Latest Posters", "Celebrity Twins", "Throwback 'Sex & the City'", "TV Tracker: SHOWS", "New on Netflix India", "Watch Latest Movies", "Quick Shots"] var fanMoviesArray = [UIImage(named: "11"), UIImage(named: "12"), UIImage(named: "13"), UIImage(named: "14"), UIImage(named: "15"), UIImage(named: "16"), UIImage(named: "17"), UIImage(named: "18"), UIImage(named: "19"), UIImage(named: "20")] var fanRating = ["⭐️7.9", "⭐️8.1", "⭐️7.5", "⭐️7.4", "⭐️7.8", "⭐️9.5", "⭐️8.6", "⭐️8.4", "⭐️9.3", "⭐️8.8"] var fanMovieName = ["Master", "Soul", "Tenet", "Bridgerton", "Lupin", "Breaking Bad", "Interstellar", "Avengers Endgame", "The Shawshank Redemption", "The Mandolorian"] var yearFan = [ "2021 NR 2h 59m", "2020 PG 1h 40m", "2020 PG 2h 30m", "2020 8eps", "2021 7ep", "2008-13 62eps", "2014 2h 40m", "2019 3h 10m", "1994 R 2h 22m", "2019 24 eps"] var primeMovieArray = [UIImage(named: "31"), UIImage(named: "32"), UIImage(named: "33"), UIImage(named: "34"), UIImage(named: "35"), UIImage(named: "36")] var primeRating = ["⭐️8.9", "⭐️7.1", "⭐️8.5", "⭐️6.4", "⭐️8.8", "⭐️9.5"] var primeMovieName = ["Mirzapur", "Mirzapur 2", "The Family Man", "The Night in Miami", "Birds of Prey", "Jack Ryan"] var primeYear = [ "2021 NR 2h 59m", "2020 PG 1h 40m", "2020 PG 2h 30m", "2020 8eps", "2021 7ep", "2008-13 62eps"] var HotstarMovieArray = [UIImage(named: "41"), UIImage(named: "42"), UIImage(named: "43"), UIImage(named: "44"), UIImage(named: "45"), UIImage(named: "46")] var hotstarRating = ["⭐️7.9", "⭐️8.1", "⭐️7.5", "⭐️7.4", "⭐️7.8", "⭐️9.5"] var hotstarMovieName = ["Hostage", "Criminal Justice", "Special Ops", "Aarya", "Dil Bechara", "Laxmii"] var hotstarYear = [ "2021 NR 2h 59m", "2020 PG 1h 40m", "2020 PG 2h 30m", "2020 8eps", "2021 7ep", "2008-13 62eps"] var vootMovieArray = [UIImage(named: "51"), UIImage(named: "52"), UIImage(named: "53"), UIImage(named: "54"), UIImage(named: "55"), UIImage(named: "56")] var vootRating = ["⭐️8.1", "⭐️6.1", "⭐️7.5", "⭐️7.4", "⭐️7.8", "⭐️9.0"] var vootMovieName = ["Asur", "Bigg Boss", "Bajirao Mastani", "Baywatch", "The Office", "Broad City"] var vootYear = [ "2021 NR 2h 59m", "2020 PG 1h 40m", "2020 PG 2h 30m", "2020 8eps", "2021 7ep", "2008-13 62eps"] var MXPlayerMovieArray = [UIImage(named: "61"), UIImage(named: "62"), UIImage(named: "63"), UIImage(named: "64"), UIImage(named: "65"), UIImage(named: "66")] var mxPlayerRating = ["⭐️8.9", "⭐️6.1", "⭐️7.5", "⭐️6.4", "⭐️7.8", "⭐️8.5"] var mxPlayerMovieName = ["Aashram", "Aashram 2", "The Expandables 2", "Crank", "The Mechanic", "Drive"] var mxPlayerYear = [ "2021 NR 2h 59m", "2020 PG 1h 40m", "2020 PG 2h 30m", "2020 8eps", "2021 7ep", "2008-13 62eps"] var bornArray = [UIImage(named: "71"), UIImage(named: "72"), UIImage(named: "73"), UIImage(named: "74"), UIImage(named: "75"), UIImage(named: "76"), UIImage(named: "77"), UIImage(named: "78"), UIImage(named: "79"), UIImage(named: "80")] var celebNames = ["Logan Lerman", "Katey Sagal", "Drea de Matteo", "Luke Macfarlane", "Mickey Sumner", "Dolly Parton","Jodie Sweetin" , "Rob Delaney", "Paul McCrane", "Rachel Luttrell"] var age = ["29", "67", "49", "41", "37", "75", "39", "44", "60", "50"] var timer = Timer() var counter = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // this function will help us in order to achieve auto scrolling. DispatchQueue.main.async { self.timer = Timer.scheduledTimer(timeInterval: 2.5 , target: self, selector: #selector(self.changeImage), userInfo: nil, repeats: true) } } //Function which we be called in viewDidLoad() by Timer.scheduledTImer() to iterate over @objc func changeImage() { if (counter < trailerArray.count){ let index = IndexPath.init(item: counter, section: 0) self.trailerCollectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true) counter += 1 } else{ counter = 0 let index = IndexPath.init(item: counter, section: 0) self.trailerCollectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true) // counter += 1 } } //MARK: Mandatory Methods func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == exploreCollectionView { return 6 } return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == featureCollectionView { let cell1 = featureCollectionView.dequeueReusableCell(withReuseIdentifier: "FeatureCollectionViewCell", for: indexPath) as! FeatureCollectionViewCell cell1.featureImage.image = featureTodayArray[indexPath.row] cell1.featureLabel.text = featureLabel[indexPath.row] return cell1 } if collectionView == fansCollectionView { let cell2 = fansCollectionView.dequeueReusableCell(withReuseIdentifier: "BasicCollectionViewCell", for: indexPath) as! BasicCollectionViewCell cell2.fanImage.image = fanMoviesArray[indexPath.row] cell2.fanRating.text = fanRating[indexPath.row] cell2.fanMovie.text = fanMovieName[indexPath.row] cell2.fanYear.text = yearFan[indexPath.row] return cell2 } if collectionView == exploreCollectionView { let cell = exploreCollectionView.dequeueReusableCell(withReuseIdentifier: "ExploreCollectionViewCell", for: indexPath) as! ExploreCollectionViewCell switch segments.selectedSegmentIndex { case 0: cell.expImages.image = primeMovieArray[indexPath.row] cell.expRating.text = primeRating[indexPath.row] cell.expMovieName.text = primeMovieName[indexPath.row] cell.expYear.text = primeYear[indexPath.row] case 1: cell.expImages.image = HotstarMovieArray[indexPath.row] cell.expRating.text = hotstarRating[indexPath.row] cell.expMovieName.text = hotstarMovieName[indexPath.row] cell.expYear.text = hotstarYear[indexPath.row] case 2: cell.expImages.image = vootMovieArray[indexPath.row] cell.expRating.text = vootRating[indexPath.row] cell.expMovieName.text = vootMovieName[indexPath.row] cell.expYear.text = vootYear[indexPath.row] case 3: cell.expImages.image = MXPlayerMovieArray[indexPath.row] cell.expRating.text = mxPlayerRating[indexPath.row] cell.expMovieName.text = mxPlayerMovieName[indexPath.row] cell.expYear.text = mxPlayerYear[indexPath.row] default: break } return cell } if collectionView == bornToday{ let cell = bornToday.dequeueReusableCell(withReuseIdentifier: "BornCollectionViewCell", for: indexPath) as! BornCollectionViewCell cell.bornImages.image = bornArray[indexPath.row] cell.bornName.text = celebNames[indexPath.row] cell.bornAge.text = age[indexPath.row] return cell } let cell = trailerCollectionView.dequeueReusableCell(withReuseIdentifier: "TrailerCollectionViewCell", for: indexPath) as! TrailerCollectionViewCell cell.trailer.image = trailerArray[indexPath.row] return cell } //This is IBOutlet Action of segmented control which is responsible to reload data everytime when we switch the tabs of segmented controls @IBAction func segmentedSelection(_ sender: UISegmentedControl) { exploreCollectionView.reloadData() } }
// // MainView.swift // Set // // Created by klioop on 2021/08/04. // import UIKit class MainView: UIView { override func draw(_ rect: CGRect) { } }
// // HomeViewController.swift // SuperShop // // Created by David on 5/7/19. // Copyright © 2019 David. All rights reserved. // import UIKit class HomeViewController: UIViewController { var products: [Product] = [Product]() { didSet { updateCollection() } } let identifierCell = "producViewCell" var shopButton: BadgeBarButtonItem? = nil private let spacingCell:CGFloat = 15 @IBOutlet weak var productsCollectionView: UICollectionView! var soldProducts: [Product] = [Product]() override func viewDidLoad() { productsCollectionView.delegate = self productsCollectionView.dataSource = self productsCollectionView.register(UINib(nibName: "ProductsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: identifierCell) productsCollectionView.backgroundColor = UIColor.Shop.backgroundPage let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: spacingCell, left: spacingCell, bottom: spacingCell, right: spacingCell) layout.minimumLineSpacing = spacingCell layout.minimumInteritemSpacing = spacingCell productsCollectionView.collectionViewLayout = layout // Logo let logoView = UIImageView(image: UIImage(named: "logo")) logoView.contentMode = .scaleAspectFit navigationItem.titleView = logoView shopButton = BadgeBarButtonItem(title: "Cart", target: self, action: #selector(tapShopButton)) navigationItem.rightBarButtonItem = shopButton loadData() super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { updateBadgeArticles() } func updateCollection() { productsCollectionView.reloadData() } func loadData() { let client = ProductstClient() client.show { (products) in self.products = products } } @objc func tapShopButton() { let next = self.storyboard?.instantiateViewController(withIdentifier: "CartViewController") as! CartViewController next.listItems = soldProducts navigationController?.pushViewController(next, animated: true) } func addArticle(article: Product) { soldProducts.append(article) } func updateBadgeArticles() { guard let btn = self.shopButton else { return } btn.badgeText = "\(soldProducts.count)" } } extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return products.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifierCell, for: indexPath) as? ProductsCollectionViewCell else { return UICollectionViewCell() } cell.product = products[indexPath.row] cell.backgroundColor = .white cell.layer.cornerRadius = 8 return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let numberOfItemsPerRow:CGFloat = 2 let spacingBetweenCells:CGFloat = 4 let totalSpacing = (2 * self.spacingCell) + ((numberOfItemsPerRow - 1) * spacingBetweenCells) let width = (productsCollectionView.bounds.width - totalSpacing - self.spacingCell)/numberOfItemsPerRow //let height = width * 1.5 < 230 ? 230 : width * 1.5 return CGSize(width: width, height: 230) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let next = self.storyboard?.instantiateViewController(withIdentifier: "ProductViewController") as! ProductViewController next.product = products[indexPath.row] navigationController?.pushViewController(next, animated: true) } func successBuy() { soldProducts.removeAll() updateBadgeArticles() let alert = UIAlertController(title: "Congratulations!", message: "Your order is going on the way!", preferredStyle: .alert) let optionOk = UIAlertAction(title: "Ok", style: .default) { (sender) in self.dismiss(animated: true, completion: nil) } alert.addAction(optionOk) self.present(alert, animated: true) } }
// // SkillOtherWorker.swift // miniTopgun // // Created by Codemobiles on 7/24/2560 BE. // Copyright (c) 2560 Izpal. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit import Alamofire class SkillOtherWorker { func fetchAllSKillOther(idJsk:String, idResume:String, completion:@escaping([SkillOtherData]?) ->Void) { let rounter = AlamofireRouter.fetchSkillOther(idJsk: idJsk, idResume: idResume) Alamofire.request(rounter).responseJSON { (response) in switch response.result { case .success(let value): let re = SkillOtherBase(object: value) if re.success == 1{ if let list = re.data { completion(list) } } case .failure(let error): print(error) completion(nil) } } } }
// // File.swift // SweetHealth // // Created by Miguel Jaimes on 10/02/2020. // Copyright © 2020 Miguel Jaimes. All rights reserved. // import UIKit class Vallidator { private var valueCamp = false func emptyField(Field field: String)->Bool{ if field.isEmpty { valueCamp = true } else { valueCamp = false } return valueCamp } func emailEmpty(Email email:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailPred.evaluate(with: email) } func passwordLenght(Password password:String) -> Bool { if password.count >= 8 { valueCamp = true }else{ valueCamp = false } return valueCamp } func validationOfBothFields(Password1 password1:String,Password2 password2:String) -> Bool { if(password1 == password2) { valueCamp = true }else { valueCamp = false } return valueCamp } }
// // JournalViewModel.swift // Calm Cloud // // Created by Kate Duncan-Welke on 8/3/21. // Copyright © 2021 Kate Duncan-Welke. All rights reserved. // import Foundation import UIKit public class JournalViewModel { var days: [Int] = [] var currentPage = 0 var direction = 0 var monthBeginning: Date? var selectedFromCalendar: Int? var monthName = "" // MARK: Cells/collection view func getDayCount() -> Int { return days.count } func getDateLabel(index: Int) -> String { if days[index] == 0 { return "" } else { return "\(days[index])" } } func getBackgroundColor(index: Int) -> UIColor { if days[index] == 0 { return.white } else if days[index] % 2 == 0 { return Colors.pink } else { return .white } } func isCheckMarkHidden(index: Int) -> Bool { let calendar = Calendar.init(identifier: .gregorian) var hideCheck = false if let beginning = monthBeginning { var components = DateComponents() components.year = calendar.component(.year, from: beginning) components.month = calendar.component(.month, from: beginning) components.day = days[index] if let calendarDate = calendar.date(from: components) { for entry in EntryManager.loadedEntries { if let date = entry.date { if Calendar.current.isDate(date, inSameDayAs: calendarDate) { print("day match found") hideCheck = false return hideCheck } else { print("day match not found") hideCheck = true } } else { hideCheck = true } } } } return hideCheck } func isDayViewable(index: Int) -> Bool { if days[index] == 0 { return false } else { return true } } func selected(index: Int) -> Bool { let calendar = Calendar.init(identifier: .gregorian) if let beginning = monthBeginning { var components = DateComponents() components.year = calendar.component(.year, from: beginning) components.month = calendar.component(.month, from: beginning) components.day = days[index] if let calendarDate = calendar.date(from: components) { var i = 0 for entry in EntryManager.loadedEntries { if let date = entry.date { if Calendar.current.isDate(date, inSameDayAs: calendarDate) { selectedFromCalendar = i print("match found") break } else { selectedFromCalendar = nil print("match not found") } } i += 1 } } } if selectedFromCalendar != nil { return true } else { return false } } // MARK: Journal Entry func getMonthName() -> String { return monthName } func saveButtonEnabled() -> Bool { if let currentEntry = EntryManager.entry, let content = currentEntry.text { return false } else { return true } } func getEntryDate() -> String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none if let entry = EntryManager.entry, let chosenDate = entry.date { return dateFormatter.string(from: chosenDate) } else { return dateFormatter.string(from: Date()) } } func getEntryText() -> String { if let entry = EntryManager.entry, let content = entry.text { return content } else { return "Start typing . . ." } } func isEditable() -> Bool { if let entry = EntryManager.entry, let content = entry.text { return false } else { return true } } func increaseDirection() { direction += 1 } func decreaseDirection() { direction -= 1 } func goForward() -> Bool { if currentPage > 0 { currentPage -= 1 EntryManager.entry = EntryManager.loadedEntries[currentPage] return true } else { return false } } func goBackward() -> Bool { if currentPage < EntryManager.loadedEntries.count - 1 { currentPage += 1 EntryManager.entry = EntryManager.loadedEntries[currentPage] return true } else { return false } } func viewEntry() { if let selected = selectedFromCalendar { currentPage = selected EntryManager.entry = EntryManager.loadedEntries[currentPage] } } func configureEntry() { if currentPage == 0 { if EntryManager.loadedEntries.isEmpty { // if there are no entries add a blank one var managedContext = CoreDataManager.shared.managedObjectContext EntryManager.loadedEntries.insert(JournalEntry(context: managedContext), at: 0) } else { // if the entry's first item does not match the current date there is no entry for today, so add a blank one if let firstEntry = EntryManager.loadedEntries.first, let dateofEntry = firstEntry.date { let calendar = Calendar.init(identifier: .gregorian) let entryIsForToday = calendar.isDate(dateofEntry, inSameDayAs: Date()) if entryIsForToday == false { var managedContext = CoreDataManager.shared.managedObjectContext EntryManager.loadedEntries.insert(JournalEntry(context: managedContext), at: 0) } } } } if EntryManager.loadedEntries.count > 0 { EntryManager.entry = EntryManager.loadedEntries[currentPage] } } func configureCalendar() { let calendar = Calendar.init(identifier: .gregorian) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none // show initial calendar page for current month let today = Date() days.removeAll() if let monthToShow = calendar.date(byAdding: .month, value: direction, to: today) { let comps = calendar.dateComponents([.year, .month], from: monthToShow) let monthFormatter = DateFormatter() monthFormatter.dateFormat = "LLLL YYYY" let nameOfMonth = monthFormatter.string(from: monthToShow) monthName = nameOfMonth if let firstOfMonth = calendar.date(from: comps) { monthBeginning = firstOfMonth let dayOfWeek = calendar.component(.weekday, from: firstOfMonth) var comps2 = DateComponents() comps2.month = 1 comps2.day = -1 let endOfMonth = Calendar.current.date(byAdding: comps2, to: firstOfMonth) if dayOfWeek != 1 { let daysToAdd = dayOfWeek - 1 for day in 1...daysToAdd { days.append(0) } } if let end = endOfMonth { let endDay = calendar.component(.day, from: end) for day in 1...endDay { days.append(day) } } } } } func saveEntry(text: String?) -> Bool? { if text != nil && text != "Start typing . . ." { var managedContext = CoreDataManager.shared.managedObjectContext EntryManager.entry?.date = Date() EntryManager.entry?.text = text // remove empty placeholder EntryManager.loadedEntries.remove(at: 0) guard let newEntry = EntryManager.entry else { return nil } EntryManager.loadedEntries.insert(newEntry, at: 0) do { try managedContext.save() print("saved entry") if TasksManager.journal == false { TasksManager.journal = true DataFunctions.saveTasks(updatingActivity: false, removeAll: false) } return true } catch { // this should never be displayed but is here to cover the possibility //showAlert(title: "Save failed", message: "Notice: Data has not successfully been saved.") return nil } } else { print("text view was empty or nil") return nil } } }
// // ForceTouchView.swift // JvbForceTouchDemo // // Created by J.J.A.P. van Breukelen on 15-09-16. // Copyright © 2016 J.J.A.P. van Breukelen. All rights reserved. // import UIKit class ForceTouchView: UIView { /** //Just for demonstation purposes: we could use the force property of UITouch directly in the UIView subclass. override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else {return} print(touch.force) } */ }