Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
8
1.32M
// // R.reuseIdentifier.swift // YumaApp // // Created by Yuma Usa on 2018-06-18. // Copyright © 2018 Yuma Usa. All rights reserved. // import Foundation extension R { struct reuseIdentifier { fileprivate init() {} } }
// // MockRSSUrlConstructor.swift // AlbumRSSTests // // Created by Gavin Li on 8/16/20. // Copyright © 2020 Gavin Li. All rights reserved. // import Foundation @testable import AlbumRSS class MockRSSUrlConstructor: UrlConstructorProtocol { private let mockFile = "mockRSS" func rssFeedUrl() -> URL? { let bundle = Bundle(for: MockRSSUrlConstructor.self) guard let path = bundle.path(forResource: mockFile, ofType: "json") else { fatalError("Invalid URL") } let url = URL(fileURLWithPath: path) return url } func rssFeedUrlString() -> String { mockFile } }
// // LPaimUtilsOperators.swift // LPaimUtils // // Created by LPaimUtils on 29/10/14. // Copyright (c) 2014 LPaimUtils. All rights reserved. // import Foundation prefix operator ~ {} /** :returns: A NSDictionary with the object atributtes */ prefix public func ~( _object: AnyObject) -> NSDictionary{ if(_object.classForCoder.description() == "NSDictionary"){ return _object as! NSDictionary } var dictionary: NSMutableDictionary = NSMutableDictionary() for(var i = 0; i < reflect(_object).count; ++i){ if(reflect(_object)[i].0 == "super"){ continue } var valor: AnyObject? = _object.valueForKey("\(reflect(_object)[i].0)") dictionary.setValue(valor, forKey: reflect(_object)[i].0) } return dictionary } infix operator <-- {associativity left precedence 140} /** Populate a left object with the attributes of a right object */ public func <-- (left: AnyObject, right: AnyObject){ var dicionarioDeDados = ~right for field in dicionarioDeDados.allKeys { if(dicionarioDeDados.valueForKey(field as! String)!.classForCoder.description() == "NSDictionary"){ if(left.respondsToSelector(Selector(field as! String))){ var obj: AnyObject? = left.valueForKey(field as! String) if(obj != nil){ obj! <-- dicionarioDeDados.valueForKey(field as! String)! } } continue } if( dicionarioDeDados.valueForKey(field as! String)!.classForCoder.description() == "NSNull"){ continue } if(left.respondsToSelector(Selector(field as! String))){ left.setValue(dicionarioDeDados.valueForKey(field as! String), forKey: field as! String) }else if(left.respondsToSelector(Selector("_" + (field as! String)))){ left.setValue(dicionarioDeDados.valueForKey(field as! String), forKey: "_" + (field as! String)) } } }
import Cocoa let PanelSize = 120 let NUMAXES = 2 let NUMPANELS = 4 var panelIndex = Int() var selectIndex = Int() var controlPickerSelection = Int() var vcControl:ControlViewController! = nil var panelList:[ControlPanelView]! = nil var panelRect:[NSRect]! = nil class ControlViewController: NSViewController { @IBOutlet var panel1: ControlPanelView! @IBOutlet var panel2: ControlPanelView! @IBOutlet var panel3: ControlPanelView! @IBOutlet var panel4: ControlPanelView! func launchPopOver(_ pIndex:Int, _ sIndex:Int) { panelIndex = pIndex selectIndex = sIndex vc.presentPopover(self.view,"ControlPickerVC") } @IBAction func x1(_ sender: NSButton) { launchPopOver(0,0) } @IBAction func y1(_ sender: NSButton) { launchPopOver(0,1) } @IBAction func x2(_ sender: NSButton) { launchPopOver(1,0) } @IBAction func y2(_ sender: NSButton) { launchPopOver(1,1) } @IBAction func x3(_ sender: NSButton) { launchPopOver(2,0) } @IBAction func y3(_ sender: NSButton) { launchPopOver(2,1) } @IBAction func x4(_ sender: NSButton) { launchPopOver(3,0) } @IBAction func y4(_ sender: NSButton) { launchPopOver(3,1) } @IBAction func helpPressed(_ sender: NSButton) { showHelpPage(view,.Control) } override func viewDidLoad() { super.viewDidLoad() vcControl = self panelList = [ panel1,panel2,panel3,panel4 ] panelRect = [ // UL corner, flipped Y NSRect(x:020, y:320, width:PanelSize, height:PanelSize), NSRect(x:150, y:320, width:PanelSize, height:PanelSize), NSRect(x:020, y:166, width:PanelSize, height:PanelSize), NSRect(x:150, y:166, width:PanelSize, height:PanelSize)] for i in 0 ..< 4 { panelList[i].panelID = i } } // so user can issue commands while viewing the help page override func keyDown(with event: NSEvent) { func alterValueViaArrowKeys(_ axis:Int, _ direction:Int) { decodeSelectionIndex(getPanelWidgetIndex(panelIndex,axis)) if winHandler.widgetPointer(selectedWindow).data[selectedRow].alterValue(direction) { winHandler.refreshWidgetsAndImage() refreshControlPanels() } } updateModifierKeyFlags(event) vc.widget.updateAlterationSpeed(event) switch Int32(event.keyCode) { case LEFT_ARROW : alterValueViaArrowKeys(0,-1); return case RIGHT_ARROW : alterValueViaArrowKeys(0,+1); return case UP_ARROW : alterValueViaArrowKeys(1,-1); return case DOWN_ARROW : alterValueViaArrowKeys(1,+1); return case 48 : panelIndex = (panelIndex + 1) % 4; refreshControlPanels() // Tab default : break } vc.keyDown(with: event) } override func keyUp(with event: NSEvent) { vc.keyUp(with: event) } //MARK: - func widgetSelectionMade() { setPanelWidgetIndex(panelIndex,selectIndex,controlPickerSelection) panelList[panelIndex].refresh() } func refreshControlPanels() { for p in panelList { p.refresh() }} func checkAllWidgetIndices() { for i in 0 ..< NUMPANELS { for j in 0 ..< NUMAXES { if !vc.widget.isLegalControlPanelIndex(getPanelWidgetIndex(i,j)) { setPanelWidgetIndex(i,j,0) } } } } } //MARK: - // save encoded picker selection for X or Y axis of specified panel func setPanelWidgetIndex(_ panelIndex:Int, _ axisIndex:Int, _ value:Int) { switch panelIndex * 2 + axisIndex { case 0 : vc.control.panel00 = Int32(value) case 1 : vc.control.panel01 = Int32(value) case 2 : vc.control.panel10 = Int32(value) case 3 : vc.control.panel11 = Int32(value) case 4 : vc.control.panel20 = Int32(value) case 5 : vc.control.panel21 = Int32(value) case 6 : vc.control.panel30 = Int32(value) case 7 : vc.control.panel31 = Int32(value) default : break } } // retrieve encoded picker selection from X or Y axis of specified panel func getPanelWidgetIndex(_ panelIndex:Int, _ axisIndex:Int) -> Int { var index = Int() switch panelIndex * 2 + axisIndex { case 0 : index = Int(vc.control.panel00) case 1 : index = Int(vc.control.panel01) case 2 : index = Int(vc.control.panel10) case 3 : index = Int(vc.control.panel11) case 4 : index = Int(vc.control.panel20) case 5 : index = Int(vc.control.panel21) case 6 : index = Int(vc.control.panel30) case 7 : index = Int(vc.control.panel31) default : index = 0 } return index } //MARK: - var selectedRow = Int() var selectedWindow = Int() func decodeSelectionIndex(_ selection:Int) { selectedRow = decodePickerSelection(selection).0 selectedWindow = decodePickerSelection(selection).1 if (selectedWindow == 0) && vc.control.isStereo { selectedRow += 1 } // 'Parallax' widget offset } //MARK: - //MARK: - class ControlPanelView: NSView { var panelID = Int() var ratio:[Float] = [ 0,0 ] func refresh() { for i in 0 ..< NUMAXES { decodeSelectionIndex(getPanelWidgetIndex(panelID,i)) ratio[i] = winHandler.widgetPointer(selectedWindow).data[selectedRow].getRatio() } setNeedsDisplay(self.bounds) } override func keyDown(with event: NSEvent) { switch event.charactersIgnoringModifiers!.uppercased() { case " " : spaceKeyDown = true default : vc.keyDown(with: event) } } override func keyUp(with event: NSEvent) { spaceKeyDown = false vc.keyUp(with: event) } var isMouseDown:Bool = false var spaceKeyDown:Bool = false var xCoord = Float() var oldXCoord = Float() var yCoord = Float() var oldYCoord = Float() func clamp(_ value:Float, _ min:Float, _ max:Float) -> Float { if value < min { return min } if value > max { return max } return value } override func mouseDown(with event: NSEvent) { let pt:NSPoint = event.locationInWindow if !isMouseDown { for i in 0 ..< NUMPANELS { let p = panelRect[i] if pt.x >= p.minX && pt.x < p.minX + CGFloat(PanelSize) && pt.y <= p.minY && pt.y > p.minY - CGFloat(PanelSize) { panelIndex = i isMouseDown = true } } } if isMouseDown { let pSize = Float(PanelSize) let p = panelRect[panelIndex] decodeSelectionIndex(getPanelWidgetIndex(panelIndex,0)) oldXCoord = xCoord xCoord = Float(pt.x - p.minX) if spaceKeyDown { xCoord = oldXCoord + (xCoord - oldXCoord) * 0.01 } xCoord = clamp(xCoord,0,pSize) winHandler.widgetPointer(selectedWindow).data[selectedRow].setRatio(xCoord / pSize) decodeSelectionIndex(getPanelWidgetIndex(panelIndex,1)) oldYCoord = yCoord yCoord = Float(p.minY - pt.y) if spaceKeyDown { yCoord = oldYCoord + (yCoord - oldYCoord) * 0.01 } yCoord = clamp(yCoord,0,pSize) winHandler.widgetPointer(selectedWindow).data[selectedRow].setRatio(yCoord / pSize) winHandler.refreshWidgetsAndImage() refresh() } } override func mouseDragged(with event: NSEvent) { mouseDown(with:event) } override func mouseUp(with event: NSEvent) { isMouseDown = false } override func draw(_ rect: NSRect) { let cr = (panelID == panelIndex) ? CGFloat(0.3) : CGFloat(0.1) let c = CGFloat(0.1) NSColor(red:cr, green:c, blue:c, alpha:1).set() NSBezierPath(rect:bounds).fill() func legend(_ index:Int) { let axisString:[String] = [ "X","Y" ] let tableString:[String] = [ "Main","Light","Color" ] var str = String() let encodedSelection = getPanelWidgetIndex(panelID,index) var r = decodePickerSelection(encodedSelection).0 let w = decodePickerSelection(encodedSelection).1 if w == 0 && vc.control.isStereo { r += 1 } // 'parallax' widget offset str = String(format:"%@: %@ %@",axisString[index],tableString[w],winHandler.stringForRow(w,r)) drawText(5,5 + CGFloat(index) * 16,str,12,.white,0) } for i in 0 ..< NUMAXES { legend(i) } let r = NSRect(x:CGFloat(ratio[0] * Float(PanelSize) - 5), y:CGFloat(ratio[1] * Float(PanelSize) - 5), width:CGFloat(10), height:CGFloat(10)) drawFilledCircle(r,.red) } func drawText(_ x:CGFloat, _ y:CGFloat, _ txt:String, _ fontSize:Int, _ color:NSColor, _ justifyCode:Int) { // 0,1,2 = left,center,right let a1 = NSMutableAttributedString( string: txt, attributes: [ kCTFontAttributeName as NSAttributedString.Key:NSFont(name: "Helvetica", size: CGFloat(fontSize))!, NSAttributedString.Key.foregroundColor : color ]) var cx = CGFloat(x) let size = a1.size() switch justifyCode { case 1 : cx -= size.width/2 case 2 : cx -= size.width default : break } a1.draw(at: CGPoint(x:cx, y:CGFloat(y))) } func drawFilledCircle(_ rect:NSRect, _ color:NSColor) { let context = NSGraphicsContext.current?.cgContext let path = CGMutablePath() path.addEllipse(in: rect) context?.setFillColor(color.cgColor) context?.addPath(path) context?.drawPath(using:.fill) } override var isFlipped: Bool { return true } override var acceptsFirstResponder: Bool { return true } }
// // SearchExperimentsOperation.swift // Experiment Go // // Created by luojie on 9/27/15. // Copyright © 2015 LuoJie. All rights reserved. // import Foundation import CloudKit class SearchExperimentsOperation: GetObjectsWithCreatorUserOperation { convenience init(searchText: String?) { self.init(type: .Refresh(CKExperiment.QueryForSearchText(searchText))) } }
// // RepositoryResponse.swift // // Created by Augusto Cesar do Nascimento dos Reis on 13/12/20 // Copyright (c) ACNR. All rights reserved. // import Foundation struct RepositoryResponse: Decodable { let items: [ItemResponse]? let incompleteResults: Bool? let totalCount: Int? enum CodingKeys: String, CodingKey { case items case incompleteResults = "incomplete_results" case totalCount = "total_count" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) items = try container.decodeIfPresent([ItemResponse].self, forKey: .items) incompleteResults = try container.decodeIfPresent(Bool.self, forKey: .incompleteResults) totalCount = try container.decodeIfPresent(Int.self, forKey: .totalCount) } }
// // FCNetworkConfiguration.swift // icar // // Created by 陈琪 on 2019/12/3. // Copyright © 2019 Carisok. All rights reserved. // import Foundation struct Configs { struct Network { static let useStaging = true // 测试模式 static let loggingEnabled = false // 请求日志输出 static let environment: Environment = .test static let apiversion = "1.0" // API版本 static let loadPageCount = 20 // 加载数据条数 } struct Path { static let Documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] static let Tmp = NSTemporaryDirectory() } } /** * 服务器环境配置信息 */ enum Environment { /** 正式环境*/ case formal /** 灰度*/ case grey /** 测试环境*/ case test var baseUrl: String { switch self { case .formal: return "" case .grey: return "" case .test: return "http://baidu.com" } } }
// // ProductCell.swift // FoodicsAssesment // // Created by mohamed gamal on 12/17/20. // import UIKit class ProductCell: UICollectionViewCell { //MARK:- OutLets @IBOutlet weak var productImage: UIImageView! @IBOutlet weak var productTitle: UILabel! @IBOutlet weak var continerView: UIView! @IBOutlet weak var priceLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() self.continerView.layer.cornerRadius = 8 self.continerView.layer.borderWidth = 3 self.continerView.layer.borderColor = UIColor.black.cgColor } func configureProducts(products: ProductModel) { productImage.setImage(with: products.image ?? "") productTitle.text = products.name ?? "" priceLabel.text = "Price: \(products.price ?? 0.0)" } }
// // Model.swift // E-card // // Created by EthanLin on 2018/2/6. // Copyright © 2018年 EthanLin. All rights reserved. // import Foundation
// // GameScene.swift // ShootingGallery // // Created by Juan Francisco Dorado Torres on 22/09/19. // Copyright © 2019 Juan Francisco Dorado Torres. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { // MARK: - Properties var scoreLabel: SKLabelNode! var shotsNode: SKSpriteNode! var gameTimer: Timer? var appearedEnemies = 0 var velocityEnemies: Double = 150 var numOfShots = 3 var score = 0 { didSet { scoreLabel.text = "Score: \(score)" } } // MARK: - Game lifecycle override func didMove(to view: SKView) { // add background music let backgroundSound = SKAudioNode(fileNamed: "bg.mp3") self.addChild(backgroundSound) // add background let woodBackground = SKSpriteNode(imageNamed: "wood-background") woodBackground.size = self.frame.size woodBackground.position = CGPoint(x: 512, y: 384) woodBackground.zPosition = -2 addChild(woodBackground) // add grass background let grassBackground = SKSpriteNode(imageNamed: "grass-trees") grassBackground.size = resized(grassBackground.size, expectedWidth: self.frame.size.width) grassBackground.position = CGPoint(x: 512, y: 384) grassBackground.zPosition = -1 addChild(grassBackground) // add water let waterBackground = SKSpriteNode(imageNamed: "water-bg") waterBackground.size = resized(waterBackground.size, expectedWidth: self.frame.size.width) waterBackground.position = CGPoint(x: 512, y: 240) waterBackground.zPosition = 1 addChild(waterBackground) let waterForeground = SKSpriteNode(imageNamed: "water-fg") waterForeground.size = resized(waterBackground.size, expectedWidth: self.frame.size.width) waterForeground.position = CGPoint(x: 512, y: 170) waterForeground.zPosition = 3 addChild(waterForeground) // add curtains let curtainsForeground = SKSpriteNode(imageNamed: "curtains") curtainsForeground.size = self.frame.size curtainsForeground.position = CGPoint(x: 512, y: 384) curtainsForeground.zPosition = 5 addChild(curtainsForeground) // add score scoreLabel = SKLabelNode(fontNamed: "Chalkduster") scoreLabel.text = "Score: 0" scoreLabel.horizontalAlignmentMode = .right scoreLabel.position = CGPoint(x: 850, y: 60) scoreLabel.zPosition = 5 addChild(scoreLabel) // add shots numOfShots = 3 print("shots\(numOfShots)") shotsNode = SKSpriteNode(imageNamed: "shots\(numOfShots)") shotsNode.size = resized(shotsNode.size, expectedWidth: shotsNode.size.width + 50) shotsNode.position = CGPoint(x: 250, y: 75) shotsNode.zPosition = 5 addChild(shotsNode) physicsWorld.gravity = CGVector(dx: 0, dy: 0) // the gravity of our physics world is empty (because it is the space) gameTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(createDuck), userInfo: nil, repeats: true) } override func update(_ currentTime: TimeInterval) { for node in children { // check each node if node.position.x < -300 || node.position.x > 1324 { // if the node is out of screen node.removeFromParent() // remove the node from the parent } } } // MARK: - Touches events override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let location = touch.location(in: self) let tappedNodes = nodes(at: location) guard numOfShots > 0 else { run(SKAction.playSoundFileNamed("empty.wav", waitForCompletion: false)) return } for node in tappedNodes { // SpriteNode -> ShotTarget -> Screen guard let shotTarget = node.parent as? ShotTarget else { continue } shotTarget.hit() numOfShots -= 1 shotsNode.texture = SKTexture(imageNamed: "shots\(numOfShots)") run(SKAction.playSoundFileNamed("shot.wav", waitForCompletion: false)) if node.name == "good" { print("good target") score += 5 } else if node.name == "bad" { print("bad target") //whackSlot.charNode.xScale = 0.85 //whackSlot.charNode.yScale = 0.85 score += 1 } } } // MARK: - Methods func resized(_ size: CGSize, expectedWidth: CGFloat) -> CGSize { let oldWidth = size.width let scaleFactor = expectedWidth / oldWidth let newHeight = size.height * scaleFactor let newWidth = oldWidth * scaleFactor return CGSize(width: newWidth, height: newHeight) } @objc func createDuck() { print(velocityEnemies) let shotTarget = ShotTarget() let duckPositions: [ShotTarget.RowPosition] = [.bottom, .middle, .front] let selectedPosition = duckPositions.shuffled()[0] shotTarget.configure(at: selectedPosition) addChild(shotTarget) // shotTarget move shotTarget.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 115, height: 240), center: CGPoint(x: 0, y: 50)) shotTarget.physicsBody?.collisionBitMask = 0 shotTarget.physicsBody?.categoryBitMask = 0 shotTarget.physicsBody?.velocity = CGVector(dx: selectedPosition == .middle ? (velocityEnemies * -1) : velocityEnemies, dy: 0) // make it move horizontal way shotTarget.physicsBody?.angularVelocity = 5 // give an angular velocity to make the enemy rotate shotTarget.physicsBody?.linearDamping = 0 // this avoids to reduce the linear velocity during the moving time shotTarget.physicsBody?.angularVelocity = 0 // this avoids to reduce the rotation during the moving time appearedEnemies += 1 if appearedEnemies == 5 { appearedEnemies = 0 velocityEnemies *= 1.2 if velocityEnemies > 1000 { gameTimer?.invalidate() let gameOver = SKSpriteNode(imageNamed: "gameOver") // create a new node with the game over image gameOver.position = CGPoint(x: 512, y: 384) // add on the center of the screen gameOver.zPosition = 1 // put the node over eveything addChild(gameOver) // add it to the screen } } } func reloadBullets() { numOfShots = 3 shotsNode.texture = SKTexture(imageNamed: "shots\(numOfShots)") run(SKAction.playSoundFileNamed("reload.wav", waitForCompletion: false)) } }
// // LeaveFeedbackActivityTableCell.swift // MyLoqta // // Created by Kirti on 9/7/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit protocol LeaveFeedbackActivityTableCellDelegate: class { func leaveFeedbackTapped(cell: LeaveFeedbackActivityTableCell) func replyTapped(cell: LeaveFeedbackActivityTableCell) } class LeaveFeedbackActivityTableCell: BaseTableViewCell, NibLoadableView, ReusableView { //MARK:- IBOutlets @IBOutlet weak var viewShadow: UIView! @IBOutlet weak var viewContainer: UIView! @IBOutlet weak var imgViewProduct: UIImageView! @IBOutlet weak var lblDescription: UILabel! @IBOutlet weak var btnFeedback: AVButton! //ConstraintOutlets @IBOutlet weak var cnstrntBtnFeedbackWidth: NSLayoutConstraint! //MARK: - Variables weak var delegate: LeaveFeedbackActivityTableCellDelegate? var isReply = false override func awakeFromNib() { super.awakeFromNib() self.setupView() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } //MARK: - Private Methods private func setupView() { self.imgViewProduct.roundCorners(4.0) self.configureViewForShadow() if isReply { self.btnFeedback.localizeKey = "Reply".localize() self.cnstrntBtnFeedbackWidth.constant = 70.0 } else { self.btnFeedback.localizeKey = "Leave feedback".localize() self.cnstrntBtnFeedbackWidth.constant = 115.0 } } private func configureViewForShadow() { self.viewShadow.layer.shadowColor = UIColor.gray.cgColor self.viewShadow.layer.shadowOffset = CGSize(width: 0, height: 0) self.viewShadow.layer.shadowOpacity = 0.2 self.viewShadow.layer.shadowRadius = 5.0 self.viewShadow.layer.cornerRadius = 8.0 self.viewContainer.layer.cornerRadius = 8.0 } //MARK:- IBActions @IBAction func tapBtnLeaveFeedback(_ sender: AVButton) { if let delegate = delegate { if isReply { delegate.replyTapped(cell: self) } else { delegate.leaveFeedbackTapped(cell: self) } } } //MARK:- Public Methods func configureCellForSellerBuyerLeavesFeedback(activity: Activity) { if let itemName = activity.itemName, let buyerName = activity.buyerName { let yourItem = "Your item".localize() let hasSold = "has been sold to".localize() let finalText = yourItem + " \(itemName) " + hasSold + " \(buyerName)." self.lblDescription.text = finalText } } func configureCellForSellerBuyerAsksQuestion(activity: Activity) { if let buyerName = activity.buyerName, let question = activity.question { let commentedOn = "commented on".localize() let finalText = buyerName + " \(commentedOn): " + question self.lblDescription.text = finalText } } }
// // ForecastView.swift // SwiftWeatherTemplate // // Created by Florian on 18.07.20. // Copyright © 2020 Florian. All rights reserved. // import UIKit import SnapKit final class ForecastView: UIView { let tableView = UITableView() convenience init() { self.init(frame: .zero) tableView.adoptBackgroundMode() addSubview(tableView) makeConstraints() } } // MARK: - ViewProtocol extension ForecastView: ViewProtocol { func makeConstraints() { tableView.snp.makeConstraints { $0.left.top.right.bottom.equalToSuperview() } } }
// // main.swift // h.w.f // // Created by Ghada Fahad on 15/03/1443 AH. // import Foundation print("Hello, World!")
// // ChatMessage.swift // Finder // // Created by Tai on 6/18/20. // Copyright © 2020 DJay. All rights reserved. // import Foundation //import FirebaseDatabase class ChatMessage { var id = "" var senderId = "" var receiverId = "" var message = "" var imgURL = "" var isRead = true var createdAt = dateToString(date: Date()) private let ref = Database.database().reference() init(id: String, senderId: String, receiverId: String, message: String, imgURL: String = "") { self.id = id self.senderId = senderId self.receiverId = receiverId self.message = message self.imgURL = imgURL self.isRead = false } init(data: [String : Any]) { update(data: data) } private func update(data: [String : Any]) { self.id = (data[ct_id] as? String) ?? "" self.senderId = (data[ct_senderId] as? String) ?? "" self.receiverId = (data[ct_receiverId] as? String) ?? "" self.message = (data[ct_message] as? String) ?? "" self.imgURL = (data[ct_imgURL] as? String) ?? "" self.isRead = (data[ct_isRead] as? Bool) ?? true self.createdAt = (data[ct_createdAt] as? String) ?? dateToString(date: Date()) } func asDictionary() -> [String : Any] { return [ct_id : self.id, ct_senderId : self.senderId, ct_receiverId : self.receiverId, ct_message : self.message, ct_imgURL : self.imgURL, ct_isRead : self.isRead, ct_createdAt : self.createdAt] } func updateOnServer(chatId: String) { ref.child("chats/\(chatId)/\(id)").setValue(self.asDictionary()) } }
// // PreparePlayerViewController.swift // Avgle // // Created by ChenZheng-Yang on 2018/1/7. // Copyright © 2018年 ChenCheng-Yang. All rights reserved. // import UIKit import BMPlayer import SafariServices import Firebase import SVProgressHUD class PreparePlayerViewController: BaseViewController { // MARK: - Property /// 是否從收藏進來的,此頁面可由主頁及我的收藏兩個地方進來,分不同模式,在likeBtn有不同呈現 public var isFromCollection: Bool = false /// 若需要刪除會有key public var dataKey: String = "" var video: VideoModel? { didSet { let url = URL(string: (video!.preview_video_url?.urlEncoded())!)! let asset = BMPlayerResource(url: url, name: video!.title!) player.seek(30) player.setVideo(resource: asset) } } var ref: DatabaseReference! fileprivate lazy var player: BMPlayer = { let player = BMPlayer(customControlView: BMPlayerCustomControlView()) player.delegate = self return player }() fileprivate lazy var blurEffectView: UIVisualEffectView = { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.view.bounds return blurEffectView }() fileprivate lazy var backgroundImageView: UIImageView = { let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)) imageView.image = UIImage(named: "BG_3") imageView.addSubview(blurEffectView) return imageView }() fileprivate lazy var cancelBtn: UIButton = { let btn = UIButton(type: .custom) btn.backgroundColor = UIColor.clear btn.layer.borderWidth = 1 btn.layer.borderColor = UIColor.white.cgColor btn.setTitle(NSLocalizedString("Cancel", comment: "") , for: .normal) btn.setTitleColor(.white, for: .normal) btn.addTarget(self, action: #selector(cancelAction), for: .touchUpInside) return btn }() fileprivate lazy var watchTheVideoBtn: UIButton = { let btn = UIButton(type: .custom) btn.layer.borderWidth = 1 btn.layer.borderColor = UIColor.white.cgColor btn.setTitle(NSLocalizedString("Watch the video", comment: ""), for: .normal) btn.setTitleColor(.white, for: .normal) btn.addTarget(self, action: #selector(watchFullVideo), for: .touchUpInside) return btn }() fileprivate lazy var likeBtn: UIButton = { let btn = UIButton(type: .custom) btn.layer.borderWidth = 1 btn.layer.borderColor = UIColor.white.cgColor btn.setTitle(NSLocalizedString(isFromCollection ? "Delete The Video":"Add My Collection", comment: ""), for: .normal) btn.setTitleColor(.white, for: .normal) btn.addTarget(self, action: #selector(likeAction(btn:)), for: .touchUpInside) return btn }() // MARK: - ViewController Life Cycle override func viewDidLoad() { super.viewDidLoad() //Animation let scale = CGAffineTransform(scaleX: 0.0, y: 0.0) let translate = CGAffineTransform(translationX: 0, y: 500) self.likeBtn.transform = scale.concatenating(translate) self.watchTheVideoBtn.transform = scale.concatenating(translate) self.cancelBtn.transform = scale.concatenating(translate) self.player.transform = scale.concatenating(translate) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources t hat can be recreated. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //Animation UIButton.animate(withDuration: 0.5, delay: 0.0, options: [], animations: { self.likeBtn.transform = CGAffineTransform.identity self.watchTheVideoBtn.transform = CGAffineTransform.identity self.cancelBtn.transform = CGAffineTransform.identity self.player.transform = CGAffineTransform.identity }, completion: nil) } // MARK : - Setup UI override func setUI() { super.setUI() view.addSubview(backgroundImageView) view.addSubview(cancelBtn) view.addSubview(watchTheVideoBtn) view.addSubview(player) view.addSubview(likeBtn) resetPlayerManager() setNeedsLayout() setData() } func setData() { ref = Database.database().reference() } // MARK: - Button Action @objc func cancelAction() { UIApplication.shared.setStatusBarHidden(false, with: .fade) dismiss(animated: true, completion: nil) } @objc func watchFullVideo() { let urlStr: String = self.video!.embedded_url!.urlEncoded() let safariVC = SFSafariViewController(url: URL(string: urlStr)!) safariVC.delegate = self self.present(safariVC, animated: true, completion: nil) } @objc func likeAction(btn: UIButton) { btn.isEnabled = false SVProgressHUD.showProgress(2.0, status: NSLocalizedString("Loading...", comment: "")) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) { SVProgressHUD.dismiss() btn.setTitle(NSLocalizedString(self.isFromCollection ? "Successfully deleted":"Added successfully", comment: ""), for: .normal) } // 節點值 let childKey: String = (Auth.auth().currentUser?.displayName)! + "_" + (Auth.auth().currentUser?.uid)! if self.isFromCollection { // 刪除 ref.child(childKey).child(dataKey).removeValue() } else { // 新增 // 獲得現在日期 let dateFormatterPrint = DateFormatter() dateFormatterPrint.dateFormat = "yyyyMMdd_hh:mm:ss" let nowDate: String = dateFormatterPrint.string(from: Date()) let dataDic: [String : Any] = ["title": video!.title!, "duration": video!.duration!, "likes": video!.likes!, "dislikes": video!.dislikes!, "embedded_url": video!.embedded_url!, "preview_url": video!.preview_url!, "preview_video_url": video!.preview_video_url!] // 上傳Database ref.child(childKey).child(nowDate).setValue(dataDic) } } // MARK: - Player func resetPlayerManager() { BMPlayerConf.shouldAutoPlay = true BMPlayerConf.tintColor = UIColor.white BMPlayerConf.topBarShowInCase = .none } // MARK: - Auto Layout func setNeedsLayout() { cancelBtn.snp.makeConstraints { (make) in make.bottom.equalTo(-30 * proportion).priority(1000) make.leading.equalTo(50) make.trailing.equalTo(-50) make.height.equalTo(50) } watchTheVideoBtn.snp.makeConstraints { (make) in make.width.height.centerX.equalTo(cancelBtn) make.bottom.equalTo(cancelBtn.snp.top).offset(-30) } likeBtn.snp.makeConstraints { (make) in make.width.height.centerX.equalTo(cancelBtn) make.bottom.equalTo(watchTheVideoBtn.snp.top).offset(-30) } player.snp.makeConstraints { (make) in make.top.equalTo(view.snp.top) make.left.equalTo(view.snp.left) make.right.equalTo(view.snp.right) make.height.equalTo(view.snp.width).multipliedBy(9.0/16.0).priority(500) } } // MARK: Device Orientation override var shouldAutorotate: Bool { return true } } extension PreparePlayerViewController: BMPlayerDelegate { func bmPlayer(player: BMPlayer, playerOrientChanged isFullscreen: Bool) { player.snp.remakeConstraints { [weak self](make) in make.top.equalTo(view.snp.top) make.left.equalTo(view.snp.left) make.right.equalTo(view.snp.right) if isFullscreen { self?.likeBtn.isHidden = true make.bottom.equalTo(view.snp.bottom) } else { self?.likeBtn.isHidden = false make.height.equalTo(view.snp.width).multipliedBy(9.0/16.0).priority(500) } } } // Call back when playing state changed, use to detect is playing or not func bmPlayer(player: BMPlayer, playerIsPlaying playing: Bool) { print("| BMPlayerDelegate | playerIsPlaying | playing - \(playing)") } // Call back when playing state changed, use to detect specefic state like buffering, bufferfinished func bmPlayer(player: BMPlayer, playerStateDidChange state: BMPlayerState) { print("| BMPlayerDelegate | playerStateDidChange | state - \(state)") } // Call back when play time change func bmPlayer(player: BMPlayer, playTimeDidChange currentTime: TimeInterval, totalTime: TimeInterval) { // print("| BMPlayerDelegate | playTimeDidChange | \(currentTime) of \(totalTime)") } // Call back when the video loaded duration changed func bmPlayer(player: BMPlayer, loadedTimeDidChange loadedDuration: TimeInterval, totalDuration: TimeInterval) { // print("| BMPlayerDelegate | loadedTimeDidChange | \(loadedDuration) of \(totalDuration)") } } extension PreparePlayerViewController: SFSafariViewControllerDelegate { func safariViewControllerDidFinish(_ controller: SFSafariViewController) { controller.dismiss(animated: true, completion: nil) } }
// // UserTeaser.swift // TinderApp // // Created by Serg on 13.02.2020. // Copyright © 2020 Sergey Gladkiy. All rights reserved. // import Foundation struct TinderUserTeaser: Decodable { let type: String? let string: String } struct UserJob: Decodable { let company: CompanyJob? let title: TitleJob? } struct UserSchool: Decodable { let name: String? } struct CompanyJob: Decodable { let name: String } struct TitleJob: Decodable { let name: String }
// // GoogleSignINView.swift // caffinho-iOS // // Created by Rafael M. A. da Silva on 8/3/16. // Copyright © 2016 venturus. All rights reserved. // import Foundation import UIKit public class GoogleSignINView: UIView { var contentView: GoogleSignINContentView! public override func awakeFromNib() { super.awakeFromNib() contentView = GoogleSignINContentView.loadFromNibNamed(NibNames.googleSignINContentView) as! GoogleSignINContentView self.addSubview(contentView) } }
// // UIColor+Extensions.swift // InAppNotification // // Created by Arnold Plakolli on 5/20/18. // Copyright © 2018 Arnold Plakolli. All rights reserved. // import Foundation extension UIColor { convenience init(r: CGFloat, g: CGFloat, b: CGFloat) { self.init(r: r, g: g, b: b, a: 255) } convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { self.init(red: r/255, green: g/255, blue: b/255, alpha: a/255) } }
import GRDB class AccountRecordStorage { private let dbPool: DatabasePool init(dbPool: DatabasePool) { self.dbPool = dbPool } } extension AccountRecordStorage { var all: [AccountRecord] { try! dbPool.read { db in try AccountRecord.fetchAll(db) } } func save(record: AccountRecord) { _ = try! dbPool.write { db in try record.insert(db) } } func delete(by id: String) { _ = try! dbPool.write { db in try AccountRecord.filter(AccountRecord.Columns.id == id).deleteAll(db) } } func clear() { _ = try! dbPool.write { db in try AccountRecord.deleteAll(db) } } }
// // bigImageViewController.swift // SlideshowApp // // Created by まく on 2018/07/15. // Copyright © 2018年 sshiono. All rights reserved. // import UIKit class bigImageViewController: UIViewController { @IBOutlet weak var bigImageParts: UIImageView! var firstValue:Int = 0 let imageList = ["cat.jpg", "dog.jpg", "fox.jpg"] override func viewDidLoad() { super.viewDidLoad() bigImageParts.image = UIImage(named:imageList[firstValue]) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // SecondScreen.swift // bleedApp // // Created by Peter Ostiguy on 11/19/16. // Copyright © 2016 Peter Ostiguy. All rights reserved. // import UIKit class SecondScreen: UIViewController, GIDSignInUIDelegate { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func signOutButton(_ sender: Any) { GIDSignIn.sharedInstance().signOut() print("signed out") } }
// // AllBreedsList.swift // Doggy_App // // Created by User on 19/06/2019. // Copyright © 2019 Maximkapitonov. All rights reserved. // import Foundation struct AllBreedsList: Codable { var status: String? var message: [String: [String]]? }
// // ViewController.swift // Foodie COPY - TRY DUMB SHIT OUT HERE // // Created by Justine Breuch on 8/30/15. // Copyright (c) 2015 Justine Breuch. All rights reserved. // import UIKit import Parse import Bolts class ViewController: UIViewController { // override func viewDidLoad() { // super.viewDidLoad() // // Do any additional setup after loading the view, typically from a nib. // get_place() // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } // // func get_place() -> Void { // // version needs to be yyyymmdd format // var version = "20150705" // // // latitude and longitude // var ll = "40.0522776,-75.2913171" // // // standard base // let url = NSURL(string: "https://api.foursquare.com/v2/venues/explore?ll=\(ll)&section=food&openNow=1&client_id=\(foursquare_client_id)&client_secret=\(foursquare_client_secret)&v=\(version)") // // var data = NSData(contentsOfURL: url!) // // let jsonError: NSError? // // if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary { // // let response = json["response"] as! NSDictionary // let groups = response["groups"] as! NSArray // let recommended = groups[0] as! NSDictionary // let items = recommended["items"] as! NSArray // // let item = items[0] as! NSDictionary // // // venue is one restaurant // let venue: NSDictionary = (item["venue"] as? NSDictionary)! // var checkpoint: String = venue["id"] as! String // // // check if it already exists // var query = PFQuery(className:"Place") // // query.whereKey("foursquare_id", equalTo: "\(checkpoint)") // query.findObjectsInBackgroundWithBlock { // (objects: [AnyObject]?, error: NSError?) -> Void in // // if error == nil { // // The find succeeded. // println("Retrieved \(objects!.count) places.") // // // if (objects!.count == 0) { // // save new entries // println("creating new object") // var place = PFObject(className:"Place") // // place["foursquare_id"] = venue["id"] // // place["name"] = venue["name"] // println(venue["name"]) // // if (venue["url"] != nil) { // place["url"] = venue["url"] // } // // if (venue["rating"] != nil) { // place["rating"] = venue["rating"] // } // // if (venue["contact"] != nil) { // let contact = venue["contact"] as! NSDictionary // if (contact["phone"] != nil && contact["formattedPhone"] != nil) { // place["phone"] = contact["phone"] // place["formatted_phone"] = contact["formattedPhone"] // } // // } // // if (venue["location"] != nil) { // let location = venue["location"] as! NSDictionary // // if (location["formattedAddress"] != nil) { // let address:Array<String> = (location["formattedAddress"] as? Array<String>)! // place["formatted_address"] = join(" ", address) as String // // } // // } // place["instagram_id"] = self.getInstagramId(checkpoint) // self.nameLabel.text = place["name"] as? String // self.getInstagramData(place["instagram_id"] as! String) // // // place.saveInBackgroundWithBlock { // (success: Bool, error: NSError?) -> Void in // if (success) { // println("Success!") // } else { // println("There was a problem!") // } // } // // } else { // // Do something with the found objects // println("Looking in Parse") // if let objects = objects as? [PFObject] { // for object in objects { // println(object["name"]) // self.nameLabel.text = object["name"] as? String // self.getInstagramData(object["instagram_id"] as! String) // } // } // } // // } else { // // Log details of the failure // println("Error: \(error!) \(error!.userInfo!)") // // } // } // // } // // } // // func getAPIdata() -> Void { // // // version needs to be yyyymmdd format // var version = "20150705" // // // latitude and longitude // var ll = "40.7,-74" // // // standard base // let url = NSURL(string: "https://api.foursquare.com/v2/venues/explore?ll=\(ll)&section=food&openNow=1&client_id=\(foursquare_client_id)&client_secret=\(foursquare_client_secret)&v=\(version)") // // var data = NSData(contentsOfURL: url!) // // let jsonError: NSError? // // if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary { // // let response = json["response"] as! NSDictionary // let groups = response["groups"] as! NSArray // let recommended = groups[0] as! NSDictionary // let items = recommended["items"] as! NSArray // // for item in items { // // venue is one restaurant // let venue: NSDictionary = (item["venue"] as? NSDictionary)! // var checkpoint: String = venue["id"] as! String // // // check if it already exists // var query = PFQuery(className:"Place") // // query.whereKey("foursquare_id", equalTo: "\(checkpoint)") // query.findObjectsInBackgroundWithBlock { // (objects: [AnyObject]?, error: NSError?) -> Void in // // if error == nil { // // The find succeeded. // println("Retrieved \(objects!.count) places.") // //// // Do something with the found objects //// if let objects = objects as? [PFObject] { //// for object in objects { //// println(object["name"]) //// } //// } // // if (objects!.count == 0) { // // save new entries // println("creating new object") // var place = PFObject(className:"Place") // // place["foursquare_id"] = venue["id"] // // place["name"] = venue["name"] // // if (venue["url"] != nil) { // place["url"] = venue["url"] // } // // if (venue["rating"] != nil) { // place["rating"] = venue["rating"] // } // // if (venue["contact"] != nil) { // let contact = venue["contact"] as! NSDictionary // if (contact["phone"] != nil && contact["formattedPhone"] != nil) { // place["phone"] = contact["phone"] // place["formatted_phone"] = contact["formattedPhone"] // } // // } // // if (venue["location"] != nil) { // let location = venue["location"] as! NSDictionary // // if (location["formattedAddress"] != nil) { // let address:Array<String> = (location["formattedAddress"] as? Array<String>)! // place["formatted_address"] = join(" ", address) as String // // } // // } // place["instagram_id"] = self.getInstagramId(checkpoint) // // place.saveInBackgroundWithBlock { // (success: Bool, error: NSError?) -> Void in // if (success) { // println("Success!") // } else { // println("There was a problem!") // } // } // // } // // } else { // // Log details of the failure // println("Error: \(error!) \(error!.userInfo!)") // // // } // } // } // } // } // // func getInstagramId(checkpoint:String) -> String? { // // // standard base // let url = NSURL(string: "https://api.instagram.com/v1/locations/search?foursquare_v2_id=\(checkpoint)&access_token=\(instagram_access_token)") // // var data = NSData(contentsOfURL: url!) // // // Create another error optional // var jsonerror:NSError? // // if let json: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &jsonerror) as? NSDictionary { // // let data = json["data"] as! NSArray // let info = data[0] as! NSDictionary // return info["id"] as! String? // } // // return "" // } // // func getInstagramData(instagram_id:String) -> Void { // // var glanceOfPlaceImageView: UIImageView! // var scrollViewContentSize:CGFloat = 0 // // picturesScrollView.backgroundColor = UIColor.orangeColor() // picturesScrollView.frame = self.view.bounds // picturesScrollView.directionalLockEnabled = true // // if let url = NSURL(string: "https://api.instagram.com/v1/locations/\(instagram_id)/media/recent?access_token=\(instagram_access_token)") { // // var contents = NSData(contentsOfURL: url) // // // Create another error optional // var jsonerror:NSError? // // if let json: AnyObject! = NSJSONSerialization.JSONObjectWithData(contents!, options: NSJSONReadingOptions.MutableContainers, error: &jsonerror) as? NSDictionary { // // let instas = json["data"] as! NSArray // // for insta in instas { // // let pictures = insta["images"] as! NSDictionary! // let standard_res = pictures["standard_resolution"] as! NSDictionary! // // let url = NSURL(string: standard_res["url"] as! String!) // let data = NSData(contentsOfURL: url!) // // if data != nil { // // glanceOfPlaceImageView = UIImageView(image: UIImage(data:data!)) // glanceOfPlaceImageView.frame.size.height = 400 // glanceOfPlaceImageView.frame.size.width = picturesScrollView.bounds.width // glanceOfPlaceImageView.frame.origin.y = scrollViewContentSize // // scrollViewContentSize += glanceOfPlaceImageView.bounds.height // // picturesScrollView.addSubview(glanceOfPlaceImageView) // println(scrollViewContentSize) // // } // // picturesScrollView.contentSize.width = view.bounds.size.width // picturesScrollView.contentSize.height = scrollViewContentSize // picturesScrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight // // view.addSubview(picturesScrollView) // // } // // } // } // } }
// // MyAccCSViewController.swift // YumaApp // // Created by Yuma Usa on 2018-02-15. // Copyright © 2018 Yuma Usa. All rights reserved. // import UIKit class MyAccCSViewController: UIViewController { @IBOutlet weak var navBar: UINavigationBar! @IBOutlet weak var navTitle: UINavigationItem! @IBOutlet weak var navClose: UIBarButtonItem! @IBOutlet weak var navHelp: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() // if #available(iOS 11.0, *) { // navBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true // } else { // navBar.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true // } navHelp.title = FontAwesome.questionCircle.rawValue navHelp.setTitleTextAttributes([NSAttributedStringKey.font : R.font.FontAwesomeOfSize(pointSize: 21)], for: .normal) navHelp.setTitleTextAttributes([ NSAttributedStringKey.font : R.font.FontAwesomeOfSize(pointSize: 21) ], for: UIControlState.highlighted) navBar.applyNavigationGradient(colors: [R.color.YumaDRed, R.color.YumaRed], isVertical: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Actions @IBAction func navCloseAct(_ sender: Any) { self.dismiss(animated: false, completion: nil) } @IBAction func navHelpAct(_ sender: Any) { let viewC = Assistance() viewC.array = R.array.help_my_account_credit_slips_guide viewC.title = "\(R.string.CreditSlips.capitalized) \(R.string.help.capitalized)" viewC.modalTransitionStyle = .crossDissolve viewC.modalPresentationStyle = .overCurrentContext self.present(viewC, animated: true, completion: nil) } }
// // EmojiArtDocument.swift // EmojiArt // // Created by Ahmed Albaqawi on 6/27/20. // Copyright © 2020 Ahmed Albaqawi. All rights reserved. // import SwiftUI import Combine //ViewModel class EmojiArtDocument: ObservableObject { private static let untitled = "EmojiArtDocument.Untitled" //we have a bug with property wrapers do not behave will with property observes @Published private var emojiArt: EmojiArt //now we can DECODE JSON we can init with the DECODER we did with init? on model // we need to create the following private var to ensure the sink live past the execution of the init with AnyCancellable? // now we ensure that this lives as long as this ViewModel lives private var autoSaveCancellable: AnyCancellable? private var fetchImageCancellable: AnyCancellable? init() { //this is a failable init so it can return nil so we have to add ?? and set to the empty model (start case) emojiArt = EmojiArt(json: UserDefaults.standard.data(forKey: EmojiArtDocument.untitled)) ?? EmojiArt() //we need to go back and fetch the backgound image, the Document do not store image only url and must fetch again //A new fix for the bug of property wrapers do not behave will with property observes autoSaveCancellable = $emojiArt.sink { emojiArt in UserDefaults.standard.set(emojiArt.json, forKey: EmojiArtDocument.untitled) print("json = \(emojiArt.json?.utf8 ?? "nil")") print("we are in the autoSaveCancellable block") } fetchBackgroundImageData() } //only model fitches images from internet, we must publish to be tracked in ViewModel @Published private(set) var backgroundImage: UIImage? //the model is private so we need to make this read version of emojiArt model //this will return all the emojis in our array // the { } acts like the Get var emojis: [EmojiArt.Emoji] { emojiArt.emojis } static let palette : String = "💻🤪😘😔😡😃🥶😱🥵😎🤩🥳🧀🥨" // MARK: - Intents func addEmoji(_ emoji: String, at location: CGPoint, size: CGFloat) { emojiArt.addEmoji(emoji, x: Int(location.x), y: Int(location.y), size: Int(size)) } //we extedned the Collection a protocol that Array impliments with 1st index matching to be able to control //collection content func moveEmoji(_ emoji: EmojiArt.Emoji, by offset: CGSize) { if let index = emojiArt.emojis.firstIndex(matching: emoji) { emojiArt.emojis[index].x += Int(offset.width) emojiArt.emojis[index].y += Int(offset.height) } } func scaleEmoji(_ emoji: EmojiArt.Emoji, by scale: CGFloat) { if let index = emojiArt.emojis.firstIndex(matching: emoji) { emojiArt.emojis[index].size = Int((CGFloat(emojiArt.emojis[index].size) * scale).rounded(.toNearestOrEven)) } } //change setbackgroundURL to computed var as backgroundURL to provide get and set to use in view, and assess if loading var backgoundURL: URL? { get { emojiArt.backgroundURL } set{ emojiArt.backgroundURL = newValue?.imageURL fetchBackgroundImageData() } } private func fetchBackgroundImageData() { backgroundImage = nil if let url = self.emojiArt.backgroundURL { // Every time there is a new request, cancel the old one fetchImageCancellable?.cancel() // Then make a new one... no need for condetional checking like before //the new publisher way of handling HTTP requests fetchImageCancellable = URLSession.shared.dataTaskPublisher(for: url) //dataTaskPublisher returns a tuple data and failure response .map { //we want to have our own publisher response that maps the data from dataTaskPublisher into UIImage // where we know we want a UIImage for the BackgoundImage data, URLResponse in UIImage(data: data) } //REMEMBER we need to do it on Main Queue as this is updating the backgound of app .receive(on: DispatchQueue.main) //next line is to ensure on sink or subscriber to publisher we do not handle errors .replaceError(with: nil) //we assigned it to our publisher declared above, assign only works if you have never as your error, link here or above on the spinner example .assign(to: \EmojiArtDocument.backgroundImage, on: self) //the previous manual way of handling HTTP requests // //manually go on network of UI thread to get image from netowrk // DispatchQueue.global(qos: .userInitiated).async { // if let imageData = try? Data(contentsOf: url) { // //now this is a problem that will try to update UI on non-main thread // DispatchQueue.main.async { // //to avoid loading more than 1 background check the url used at start of the exec block is same, // // if user drops more than 1 backgound we will not get impacted and cause conflicts // // this prevention allows us to show the latest url selected // if url == self.emojiArt.backgroundURL { // self.backgroundImage = UIImage(data: imageData) // // } // } // } // } } } }
// // CategoryViewController.swift // bundapp // // Created by YinZhang on 14/12/8. // Copyright (c) 2014年 THEBUND. All rights reserved. // import UIKit class CategoryViewController: UIViewController { var key: (String, String, String?, String?, String?, String?, String?, String?, Bool) = ("","",nil,nil,nil,nil,nil,nil, false) @IBOutlet weak var tableView: AsyncTable! var refreshControl: UIRefreshControl? var page = 1 var pageEnd = false override func viewDidLoad() { super.viewDidLoad() // refresh control var refresh = UIRefreshControl() var attr = [NSForegroundColorAttributeName:UIColor.blackColor()] YinCache.sharedInstance.getString(key: "\(self.key.1)_type_last_refresh_time", onSuccess: { string in refresh.attributedTitle = NSAttributedString(string: string, attributes:attr) }, onFailure: { _ in // refresh.attributedTitle = NSAttributedString(string: "上次刷新时间:无", attributes:attr) refresh.attributedTitle = NSAttributedString(string: "下拉刷新", attributes:attr) }) refresh.addTarget(self, action: "refresh", forControlEvents:.ValueChanged) self.refreshControl = refresh self.tableView.insertSubview(refresh, atIndex: 0) var focus = CategoryFocusData() focus.firstImgId = self.key.3 if self.key.8 { focus.secondImgId = self.key.2 } focus.title = self.key.4 focus.link = self.key.5 focus.showLink = self.key.6 focus.clickLink = self.key.7 PostList.sharedInstance.cateList = [] PostList.sharedInstance.appendCategoryList(focus) self.tableView.fetchData = getData self.tableView.selectData = selectData self.tableView.onSwipeUp = swipeUp self.tableView.onSwipeDown = swipeDown self.tableView.loadSegment(nil) } func refresh() { self.refreshControl?.attributedTitle = NSAttributedString(string: "刷啊刷~") self.page = 1 pageEnd = false var first = PostList.sharedInstance.cateList[0] PostList.sharedInstance.cateList = [] PostList.sharedInstance.cateList.append(first) self.tableView.loadSegment() { () -> () in let time = NSDate() let outFormatter = NSDateFormatter() outFormatter.locale = NSLocale(localeIdentifier: "zh_CN") outFormatter.dateFormat = "'上次刷新时间:'MM'月'dd'日 'HH:mm:ss" let last_time = outFormatter.stringFromDate(time) YinCache.sharedInstance.setString(value: last_time, key: "\(self.key.1)_type_last_refresh_time") dispatch_async(dispatch_get_main_queue(), { self.refreshControl?.attributedTitle = NSAttributedString(string: "下拉刷新") self.refreshControl?.endRefreshing() return }) } } var loggedDate: NSDate? func getData(listener:(Bool,[CellData]?) -> ()) { if pageEnd { listener(false,nil) return } // println("get data page:\(self.page)") // PostList.sharedInstance.appendCategoryList(date) let urlstr = "http://www.bundpic.com/app-post?n=10&p=\(self.page++)&c=\(self.key.1)" // println("category:\(urlstr)") YinCache.sharedInstance.getJson(url: urlstr, refresh: true, onSuccess: { data in let postArr = data as Array<AnyObject> let inFormatter = NSDateFormatter() inFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'" inFormatter.timeZone = NSTimeZone(name: "UTC") self.loggedDate == nil if self.loggedDate == nil { let now = NSDate() let cal = NSCalendar.currentCalendar() var com = cal.components(NSCalendarUnit.CalendarUnitYear|NSCalendarUnit.CalendarUnitMonth|NSCalendarUnit.CalendarUnitDay, fromDate: now) com.day += 1 self.loggedDate = cal.dateFromComponents(com) } let outFormatter = NSDateFormatter() outFormatter.locale = NSLocale(localeIdentifier: "zh_CN") outFormatter.dateFormat = "MM'月'd'日 'EEEE" for index in 0..<postArr.count { let item : AnyObject? = postArr[index] let post = item! as Dictionary<String, AnyObject> let id = post["_id"]! as String let title = post["标题"]! as String let image = post["图片链接"] as String? var link:String? = post["链接"] as String? let dateStr = post["发布时间"]! as String var date = inFormatter.dateFromString(dateStr) let showLink:String? = post["出现统计"] as String? let clickLink:String? = post["点击统计"] as String? let pic = post["缩略图"] as? Dictionary<String, AnyObject> var picName : String? = nil if pic != nil { picName = pic!["filename"] as String? } var sourceName: String? if let source = post["来源"] as? Dictionary<String, AnyObject> { if let sName = source["名称"] as String? { var sTime = YTools.getRelativeTime(date!) sourceName = "\(sName) 发表于 \(sTime)" } } var noTime = true if self.loggedDate?.compare(date!) == NSComparisonResult.OrderedDescending { let cal = NSCalendar.currentCalendar() var com = cal.components(NSCalendarUnit.CalendarUnitYear|NSCalendarUnit.CalendarUnitMonth|NSCalendarUnit.CalendarUnitDay, fromDate: date!) self.loggedDate = cal.dateFromComponents(com) var categoryDate = CategoryDateData() categoryDate.date = self.loggedDate categoryDate.text = outFormatter.stringFromDate(self.loggedDate!) PostList.sharedInstance.appendCategoryList(categoryDate) noTime = false } if noTime { var blank = BlankData() PostList.sharedInstance.appendHomeList(blank) } var categoryPost = PostData() categoryPost.title = title categoryPost.clickLink = clickLink categoryPost.source = sourceName categoryPost.link = "http://www.bundpic.com/mpost/\(id)" if link != nil { if let linkUrl : NSURL? = NSURL(string: link!) { if linkUrl != nil && linkUrl?.scheme != nil { categoryPost.link = link } } } if picName != nil { categoryPost.imgLink = "http://www.bundpic.com/upload/\(picName!)" } else { categoryPost.imgLink = image } PostList.sharedInstance.appendCategoryList(categoryPost) if let url:String = showLink { if let nsurl: NSURL = NSURL(string: url)? { Network.callUrl(url) } } } if postArr.count == 0 { self.pageEnd = true listener(false,nil) return } listener(true, PostList.sharedInstance.cateList) }) } func selectData(index: Int) { if let post = PostList.sharedInstance.cateList[index] as? PostData { PostList.sharedInstance.cateListIndex = index if let url:String = post.clickLink { if let nsurl: NSURL = NSURL(string: url)? { Network.callUrl(url) } } if let postUrl:String = post.link { openUrl(postUrl) } } else if let focus = PostList.sharedInstance.cateList[index] as? CategoryFocusData{ PostList.sharedInstance.cateListIndex = index if let url:String = focus.clickLink { if let nsurl: NSURL = NSURL(string: url)? { Network.callUrl(url) } } if let postUrl:String = focus.link { openUrl(postUrl) } } } var segueUrl: String = "" func openUrl(url:String) { if url == "" || url == "undefined"{ return } segueUrl = url if let _ = url.rangeOfString("http://www.bundpic.com/mpost/") { performSegueWithIdentifier("openpost", sender: self) } else { performSegueWithIdentifier("openweb", sender: self) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { var view:UIViewController = segue.destinationViewController as UIViewController if let webView:WebViewController = view as? WebViewController { webView.url = segueUrl } else if let webView:PostViewController = view as? PostViewController { webView.url = segueUrl webView.getNext = PostList.sharedInstance.cateListNext } } func swipeUp() { setTabBarVisible(false, animated: true) } func swipeDown() { setTabBarVisible(true, animated: true) } func setTabBarVisible(visible:Bool, animated:Bool) { //* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time // bail if the current state matches the desired state if (tabBarIsVisible() == visible) { return } // get a frame calculation ready let frame = self.tabBarController?.tabBar.frame let height = frame?.size.height let offsetY = (visible ? -height! : height) // zero duration means no animation let duration:NSTimeInterval = (animated ? 0.3 : 0.0) // animate the tabBar if frame != nil { UIView.animateWithDuration(duration) { self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!) return } } } func tabBarIsVisible() ->Bool { return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame) } }
// DomRoundTripTableViewCell.swift import UIKit class AirLinesCell: UITableViewCell { @IBOutlet weak var airlineLogo: UIImageView! @IBOutlet weak var centerLine: UIImageView! @IBOutlet weak var airlineName: UILabel! @IBOutlet weak var depTime: UILabel! @IBOutlet weak var arrTime: UILabel! @IBOutlet weak var fromCityCode: UILabel! @IBOutlet weak var toCityCode: UILabel! @IBOutlet weak var duration: UILabel! @IBOutlet weak var stops: UILabel! @IBOutlet weak var specialTag: UILabel! @IBOutlet weak var grossFare: UILabel! @IBOutlet weak var netFare: UILabel! @IBOutlet weak var arrTime_splitView: UILabel! @IBOutlet weak var netFare_splitView: UILabel! @IBOutlet weak var logoHightConst: NSLayoutConstraint! @IBOutlet weak var logoWidthConst: NSLayoutConstraint! @IBOutlet weak var depTimeLeftConst: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() self.layoutIfNeeded() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func layoutSubviews() { super.layoutSubviews() DispatchQueue.main.async { if self.frame.size.width < 200 { self.arrTime_splitView.isHidden = false self.netFare_splitView.isHidden = false self.airlineLogo.isHidden = false self.depTime.isHidden = false self.logoHightConst.constant = 45 self.logoWidthConst.constant = 45 self.depTimeLeftConst.constant = 10 self.depTime.font = AppFont.bodyFont self.arrTime_splitView.font = AppFont.bodyFont self.netFare_splitView.font = UIFont.systemFont(ofSize: 16) self.airlineName.isHidden = true self.arrTime.isHidden = true self.fromCityCode.isHidden = true self.toCityCode.isHidden = true self.duration.isHidden = true self.stops.isHidden = true self.specialTag.isHidden = true self.grossFare.isHidden = true self.netFare.isHidden = true self.centerLine.isHidden = true }else{ self.arrTime_splitView.isHidden = true self.netFare_splitView.isHidden = true self.logoHightConst.constant = 56 self.logoWidthConst.constant = 56 self.depTimeLeftConst.constant = 64 self.depTime.font = UIFont.systemFont(ofSize: 18) self.airlineLogo.isHidden = false self.airlineName.isHidden = false self.depTime.isHidden = false self.arrTime.isHidden = false self.fromCityCode.isHidden = false self.toCityCode.isHidden = false self.duration.isHidden = false self.stops.isHidden = false self.specialTag.isHidden = false self.grossFare.isHidden = false self.netFare.isHidden = false self.centerLine.isHidden = false } } } }
// // CreatePaymentDataSource.swift // Hippo // // Created by Vishal on 21/02/19. // import UIKit class CreatePaymentDataSource: NSObject { var store: PaymentStore var shouldSavePaymentPlan : Bool? init(store: PaymentStore) { self.store = store } enum DataSourceSection: Int, CaseCountable { case fields = 0 case items case button } } extension CreatePaymentDataSource: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return DataSourceSection.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let tableSection = DataSourceSection(rawValue: section) else { return 0 } switch tableSection { case .fields: return store.fields.count case .items: return store.items.count case .button: return store.buttons.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let tableSection = DataSourceSection(rawValue: indexPath.section) else { return UITableView.defaultCell() } switch tableSection { case .fields: let customCell = tableView.dequeueReusableCell(withIdentifier: "BroadCastTextFieldCell", for: indexPath) as! BroadCastTextFieldCell let form = store.fields[indexPath.row] customCell.setupCell(form: form) customCell.isUserInteractionEnabled = store.isEditing return customCell case .button: let value = store.buttons[indexPath.row] switch value.action { case .addMore: let customCell = tableView.dequeueReusableCell(withIdentifier: "ShowMoreTableViewCell", for: indexPath) as! ShowMoreTableViewCell customCell.button_CheckBox.isHidden = ((store.canEditPlan ?? false) || (store.isCustomisedPayment ?? false)) ? true : false customCell.button_CheckBox.imageView?.tintColor = .black customCell.button_CheckBox.isSelected = shouldSavePaymentPlan ?? false customCell.button_CheckBox.setImage((shouldSavePaymentPlan ?? false) ? HippoConfig.shared.theme.checkBoxActive : HippoConfig.shared.theme.checkBoxInActive, for: .normal) customCell.totalPriceLabel.text = ((store.canEditPlan ?? false) || (store.isCustomisedPayment ?? false)) ? " " : HippoStrings.savePlan customCell.setupCell(form: value, store: store) return customCell default: let customCell = tableView.dequeueReusableCell(withIdentifier: "BroadcastButtonCell", for: indexPath) as! BroadcastButtonCell customCell.setupCellFor(form: value) return customCell } case .items: let customCell = tableView.dequeueReusableCell(withIdentifier: "PaymentItemDescriptionCell", for: indexPath) as! PaymentItemDescriptionCell customCell.isCustomPayment = store.isCustomisedPayment customCell.hideTitleTextField(store.isCustomisedPayment ?? false) let item = store.items[indexPath.row] let count = store.items.count customCell.setupCellFor(item: item) customCell.isUserInteractionEnabled = store.isEditing customCell.cancelIcon.isHidden = count == 1 || !store.isEditing return customCell } } }
public func width(_ size: Size) -> Feature { return .init(key: "width", value: size.value()) } public func maxWidth(_ size: Size) -> Feature { return .init(key: "max-width", value: size.value()) } public func minWidth(_ size: Size) -> Feature { return .init(key: "min-width", value: size.value()) }
// // MapMarker.swift // bm-persona // // Created by Kevin Hu on 2/24/20. // Copyright © 2020 RJ Pimentel. All rights reserved. // import Foundation import UIKit import MapKit // MARK: - KnownType enum KnownType<T: RawRepresentable>: RawRepresentable { typealias RawValue = T.RawValue case known(type: T) case unknown(raw: RawValue) var rawValue: RawValue { switch self { case .known(let type): return type.rawValue case .unknown(let raw): return raw } } init?(rawValue: RawValue) { let type = T(rawValue: rawValue) if let type = type { self = .known(type: type) } else { self = .unknown(raw: rawValue) } } } // MARK: - MapMarkerType /** Lists all recognized Map Marker Types, where the `rawValue` is the Collection name on Firebase. Add to this enum to add another type of map resource. */ enum MapMarkerType: String, CaseIterable, Comparable { case restaurant = "Restaurant" case cafe = "Cafe" case store = "Store" case mentalHealth = "Mental Health" case garden = "Campus Garden" case bikes = "Lyft Bike" case lactation = "Lactation" case rest = "Rest" case microwave = "Microwave" case printer = "Printer" case water = "Water" case waste = "Waste" case none = "_none" static func < (lhs: MapMarkerType, rhs: MapMarkerType) -> Bool { // Compare marker types by their declaration order guard let lhsIdx = allCases.firstIndex(of: lhs), let rhsIdx = allCases.firstIndex(of: rhs) else { return true } return lhsIdx < rhsIdx } /** The icon to be shown on the map at the marker location */ func icon() -> UIImage { let icon: UIImage? switch self { case .microwave: icon = UIImage(named: "microwave-icon")? .withShadow() break case .rest: icon = UIImage(named: "nap-pods-icon")? .withRoundedBorder(width: 3, color: .white)? .withShadow() break case .printer: icon = UIImage(named: "printer-icon")? .withRoundedBorder(width: 3, color: .white)? .withShadow() break case .water: icon = UIImage(named: "water-bottle-icon")? .withShadow() break case .bikes: icon = UIImage(named: "bike-icon")? .withRoundedBorder(width: 3, color: .white)? .withShadow() break case .lactation: icon = UIImage(named: "lactation-icon")? .withShadow() break case .waste: icon = UIImage(named: "waste-icon") break case .garden: icon = UIImage(named: "garden-icon")? .withShadow() break case .cafe: icon = UIImage(named: "cafe-icon")? .withShadow() break case .store: icon = UIImage(named: "store-icon")? .withRoundedBorder(width: 3, color: .white)? .withShadow() break case .mentalHealth: icon = UIImage(named: "mental-health-icon")? .withShadow() break default: icon = UIImage(named: "Placemark")? .colored(Color.MapMarker.other) break } return (icon ?? UIImage()).resized(size: CGSize(width: 30, height: 30)) } /** The color describing this marker type */ func color() -> UIColor { switch self { case .microwave: return Color.MapMarker.microwave case .rest: return Color.MapMarker.rest case .printer: return Color.MapMarker.printer case .water: return Color.MapMarker.water case .bikes: return Color.MapMarker.bikes case .lactation: return Color.MapMarker.lactation case .waste: return Color.MapMarker.waste case .garden: return Color.MapMarker.garden case .store: return Color.MapMarker.store case .cafe: return Color.MapMarker.cafe case .mentalHealth: return Color.MapMarker.mentalHealth default: return Color.MapMarker.other } } } // MARK: - MapMarker /** Object describing resource locations (Microwaves, Bikes, Nap Pods, etc.) */ class MapMarker: NSObject, MKAnnotation, HasOpenTimes, SearchItem { var type: KnownType<MapMarkerType> var coordinate: CLLocationCoordinate2D @Display var title: String? @Display var subtitle: String? @Display var phone: String? @Display var email: String? @Display var address: String? var onCampus: Bool? var weeklyHours: WeeklyHours? var appointment: Bool? var mealPrice: String? var cal1Card: Bool? var eatWell: Bool? var searchName: String var location: (Double, Double) var locationName: String var icon: UIImage? var name: String init?(type: String, location: CLLocationCoordinate2D, name: String? = nil, description: String? = nil, address: String? = nil, onCampus: Bool? = nil, phone: String? = nil, email: String? = nil, weeklyHours: WeeklyHours? = nil, appointment: Bool? = nil, mealPrice: String? = nil, cal1Card: Bool? = nil, eatWell: Bool? = nil) { guard let type = KnownType<MapMarkerType>(rawValue: type) else { return nil } self.type = type self.coordinate = location self.title = name self.subtitle = description self.address = address self.onCampus = onCampus self.phone = phone self.email = email self.weeklyHours = weeklyHours self.mealPrice = mealPrice self.cal1Card = cal1Card self.eatWell = eatWell self.searchName = name ?? "" self.location = (location.latitude, location.longitude) self.locationName = address ?? "" self.icon = nil self.name = name ?? "" } }
// // LPJNavigationController.swift // LightPomodoro // // Created by 王嘉宁 on 2020/12/9. // Copyright © 2020 Johnny. All rights reserved. // import UIKit class LPJNavigationController: UINavigationController { }
// // ViewController.swift // Past Paper Crawler // // Created by 吴浩榛 on 2018/8/26. // Copyright © 2018年 吴浩榛. All rights reserved. // import Cocoa class MainViewController: NSViewController { @IBOutlet var quickOpComboBox: NSComboBox! @IBOutlet var quickOpPerformButton: NSButton! @IBOutlet var quickOpProcess: NSProgressIndicator! @IBOutlet var quickOpPromptLabel: PromptLabel! @IBOutlet var quickOpRetryButton: NSButton! var quickOpRetryAction: () -> () = {} { didSet { quickOpRetryButton.isHidden = false } } var quickOpPossiblePapers: [WebFile] = [] { didSet { quickOpComboBox.reloadData() } } var currentCode = "" var currentSubjectPrompt = "" var accessCount = 0 @IBOutlet var subjectPopButton: QuickListPopUpButton! let subjectPopButtonOperationQueue = DispatchQueue(label: "Subject Pop Button Protect") var defaultPopButtonPrompt = "" @IBOutlet weak var subjectProgress: NSProgressIndicator! @IBOutlet var subjectPromptLabel: PromptLabel! enum Mode { case Subject case Paper } var quickOpMode: Mode = .Paper { willSet { if newValue != quickOpMode { if newValue == .Subject { quickOpPerformButton.title = "open sub" } else { quickOpPerformButton.title = "download" } } } } override func viewDidLoad() { super.viewDidLoad() quickOpComboBox.usesDataSource = true quickOpComboBox.dataSource = self quickOpComboBox.delegate = self quickOpMode = .Subject } @IBAction func operationConfirmed(_ sender: Any) { let text = quickOpComboBox.stringValue if quickOpMode == .Subject { if !quickOpPerformButton.isHidden { subjectPopButton.performConfirmSelection() } } else if let selectedPaper = quickOpPossiblePapers.first(where: { $0.name == text }) { quickOpDownload(paper: selectedPaper) } } func quickOpDownload(paper: WebFile, to path: String? = nil) { quickOpProcess.startAnimation(nil) quickOpPromptLabel.showPrompt("Downloading...") quickOpComboBox.isEnabled = false quickOpPerformButton.isEnabled = false ADDownload(papers: [paper], to: path) { path, failed in DispatchQueue.main.async { if !failed.isEmpty { self.quickOpPromptLabel.showError("Failed!") self.quickOpRetryAction = { self.quickOpDownload(paper: paper, to: path) } } else { self.quickOpPromptLabel.showPrompt("Succeed!") } self.quickOpProcess.stopAnimation(nil) self.quickOpComboBox.isEnabled = true self.quickOpPerformButton.isEnabled = true } } } @IBAction func retryClicked(_ sender: Any) { quickOpRetryButton.isHidden = true quickOpRetryAction() // fire action } func startLoadingSubject() { // lock up button quickOpComboBox.isEnabled = false quickOpPerformButton.isEnabled = false subjectPopButton.isEnabled = false subjectProgress.startAnimation(nil) } func endLoadingSubject() { } var _subjactLoading: Bool = false var subjectLoading: Bool { get { return _subjactLoading } set { _subjactLoading = newValue if newValue { // lock up button quickOpComboBox.isEnabled = false quickOpPerformButton.isEnabled = false subjectPopButton.isEnabled = false subjectProgress.startAnimation(nil) } else { quickOpComboBox.isEnabled = true quickOpPerformButton.isEnabled = true subjectPopButton.isEnabled = true subjectProgress.stopAnimation(nil) } } } @IBAction func subjectSelected(_ sender: Any) { if let subject = subjectPopButton.selectedSubject { var undone = false undoManager?.registerUndo(withTarget: subjectPopButton) { _ in undone = true self.subjectLoading = false } subjectPromptLabel.setToDefault() subjectLoading = true let paperWindow: NSWindowController = getController("Papers Window")! let paperView = paperWindow.contentViewController as! PapersViewController DispatchQueue.global(qos: .userInteractive).async { defer { DispatchQueue.main.async { self.subjectLoading = false self.undoManager?.removeAllActions() } } // load current subject if !paperView.rawLoad(subject: subject) { DispatchQueue.main.async { self.subjectPromptLabel.showError("Failed to load subject!") } return } if undone { return } DispatchQueue.main.async { // display paper window paperView.subjectPopButton.selectedSubject = subject paperView.defaultUpdateAfterLoadingSubject() paperWindow.showWindow(nil) // set back prompt self.subjectPopButton.discardSelectedSubject() self.quickOpPerformButton.isHidden = true } } } } } extension MainViewController: NSComboBoxDelegate { func controlTextDidChange(_ obj: Notification) { quickOpRetryButton.isHidden = true let text = quickOpComboBox.stringValue if text.isEmpty { quickOpPromptLabel.setToDefault() return } if text[0] < "0" || text[0] > "9" { findSubject() } else { loadPapers() } } func findSubject() { quickOpMode = .Subject quickOpPromptLabel.setToDefault() quickOpPossiblePapers = [] let text = quickOpComboBox.stringValue subjectPopButtonOperationQueue.sync { // find subject from quick list let lowercasedText = text.lowercased() var found = false for index in 2..<2+PFQuickListCount { if let item = subjectPopButton.item(at: index), item.isEnabled && item.title.lowercased().hasPrefix(lowercasedText) { DispatchQueue.main.async { self.subjectPopButton.select(item) self.quickOpMode = .Subject self.quickOpPerformButton.isHidden = false } found = true break } } if !found { quickOpPerformButton.isHidden = true } } } func loadPapers() { quickOpMode = .Paper let text = quickOpComboBox.stringValue quickOpPerformButton.isHidden = !quickOpPossiblePapers.contains(where: { $0.name == text }) let count = text.count if count < 4 { quickOpPossiblePapers = [] if count > 0 { quickOpPromptLabel.showError("Subject code incomplete!") } currentCode = "" currentSubjectPrompt = "" quickOpProcess.stopAnimation(nil) return } let code = text[0...3] if code != currentCode { currentCode = code loadSubject(code: code) } else if !currentSubjectPrompt.isEmpty { quickOpPromptLabel.showPrompt(currentSubjectPrompt) } } func loadSubject(code: String) { quickOpPromptLabel.showPrompt("Loading subject...") quickOpProcess.startAnimation(nil) accessCount += 1 DispatchQueue.global(qos: .userInteractive).async { defer { DispatchQueue.main.async { self.accessCount -= 1 if self.accessCount == 0 { self.quickOpProcess.stopAnimation(nil) } } } guard let subject = SubjectUtil.current.findSubject(with: code) else { DispatchQueue.main.async { self.quickOpPossiblePapers = [] self.quickOpPromptLabel.showError("Failed to find subject code!") self.quickOpRetryAction = { self.loadSubject(code: code) } } return } if self.currentCode != code { return } guard let files = PFUsingWebsite.getPapers(level: subject.level, subject: subject.name) else { DispatchQueue.main.async { self.quickOpPossiblePapers = [] self.quickOpPromptLabel.showError("Failed to get paper list!") self.quickOpRetryAction = { self.loadSubject(code: code) } } return } if self.currentCode != code { return } DispatchQueue.main.async { self.quickOpPossiblePapers = files self.currentSubjectPrompt = "Subject: \(subject.name)" self.quickOpPromptLabel.showPrompt(self.currentSubjectPrompt) } } } } extension MainViewController: NSComboBoxDataSource { func numberOfItems(in comboBox: NSComboBox) -> Int { return quickOpPossiblePapers.count } func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? { return quickOpPossiblePapers[index].name } }
// // Copyright © 2020 Tasuku Tozawa. All rights reserved. // import Combine import Domain protocol SettingsViewProtocol: AnyObject { func set(version: String) func set(isICloudSyncEnabled: Bool) func confirmToUnavailabilityICloudSync(shouldTurnOff: @escaping (Bool) -> Void) func confirmToUnavailabilityICloudSync(shouldTurnOn: @escaping (Bool) -> Void) func confirmToTurnOffICloudSync(confirmation: @escaping (Bool) -> Void) } class SettingsPresenter { private let storage: UserSettingsStorageProtocol private let availabilityStore: CloudAvailabilityStore private var subscriptions: Set<AnyCancellable> = .init() private(set) var shouldHideHiddenItems: CurrentValueSubject<Bool, Never> private(set) var shouldSyncICloudEnabled: CurrentValueSubject<Bool, Never> weak var view: SettingsViewProtocol? // MARK: - Lifecycle init(storage: UserSettingsStorageProtocol, availabilityStore: CloudAvailabilityStore) { self.storage = storage self.availabilityStore = availabilityStore self.shouldHideHiddenItems = .init(false) self.shouldSyncICloudEnabled = .init(false) self.storage.showHiddenItems .receive(on: DispatchQueue.main) .map { !$0 } .sink(receiveValue: { [weak self] value in self?.shouldHideHiddenItems.send(value) }) .store(in: &self.subscriptions) self.storage.enabledICloudSync .combineLatest(self.availabilityStore.state) .receive(on: DispatchQueue.main) .sink(receiveValue: { [weak self] settingEnabled, availability in let isOn = settingEnabled && availability?.isAvailable == true self?.shouldSyncICloudEnabled.send(isOn) }) .store(in: &self.subscriptions) } func set(hideHiddenItems: Bool) { self.storage.set(showHiddenItems: !hideHiddenItems) } func set(isICloudSyncEnabled: Bool) -> Bool { guard let availability = self.availabilityStore.state.value else { return false } if isICloudSyncEnabled, availability == .unavailable { let isEnabledICloudSync = self.storage.readEnabledICloudSync() if isEnabledICloudSync { self.view?.confirmToUnavailabilityICloudSync(shouldTurnOff: { [weak self] shouldTurnOff in guard shouldTurnOff else { return } self?.view?.confirmToTurnOffICloudSync { isOk in guard isOk else { return } self?.storage.set(enabledICloudSync: false) } }) } else { self.view?.confirmToUnavailabilityICloudSync(shouldTurnOn: { [weak self] shouldTurnOn in guard shouldTurnOn else { return } self?.storage.set(enabledICloudSync: true) }) } return false } if isICloudSyncEnabled { self.storage.set(enabledICloudSync: true) } else { self.view?.confirmToTurnOffICloudSync { [weak self] isOk in guard isOk else { self?.view?.set(isICloudSyncEnabled: true) return } self?.storage.set(enabledICloudSync: false) } } return true } func displayVersion() { // swiftlint:disable:next force_cast force_unwrapping let versionString = Bundle(for: Self.self).infoDictionary!["CFBundleShortVersionString"] as! String self.view?.set(version: "\(versionString)") } }
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var platesArray = [1,2,3,4,5,5,5,5,9,10,11,12] for i in platesArray{ i } for var i = 0; i < platesArray.count; i++ { ++platesArray[i] } var plates = [10,0,2,0,0,0] var thePlates = [0,0,0,0,0,0] //1 is 45 //2 is 35 //3 is 25 //4 is 10 //5 is 5 //if there are more than 12 45 plates make it so theres only 12 in the array if plates[0] > 12 { for var i = 0; i < thePlates.count; i++ { thePlates[i] = 1 //return the array } } var plateRefs = [Int]() for var i = 0; i < thePlates.count; i++ { if plates[i] == 2 && i == 0 { thePlates[i] = 1 plateRefs.append(1) } else if plates[i] == 2 && i == 1 { thePlates[i] = 2 plateRefs.append(2) } else if plates[i] == 2 && i == 2 { thePlates[i] = 3 plateRefs.append(3) } else if plates[i] == 2 && i == 3 { thePlates[i] = 4 plateRefs.append(4) } else if plates[i] == 2 && i == 4 { thePlates[i] = 5 plateRefs.append(5) } else if plates[0] == 4 && i == 0 { plateRefs.append(1) plateRefs.append(1) } else if plates[0] == 6 && i == 0 { plateRefs.append(1) plateRefs.append(1) plateRefs.append(1) } else if plates[0] == 8 && i == 0 { plateRefs.append(1) plateRefs.append(1) plateRefs.append(1) plateRefs.append(1) } else if plates[0] == 10 && i == 0 { plateRefs.append(1) plateRefs.append(1) plateRefs.append(1) plateRefs.append(1) plateRefs.append(1) } print(plateRefs) var temp = plateRefs for var i = 0; i < plateRefs.count; i++ { temp.append(plateRefs[i]) } println(temp) temp.sort({ (T: Int, P: Int) -> Bool in return P > T }) println(temp) // temp.sort({ (a,b) -> Bool in // println(temp) // }) }
// // AddTableViewController.swift // FoodPin // // Created by 廖慶麟 on 2016/2/25. // Copyright © 2016年 廖慶麟. All rights reserved. // import UIKit import Foundation import CoreData import CloudKit class AddTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { @IBOutlet weak var imageView:UIImageView! @IBOutlet weak var nameTextField:UITextField! @IBOutlet weak var typeTextField:UITextField! @IBOutlet weak var locationTextField:UITextField! @IBOutlet weak var yesButton:UIButton! @IBOutlet weak var noButton:UIButton! var restaurant:Restaurant! override func viewDidLoad() { super.viewDidLoad() yesButton.addTarget(self, action: "yesButtonTapped", forControlEvents: .TouchUpInside) noButton.addTarget(self, action: "noButtonTapped", forControlEvents: .TouchUpInside) nameTextField.delegate = self; typeTextField.delegate = self; locationTextField.delegate = self; // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){ let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.sourceType = .PhotoLibrary self.presentViewController(imagePicker, animated: true, completion: nil) } } tableView.deselectRowAtIndexPath(indexPath, animated: true) } // when press return on keyboard, then dismiss it! func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // After user finishes picking pictures. func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true dismissViewControllerAnimated(true, completion: nil) } @IBAction func save(){ let alert = UIAlertView() var emptyfield: String! if nameTextField.text == "" { emptyfield = "restaurant name" } else if typeTextField.text == "" { emptyfield = "restaurant type" } else if locationTextField.text == "" { emptyfield = "restaurant location" } if emptyfield == nil { var isVisited: Bool = true if noButton.backgroundColor == UIColor.redColor(){ isVisited = false } // Save object to CoreData if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext { restaurant = NSEntityDescription.insertNewObjectForEntityForName("Restaurant", inManagedObjectContext: managedObjectContext) as! Restaurant restaurant.name = nameTextField.text restaurant.type = typeTextField.text restaurant.location = locationTextField.text restaurant.image = UIImagePNGRepresentation(imageView.image!) restaurant.isVisited = isVisited var e: NSError? do { try managedObjectContext.save() } catch { print("insert error: \(e!.localizedDescription)") } saveRecordToCloud(restaurant) performSegueWithIdentifier("unwindToHomeScreen", sender: self) } }else { alert.title = "Ooops" alert.message = "We can't proceed as you forget to fill in the \(emptyfield). All fields are mandatory." alert.addButtonWithTitle("OK") alert.show() } } func noButtonTapped(){ noButton.backgroundColor = UIColor.redColor() yesButton.backgroundColor = UIColor.lightGrayColor() } func yesButtonTapped(){ yesButton.backgroundColor = UIColor.redColor() noButton.backgroundColor = UIColor.lightGrayColor() } func saveRecordToCloud(restaurant:Restaurant!) -> Void { // Prepare the record to save var record = CKRecord(recordType: "Restaurant") record.setValue(restaurant.name, forKey:"name") record.setValue(restaurant.type, forKey:"type") record.setValue(restaurant.location, forKey:"location") // Resize the image var originalImage = UIImage(data: restaurant.image) var scalingFactor = (originalImage!.size.width > 1024) ? 1024 / originalImage!.size.width : 1.0 var scaledImage = UIImage(data: restaurant.image, scale: scalingFactor) // Write the image to local file for temporary use let imageFilePath = NSTemporaryDirectory() + restaurant.name UIImageJPEGRepresentation(scaledImage!, 0.8)?.writeToFile(imageFilePath, atomically: true) // Create image asset for upload let imageFileURL = NSURL(fileURLWithPath: imageFilePath) var imageAsset = CKAsset(fileURL: imageFileURL) record.setValue(imageAsset, forKey: "image") // Get the Public iCloud Database let cloudContainer = CKContainer.defaultContainer() let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase // Save the record to iCloud publicDatabase.saveRecord(record, completionHandler: { (record:CKRecord?, error:NSError?) -> Void in // Remove temp file var err:NSError? do{ try NSFileManager.defaultManager().removeItemAtPath(imageFilePath) } catch { print("Failed to save record to the cloud: \(err?.localizedDescription)") } }) } // MARK: - Table view data source /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return 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. } */ }
// // SessionManager+Exposure.swift // Exposure // // Created by Fredrik Sjöberg on 2017-10-13. // Copyright © 2017 emp. All rights reserved. // import Foundation import iOSClientDownload import iOSClientExposure extension iOSClientDownload.SessionManager where T == ExposureDownloadTask { /* /// Create an `ExposureDownloadTask` by requesting a `PlaybackEntitlementV2` supplied through exposure. /// /// If the requested content is *FairPlay* protected, the appropriate `DownloadExposureFairplayRequester` will be created. Configuration will be taken from the `PlaybackEntitlementV2` response. /// /// A relevant `ExposureAnalytics` object will be created. /// /// - parameter assetId: A unique identifier for the asset /// - parameter sessionToken: Token identifying the active session /// - parameter environment: Exposure environment used for the active session /// - returns: `ExposureDownloadTask` public func download(assetId: String, using sessionToken: SessionToken, in environment: Environment) -> T { let provider = ExposureAnalytics(environment: environment, sessionToken: sessionToken) return download(assetId: assetId, analyticProvider: provider) } */ public func download(assetId: String, using sessionToken: SessionToken, in environment: Environment) -> T { return download(assetId: assetId, sessionToken: sessionToken, environment: environment) } } extension iOSClientDownload.SessionManager where T == ExposureDownloadTask { /* Remove passing analyticsProvider temporary /// Create an `ExposureDownloadTask` by requesting a `PlaybackEntitlementV2` supplied through exposure. /// /// Entitlement requests will be done by using the `Environment` and `SessionToken` associated with `analyticsProvider` /// /// If the requested content is *FairPlay* protected, the appropriate `DownloadExposureFairplayRequester` will be created. Configuration will be taken from the `PlaybackEntitlementV2` response. /// /// - parameter assetId: A unique identifier for the asset /// - parameter analyticsProvider: The specified analytics provider. /// - returns: `ExposureDownloadTask` public func download(assetId: String, analyticProvider: ExposureDownloadAnalyticsProvider) -> T { if let currentTask = delegate[assetId] { print("♻️ Retrieved ExposureDownloadTask associated with request for: \(assetId)") return currentTask } else { print("✅ Created new ExposureDownloadTask for: \(assetId)") return ExposureDownloadTask(assetId: assetId, sessionManager: self, analyticsProvider: analyticProvider) } } */ /// Create an `ExposureDownloadTask` by requesting a `PlaybackEntitlementV2` supplied through exposure. /// /// Entitlement requests will be done by using the `Environment` and `SessionToken` associated with `analyticsProvider` /// /// If the requested content is *FairPlay* protected, the appropriate `DownloadExposureFairplayRequester` will be created. Configuration will be taken from the `PlaybackEntitlementV2` response. /// /// - Parameters: /// - assetId: assetId: A unique identifier for the asset /// - sessionToken: user session token /// - environment: customer enviornment /// - Returns: ExposureDownloadTask public func download(assetId: String, sessionToken: SessionToken, environment: Environment ) -> T { if let currentTask = delegate[assetId] { print("♻️ Retrieved ExposureDownloadTask associated with request for: \(assetId)") return currentTask } else { print("✅ Created new ExposureDownloadTask for: \(assetId)") return ExposureDownloadTask(assetId: assetId, sessionManager: self, sessionToken: sessionToken, environment: environment) } } } // MARK: - OfflineMediaAsset extension iOSClientDownload.SessionManager where T == ExposureDownloadTask { public func getDownloadedAsset(assetId: String) -> OfflineMediaAsset? { return getDownloadedAssets() .filter{ $0.assetId == assetId } .first } public func getDownloadedAssets() -> [OfflineMediaAsset] { guard let localMedia = localMediaRecords else { return [] } return localMedia.map{ resolve(mediaRecord: $0) } } /// Get downloaded Assets by `accountId` /// - Parameter accountId: accountId /// - Returns: array of OfflineMediaAsset public func getDownloadedAssets(accountId:String?) -> [OfflineMediaAsset] { guard let localMedia = localMediaRecords else { return [] } guard let accountId = accountId else { return [] } let allLocalMdeia = localMedia.map{ resolve(mediaRecord: $0) } return allLocalMdeia.filter(){ $0.accountId == accountId } } /// Shoud renew licenes for a given asset /// - Parameters: /// - assetId: asset Id /// - sessionToken: session token /// - environment: environment /// - completion: completion public func renewLicense(assetId: String, sessionToken: SessionToken, environment: Environment, completion: @escaping (OfflineMediaAsset?, Error?) -> Void) { guard let media = getDownloadedAsset(assetId: assetId) else { print("❌ Could not find local media for renewal: assetId \(assetId)") let error = ExposureDownloadTask.Error.fairplay(reason: .missingApplicationCertificateUrl) completion(nil, error) return } self.validateEntitlementRequest(environment: environment, sessionToken: sessionToken, assetId: assetId) { [weak self] newEntitlement, error in guard let `self` = self else { completion(nil, nil ) return } if let error = error { print("❌ Entitlement granted failed for assetId: \(assetId) , Error \(error)") completion(nil, error ) } else { print("✅ New entitlement was granted for assetId : \(assetId)") do { if let localRecord = self.getLocalMediaRecordFor(assetId: assetId) { var updatedLocalRecord = localRecord updatedLocalRecord.entitlement = newEntitlement self.save(localRecord: updatedLocalRecord) let offlineAsset = OfflineMediaAsset(assetId: assetId, accountId: sessionToken.accountId, userId: sessionToken.userId, entitlement: newEntitlement, url: try media.fairplayRequester?.contentKeyUrl(for: assetId), downloadState: .completed, format: media.format, sessionManager: self) self.sendDownloadRenewed(assetId: assetId, environment:environment, sessionToken: sessionToken ) completion(offlineAsset, nil ) } } catch { print("❌ Updating local record with new entitlement was failed for assetId : \(assetId) , Error \(error)") completion(nil, error) } } } } /// Send download renewal completion to the exposure /// - Parameter assetId: assetId internal func sendDownloadRenewed(assetId: String, environment: Environment, sessionToken: SessionToken) { SendDownloadRenewed(assetId: assetId, environment: environment, sessionToken: sessionToken) .request() .validate() .response { result in if result.error != nil { // Ignore any errors , keep the downloaded media print("🚨 DownloadRenewed request to the Backend was failed. Error from Exposure : \(result.error )" ) } else { print("✅ DownloadRenewed request to the Backend was success. Message from Exposure : \(result.value )" ) } } } fileprivate func validateEntitlementRequest(environment:Environment,sessionToken:SessionToken, assetId: String, completionHandler: @escaping (PlayBackEntitlementV2?, ExposureError?) -> Void) { let _ = Entitlement(environment:environment, sessionToken: sessionToken) .validate(downloadId: assetId) .request() .validate() .response { guard let entitlement = $0.value else { // self.eventPublishTransmitter.onError(self, nil, $0.error!) completionHandler(nil, $0.error) return } completionHandler(entitlement, nil ) } } /// Get downloaded Assets by `userId` /// - Parameter userId: userId /// - Returns: array of OfflineMediaAsset public func getDownloadedAssets(userId:String?) -> [OfflineMediaAsset] { guard let localMedia = localMediaRecords else { return [] } guard let userId = userId else { return [] } let allLocalMdeia = localMedia.map{ resolve(mediaRecord: $0) } return allLocalMdeia.filter(){ $0.userId == userId } } public func delete(media: OfflineMediaAsset) { remove(localRecordId: media.assetId) do { try media.fairplayRequester?.deletePersistedContentKey(for: media.assetId) if let url = media.urlAsset?.url { try FileManager.default.removeItem(at: url) } print("✅ SessionManager+Exposure. Cleaned up local media",media.assetId,"Destination:",media.urlAsset?.url) } catch { print("🚨 SessionManager+Exposure. Failed to clean local media: ",error.localizedDescription) } } /// Delete a downloaded asset /// - Parameter assetId: assetId public func removeDownloadedAsset(assetId: String, sessionToken: SessionToken, environment: Environment) { guard let media = getDownloadedAsset(assetId: assetId) else { return } delete(media: media) } internal func save(assetId: String, accountId:String?, userId:String?, entitlement: PlayBackEntitlementV2?, url: URL?, downloadState: DownloadState) { do { if let currentAsset = getDownloadedAsset(assetId: assetId) { if currentAsset.urlAsset?.url != nil { print("⚠️ There is another record for an offline asset with id: \(assetId). This data will be overwritten. The location of any downloaded media or content keys will be lost!") print(" x ",currentAsset.urlAsset?.url) print(" <- ",url) } else { print("✅ SessionManager+Exposure. Updated \(assetId) with a destination url \(url)") } } let record = try LocalMediaRecord(assetId: assetId, accountId: accountId, userId: userId, entitlement: entitlement, completedAt: url, downloadState: downloadState, format: entitlement?.formats?.first?.format ?? "HLS") save(localRecord: record) } catch { print("🚨 Unable to bookmark local media record \(assetId): ",error.localizedDescription) } } } // MARK: - LocalMediaRecord extension iOSClientDownload.SessionManager where T == ExposureDownloadTask { /// Get local media record for a given `assetId` func getLocalMediaRecordFor(assetId: String) -> LocalMediaRecord? { do { let logFile = try logFileURL() let logData = try Data(contentsOf: logFile) print("Reading... 📖: \(logFile.description)") let localMedia = try JSONDecoder().decode([LocalMediaRecord].self, from: logData) let filteredLog = localMedia.filter{ $0.assetId == assetId }.first return filteredLog } catch { print("🚨 Error fetching local media : \(error)") return nil } } var localMediaRecords: [LocalMediaRecord]? { do { let logFile = try logFileURL() if !FileManager.default.fileExists(atPath: logFile.path) { return [] } let data = try Data(contentsOf: logFile) let localMedia = try JSONDecoder().decode([LocalMediaRecord].self, from: data) return localMedia } catch { print("localMediaLog failed",error.localizedDescription) return nil } } fileprivate func resolve(mediaRecord: LocalMediaRecord) -> OfflineMediaAsset { var bookmarkDataIsStale = false guard let urlBookmark = mediaRecord.urlBookmark else { return OfflineMediaAsset(assetId: mediaRecord.assetId, accountId: mediaRecord.accountId, userId: mediaRecord.userId, entitlement: mediaRecord.entitlement, url: nil, downloadState: mediaRecord.downloadState, format: mediaRecord.format, sessionManager: self) } do { let url = try URL(resolvingBookmarkData: urlBookmark, bookmarkDataIsStale: &bookmarkDataIsStale) /* guard let url = try URL(resolvingBookmarkData: urlBookmark, bookmarkDataIsStale: &bookmarkDataIsStale) else { return OfflineMediaAsset(assetId: mediaRecord.assetId, entitlement: mediaRecord.entitlement, url: nil) } */ guard !bookmarkDataIsStale else { return OfflineMediaAsset(assetId: mediaRecord.assetId, accountId: mediaRecord.accountId, userId: mediaRecord.userId, entitlement: mediaRecord.entitlement, url: nil, downloadState: mediaRecord.downloadState, format: mediaRecord.format, sessionManager: self) } return OfflineMediaAsset(assetId: mediaRecord.assetId, accountId: mediaRecord.accountId, userId: mediaRecord.userId, entitlement: mediaRecord.entitlement, url: url, downloadState: mediaRecord.downloadState, format: mediaRecord.format, sessionManager: self) } catch { return OfflineMediaAsset(assetId: mediaRecord.assetId, accountId: mediaRecord.accountId, userId: mediaRecord.userId, entitlement: mediaRecord.entitlement, url: nil, downloadState: mediaRecord.downloadState, format: mediaRecord.format, sessionManager: self) } } } // MARK: Directory extension iOSClientDownload.SessionManager where T == ExposureDownloadTask { fileprivate var localMediaRecordsFile: String { return "localMediaRecords" } fileprivate func logFileURL() throws -> URL { return try baseDirectory().appendingPathComponent(localMediaRecordsFile) } /// This directory should be reserved for analytics data. /// /// - returns: `URL` to the base directory /// - throws: `FileManager` error internal func baseDirectory() throws -> URL { return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent("emp") .appendingPathComponent("exposure") .appendingPathComponent("offlineMedia") } } // MARK: Save / Remove extension iOSClientDownload.SessionManager where T == ExposureDownloadTask { /// This method will update `LocalMediaLog` with given updated `localRecord` fileprivate func update(localRecord: LocalMediaRecord) { var localMedia = localMediaRecords ?? [] let filteredLog = localMedia.filter{ $0.assetId == localRecord.assetId }.first localMedia.removeAll(where: {$0.assetId == filteredLog?.assetId }) localMedia.append(localRecord) save(mediaLog: localMedia) print("✅ Update bookmark for local media record \(localRecord.assetId): ") } /// This method will ensure `LocalMediaLog` has a unique list of downloads with respect to `assetId` fileprivate func save(localRecord: LocalMediaRecord) { let localMedia = localMediaRecords ?? [] var filteredLog = localMedia.filter{ $0.assetId != localRecord.assetId } filteredLog.append(localRecord) save(mediaLog: filteredLog) print("✅ Saved bookmark for local media record \(localRecord.assetId): ") } fileprivate func save(mediaLog: [LocalMediaRecord]) { do { let logURL = try baseDirectory() let data = try JSONEncoder().encode(mediaLog) try data.persist(as: localMediaRecordsFile, at: logURL) } catch { print("save(mediaLog:) failed",error.localizedDescription) } } internal func remove(localRecordId: String) { guard let localMedia = localMediaRecords else { return } /// Update and save new log let newLog = localMedia.filter{ $0.assetId != localRecordId } save(mediaLog: newLog) } } // MARK: - Download Info extension iOSClientDownload.SessionManager where T == ExposureDownloadTask { /// Returns if an asset is available to download or not /// - Parameters: /// - assetId: assetId /// - environment: enviornment /// - sessionToken: sessionToken /// - completionHandler: completion public func isAvailableToDownload( assetId: String, environment: Environment, sessionToken: SessionToken, _ completionHandler: @escaping (Bool) -> Void) { self.getDownloadableInfo(assetId: assetId, environment: environment, sessionToken: sessionToken) { [weak self] info in completionHandler( info != nil ? true : false ) } } /// Get downloadable info of an Asset /// - Parameters: /// - assetId: assetId /// - environment: Exposure Enviornment /// - sessionToken: user sessionToken /// - completionHandler: completion public func getDownloadableInfo(assetId: String, environment: Environment, sessionToken: SessionToken, _ completionHandler: @escaping (DownloadInfo?) -> Void) { GetDownloadableInfo(assetId: assetId, environment: environment, sessionToken: sessionToken) .request() .validate() .response { info in if let downloadInfo = info.value { completionHandler(downloadInfo) } else { completionHandler(nil) } } } /// Check if the license has expired or not /// - Parameter assetId: asset id /// - Returns: true if the license has expired public func isExpired(assetId: String)-> Bool { let downloadedAsset = getDownloadedAsset(assetId: assetId) guard let playTokenExpiration = downloadedAsset?.entitlement?.playTokenExpiration else { return true } let today = Date().millisecondsSince1970 return playTokenExpiration * 1000 >= today ? false : true } /// get the license expiration time /// - Parameter assetId: asset id /// - Returns: playTokenExpiration public func getExpiryTime(assetId: String)->Int? { let downloadedAsset = getDownloadedAsset(assetId: assetId) return downloadedAsset?.entitlement?.playTokenExpiration } }
// // LeafEdgeImageSelectionView.swift // florafinder // // Created by Andrew Tokeley on 6/05/16. // Copyright © 2016 Andrew Tokeley . All rights reserved. // import Foundation class LeafEdgeImageSelectionView: ImageSelectionView { override internal var cellSize: CGSize { return CGSizeMake(70,80) } override internal var showLabel: Bool { return true } override internal var numberOfColumns: Int? { return 3 } var selectedItem: LeafEdgeType? { return super._selectedItem?.tag as? LeafEdgeType } override internal var datasource: [ImageSelectionData] { if (_datasource.count == 0) { _datasource = [ImageSelectionData]() let service = ServiceFactory.shareInstance.leafEdgeTypeService for edge in service.getAll() { if let lookup = LeafEdgeTypeEnum(rawValue: edge.name!) { if let image = lookup.image().changeColor(UIColor.leafDarkGreen()) { let data = ImageSelectionData(image: image, text: edge.name, selected: false) data.tag = edge _datasource.append(data) } } } } return _datasource } }
// // TimerViewController.swift // StudyUp // // Created by Mitchel Eppich on 2017-03-04. // Copyright © 2017 SFU Health++. All rights reserved. // // Contributions from: Owen Kwok, Leone Tory // import UIKit import FirebaseAuth class TimerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { let courses = current_user.course var timerCount = 60 var timerRunning = false var start_time : Int? // Mitchel Added var timer = Timer() var breakTimer = Timer() var breakRunning = false var timerEnabled = false var sessionTime = 3001 // 3000 seconds = 50 min sessions var breakTime = 600 // = 10 min break var breakRatio : Double = 1/6 // Break time for <50 min sessions @IBOutlet weak var timePicker: UIDatePicker! @IBOutlet weak var countDownLabel: UILabel! @IBOutlet weak var breakTimeLabel: UILabel! @IBOutlet weak var totalTimeLabel: UILabel! @IBOutlet weak var totalTextLabel: UILabel! @IBOutlet weak var coursePickerButton: UIButton! @IBOutlet weak var coursePicker: UIPickerView! @IBOutlet weak var smartStudyToggle: UISwitch! @IBOutlet weak var smartStudyToggleView: UIView! @IBOutlet weak var smartStudyView: UIView! @IBOutlet weak var breakButton: UIButton! @IBOutlet weak var resumeButton: UIButton! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var endButton: UIButton! override func viewDidLoad() { super.viewDidLoad() coursePicker.dataSource = self coursePicker.delegate = self timePicker.countDownDuration = 60.0 if timerCount == 0 { timerRunning = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Sends int value from UIDatePicker @IBAction func timePickerAction(_ sender: UIDatePicker) { timerCount = Int(timePicker.countDownDuration) } @IBAction func courseButtonPressed(_ sender: AnyObject) { coursePicker.isHidden = false smartStudyToggleView.isHidden = true smartStudyView.isHidden = true } // Toggles smartStudy @IBAction func smartStudyToggled(_ sender: AnyObject) { if smartStudyToggle.isOn{ smartStudyView.isHidden = false } else { smartStudyView.isHidden = true totalTimeLabel.isHidden = true totalTextLabel.isHidden = true } } func numberOfComponents(in pickerView: UIPickerView)-> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return courses.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent: Int) -> String? { return Array(courses.keys)[row] } // Displays courses to select in the scroll wheel // User will not be able to start unless they pick a course or general setting func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){ coursePickerButton.setTitle(Array(courses.keys)[row], for: UIControlState.normal) coursePicker.isHidden = true smartStudyView.isHidden = false smartStudyToggleView.isHidden = false startButton.isEnabled = true } // Main functionality of timer // Uses timerCount to display the timer value and initializes timer @IBAction func startButtonPressed(_ sender: UIButton) { // Prevents multiple timers running if timerRunning == false { timerCount = Int(timePicker.countDownDuration) start_time = timerCount timerCount += 1 sessionTime = 3001 timerRunning = true // Timer function buttons startButton.isHidden = true endButton.isHidden = false breakButton.isHidden = false // Hide/show UI elements timePicker.isHidden = true countDownLabel.isHidden = false smartStudyToggle.isUserInteractionEnabled = false smartStudyToggleView.isHidden = true coursePickerButton.isEnabled = false if smartStudyToggle.isOn{ totalTimeLabel.isHidden = false totalTextLabel.isHidden = false } runTimer() } } func runTimer(){ timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(TimerViewController.updateCounter)), userInfo: nil, repeats: true) } func updateCounter() { // Decrement timers timerCount -= 1 sessionTime -= 1 // Smart Study ON - counter with small total timer if smartStudyToggle.isOn{ if (timerCount > sessionTime){ countDownLabel.text = timeString(time: TimeInterval(sessionTime)) totalTimeLabel.text = timeString(time: TimeInterval(timerCount)) } else { countDownLabel.text = timeString(time: TimeInterval(timerCount)) totalTimeLabel.text = timeString(time: TimeInterval(timerCount)) } } // Smart Study OFF else{ countDownLabel.text = timeString(time: TimeInterval(timerCount)) } // Stops the timer when it reaches 0 if timerCount == 0 { timer.invalidate() timerRunning = false // Notification on session completion let alertController = UIAlertController(title: "Session Complete!", message: "Keep studying or take a break?", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("You pressed OK") } alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } } func runBreak(){ breakTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(TimerViewController.updateBreak)), userInfo: nil, repeats: true) } // Used by runBreak() to update counters // and send a notification when the break ends func updateBreak(){ breakTime -= 1 breakTimeLabel.text = timeString(time: TimeInterval(breakTime)) if breakTime <= 0 { breakTimer.invalidate() breakRunning = false let alertController = UIAlertController(title: "Break Ended", message: "Time to study!", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("You pressed OK") } alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } } @IBAction func breakBtnPressed(_ sender: UIButton) { resumeButton.isHidden = false breakButton.isHidden = true timer.invalidate() // Break timer for Smart Study // if statement will prevent multiple timers leading to a sped up timer if breakRunning == false{ breakTime = 600 breakRunning = true // Show the break time timer if smartStudyToggle.isOn{ countDownLabel.isHidden = true breakTimeLabel.isHidden = false if (timerCount > sessionTime){ breakTimeLabel.text = timeString(time: TimeInterval(breakTime)) } else{ breakTime = Int(breakRatio * Double(timerCount)) breakTimeLabel.text = timeString(time: TimeInterval(breakTime)) } } runBreak() } } // Function for resuming the timer @IBAction func resumeBtnPressed(_ sender: UIButton) { breakButton.isHidden = false resumeButton.isHidden = true breakTimeLabel.isHidden = true countDownLabel.isHidden = false breakTimer.invalidate() breakRunning = false runTimer() } // Ends timer and displays the standard timer UI @IBAction func endButtonPressed(_ sender: UIButton) { timer.invalidate() timerRunning = false breakTimer.invalidate() breakRunning = false startButton.isEnabled = false coursePickerButton.isEnabled = true // Timer buttons startButton.isHidden = false endButton.isHidden = true breakButton.isHidden = true resumeButton.isHidden = true // Timer UI labels timePicker.isHidden = false countDownLabel.isHidden = true totalTimeLabel.isHidden = true totalTextLabel.isHidden = true breakTimeLabel.isHidden = true // Button UI smartStudyToggleView.isHidden = false coursePickerButton.isHidden = false smartStudyToggle.isUserInteractionEnabled = true // Save timer values as int and send to Firebase let course = Array(courses.keys)[self.coursePicker.selectedRow(inComponent: 0)] let time = (self.start_time! - self.timerCount) / (60 * 60) if current_user.course[course] == nil { current_user.course[course] = time } else { current_user.course[course] = current_user.course[course]! + time } current_user.localSave() current_user.update() } // Method to format time into HH:MM:SS func timeString(time:TimeInterval) -> String { let hours = Int(time) / 3600 let minutes = Int(time) / 60 % 60 let seconds = Int(time) % 60 return String(format:"%02i:%02i:%02i", hours, minutes, seconds) } /* // 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. } */ }
// // PeripheralsTVC.swift // Bluetooth Scanner // // Created by Pavan Athreya on 01/03/2019. // Copyright (c) 2019 Pavan Athreya. All rights reserved. // import UIKit import CoreBluetooth import CoreLocation //Class for listing the peripherals class PeripheralsTVC: UITableViewController, CBCentralManagerDelegate, CBPeripheralDelegate, CLLocationManagerDelegate { // CoreBluetooth Central Manager static var centralManager:CBCentralManager! // CoreLocation Location Manager var locationManager:CLLocationManager! // All peripherals in Central Manager var peripherals = [CBPeripheral]() // Peripheral chosen by user var connectedPeripheral:CBPeripheral! // MARK: - View Life Cycle //View Did Load override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager.delegate = self locationManager.requestAlwaysAuthorization() // This will trigger centralManagerDidUpdateState PeripheralsTVC.centralManager = CBCentralManager(delegate: self, queue: nil) //centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main) } //View Did Appear override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Re-start scan after coming back from background peripherals.removeAll() if PeripheralsTVC.centralManager.state == .poweredOn { PeripheralsTVC.centralManager.scanForPeripherals(withServices:nil, options: ["CBCentralManagerScanOptionAllowDuplicatesKey" : false]) } } //View Will Disappear override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Stop scan to save battery when entering background PeripheralsTVC.centralManager.stopScan() // Remove all peripherals from the table and array (they will be re-discovered upon viewDidAppear) peripherals.removeAll(keepingCapacity: false) self.tableView.reloadData() } // MARK : - CLLocationManager Delegates //Location manager did change authorization status func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { print("Did update Status: \(status)") } // MARK: - CBCentralManagerDelegate //Central manager did update bluetooth state func centralManagerDidUpdateState(_ central: CBCentralManager) { print("Central Manager did update state") if (central.state == .poweredOn) { print("Bluetooth is powered on") // Scan for any peripherals peripherals.removeAll() PeripheralsTVC.centralManager.scanForPeripherals(withServices: nil, options: ["CBCentralManagerScanOptionAllowDuplicatesKey" : false]) } else { var message = String() switch central.state { case .unsupported: message = "Bluetooth is unsupported" case .unknown: message = "Bluetooth state is unkown" case .unauthorized: message = "Bluetooth is unauthorized" case .poweredOff: message = "Bluetooth is powered off" default: break } print(message) } } //Central manager did discover peripheral func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { print("Peripheral discovered: \(peripheral)") print("Advertisement Data: \(advertisementData)") peripherals.append(peripheral) self.tableView.reloadData() } //Central manager did connect to peripheral func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { print("Peripheral connected: \(String(describing: peripheral))") PeripheralsTVC.centralManager.stopScan() // Keep reference to be used in prepareForSegue self.connectedPeripheral = peripheral performSegue(withIdentifier: "Services", sender: self) } //Central Manager Failed to connect to peripheral func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { print("Peripheral failed to connect: \(peripheral)") } // MARK: - Table view data source //Number of sections in Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } //Number of rows in given section of the table view override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return peripherals.count } //Table View Cell for row at index path override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Peripheral", for: indexPath) as UITableViewCell let p = peripherals[indexPath.row] cell.textLabel?.text = p.name ?? "[Unkown name]" cell.detailTextLabel?.text = "UUID: \(p.identifier.uuidString)" return cell } // MARK: - Table view delegates //Table View did select row at index path override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.connectedPeripheral = peripherals[indexPath.row] print("Tring to connnect to peripheral: \(String(describing: self.connectedPeripheral))") PeripheralsTVC.centralManager.connect(self.connectedPeripheral, options: nil) } // MARK: - Segue //View Controller Prepare for segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let servicesTVC = segue.destination as! ServicesTVC servicesTVC.peripheral = self.connectedPeripheral } }
// // MoreListViewController.swift // PyConJP2016 // // Created by Yutaro Muta on 3/7/16. // Copyright © 2016 PyCon JP. All rights reserved. // import UIKit import WebAPIFramework import SafariServices class MoreListViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - Table View Controller Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let sectionType = SectionType(rawValue: (indexPath as NSIndexPath).section) else { return } let rowType = sectionType.rows[(indexPath as NSIndexPath).row] switch rowType { case .whatsPyConJP, .codeOfConduct, .summary, .license, .staffList: guard let identifier = rowType.identifier, let viewController = self.storyboard?.instantiateViewController(withIdentifier: identifier) else { return } self.navigationController?.pushViewController(viewController, animated: true) case .participantsInformation, .sponsor, .questionnaire, .repository: guard let url = rowType.url else { return } let safariViewController = SFSafariViewController(url: url) self.present(safariViewController, animated: true, completion: nil) case .conferenceMap: let mapListViewController = MapListViewController.build() self.navigationController?.pushViewController(mapListViewController, animated: true) case .sprintMap: let mapViewController = MapViewController.build(venue: MapViewController.Venue.microsoft) self.navigationController?.pushViewController(mapViewController, animated: true) case .library: let acknowledgmentsListViewController = AcknowledgmentsListViewController.build() self.navigationController?.pushViewController(acknowledgmentsListViewController, animated: true) case .feedback: guard let urlSheme = rowType.urlSheme else { return } UIApplication.shared.openURL(urlSheme) tableView.deselectRow(at: indexPath, animated: true) } } private enum SectionType: Int { case about case map case application var rows: Array<RowType> { switch self { case .about: return [.participantsInformation, .whatsPyConJP, .codeOfConduct, .summary, .sponsor, .staffList, .questionnaire] case .map: return [.conferenceMap, .sprintMap] case .application: return [.repository, .library, .license, .feedback] } } } private enum RowType: MailURLSchemeProtocol { case participantsInformation case whatsPyConJP case codeOfConduct case summary case sponsor case staffList case questionnaire case conferenceMap case sprintMap case repository case library case license case feedback var identifier: String? { switch self { case .whatsPyConJP: return "WhatsPyConJPViewController" case .codeOfConduct: return "CodeOfConductViewController" case .summary: return "SummaryViewController" case .license: return "LicenseViewController" case .staffList: return "StaffListViewController" default: return nil } } var url: URL? { switch self { case .participantsInformation: return URL(string: WebConfig.baseURL + "participants/") case .sponsor: return URL(string: WebConfig.baseURL + "sponsors/") case .questionnaire: return URL(string: "https://docs.google.com/forms/d/e/1FAIpQLSefOgaVN8_cwUAcW-NmTaBNoNG8K47vursedtxkE_cbv_E37A/viewform") case .repository: return URL(string: "https://github.com/pyconjp/pyconjp-ios") default: return nil } } var urlSheme: URL? { switch self { case .feedback: return mailURLScheme(to: PCJConfig.mailAddress, subject: "Feedback for PyCon JP 2016 App", body: String(format: "iOS version: %@\nDevice Model: %@\nReply-to:\n\nFeedback:", arguments: [UIDevice.current.systemVersion, UIDevice.current.modelType])) default: return nil } } } }
// // TeamsTableViewCell.swift // AutosportInfo // // Created by Egor Salnikov on 05.10.2020. // Copyright © 2020 Egor Salnikov. All rights reserved. // import UIKit class TeamsTableViewCell: UITableViewCell { @IBOutlet weak var cellView: UIView! @IBOutlet weak var teamName: UILabel! @IBOutlet weak var teamNationalityLabel: UILabel! @IBOutlet weak var countWins: UILabel! @IBOutlet weak var countPoints: UILabel! @IBOutlet weak var countPosition: UILabel! }
// // productsCollectionViewCell.swift // D2020 // // Created by MacBook Pro on 3/10/20. // Copyright © 2020 Abdallah Eslah. All rights reserved. // import UIKit class productsCollectionViewCell: UICollectionViewCell { @IBOutlet weak var productImageView: RoundedImageView! @IBOutlet weak var productNameLabel: UILabel! @IBOutlet weak var productPriceLabel: UILabel! @IBOutlet weak var editButton: UIButton! }
// // Mine.swift // FudanNews // // Created by Lotus on 2016/11/16. // Copyright © 2016年 Fudan University. All rights reserved. // import UIKit import AlamofireImage import MJRefresh class SubscriptionMine: UITableViewController { var dataArray = [Subscription]() var dataArrayAll = [Subscription]() var now = 0 var flag = 0 var rootView: SubscriptionViewController! override func viewWillAppear(_ animated: Bool) { if LocalStorageManager.loadUserLoginInfo() != nil { rootView.button1.alpha = 0 if (dataArray.count == 0) { headerRefresh() return } if (rootView.nowView == 1){ headerRefresh() rootView.nowView = 0 return } var i = -1 for e in dataArray { i += 1 if !e.isSubscribed { dataArray.remove(at: i) dataArrayAll.remove(at: i) break } } now = dataArrayAll.count if now == 0 { rootView.button2.alpha = 1 } else { rootView.button2.alpha = 0 } tableView.reloadData() } else { rootView.button2.alpha = 0 dataArray.removeAll() dataArrayAll.removeAll() now = 0 tableView.reloadData() rootView.button1.alpha = 1 self.tableView.mj_header.endRefreshing() self.tableView.mj_footer.endRefreshing() } } override func viewDidLoad() { super.viewDidLoad() self.tableView!.separatorStyle = UITableViewCellSeparatorStyle.none self.tableView!.delegate = self self.tableView!.dataSource = self self.tableView!.register(UINib(nibName:"SubscriptionMyTableViewCell", bundle:nil), forCellReuseIdentifier:"SubscriptionMyTableViewCell") let header:MJRefreshGifHeader = MJRefreshGifHeader(refreshingTarget: self,refreshingAction:#selector(self.headerRefresh)) self.tableView!.mj_header = header self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self,refreshingAction:#selector(self.headerRefresh)) self.tableView.mj_footer = MJRefreshBackFooter(refreshingTarget: self, refreshingAction: #selector(self.footerRefresh)) self.tableView.backgroundColor = UIColor(red:248/255,green:248/255,blue:248/255,alpha:1) } func footerRefresh() { refreshData() } func headerRefresh(){ dataArrayAll.removeAll() now = 0 refreshData() } func refreshData() { NetworkManager.getMySubscriptionList(startedFrom: self.now, withLimit: 15) { subscriptionList in if let subscriptionList = subscriptionList { for subscription in subscriptionList { self.dataArrayAll.append(subscription) } self.dataArray = self.dataArrayAll self.now = self.dataArrayAll.count if (self.now == 0){ self.rootView.button2.alpha = 1 } else { self.rootView.button2.alpha = 0 } self.tableView.mj_header.endRefreshing() self.tableView.mj_footer.endRefreshing() self.tableView.reloadData() } else { if (self.now == 0){ self.rootView.button2.alpha = 1 } else { self.rootView.button2.alpha = 0 } self.tableView.mj_header.endRefreshing() self.tableView.mj_footer.endRefreshing() } } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:SubscriptionMyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "SubscriptionMyTableViewCell") as! SubscriptionMyTableViewCell cell.content = dataArray[indexPath.row] cell.article = dataArray[indexPath.row].previewArticles cell.prepare() cell.rootView = self.rootView cell.Entry.tag = indexPath.row cell.Entry.addTarget(self, action: #selector(entry), for: .touchUpInside) cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return kScreenWidth/2+40+kScreenWidth/10 } func entry(_sender : UIButton){ rootView.nowView = 0 rootView.performSegue(withIdentifier: "ShowTopic", sender: dataArray[_sender.tag]) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { rootView.nowView = 0 rootView.performSegue(withIdentifier: "ShowTopic", sender: dataArray[indexPath.row]) } }
// // LoginViewController.swift // Frames-App // // Created by Tyler Zhao on 12/5/18. // Copyright © 2018 Tyler Zhao. All rights reserved. // import UIKit import RxSwift import RxCocoa class SignInViewController: UIViewController, StoryboardInitializable { @IBOutlet weak var loginTextField: FramesTextField! @IBOutlet weak var passwordTextField: FramesTextField! @IBOutlet weak var forgotPasswordButton: UIButton! @IBOutlet weak var signInButton: FramesButton! var viewModel: SignInViewModel! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() setup() bindViewModel() } private func setup() { title = "Sign In" } private func bindViewModel() { assert(viewModel != nil) let input = SignInViewModel.Input(signInTrigger: signInButton.rx.tap.asObservable()) let output = viewModel.transform(input: input) } }
// // TimeEntryCellDelegate.swift // MPM-Sft-Eng-Proj // // Created by Sebastian Peden on 9/18/18. // Copyright © 2018 Harrison Ellerm. All rights reserved. // import Foundation import UIKit protocol TimeEntryCellDelegate { func textFieldInCell(cell: TimeEntryCell, editingChangedInTextField newText:String) }
// // Constants.swift // Papr // // Created by Mitchell Sturba on 2020-03-23. // Copyright © 2020 Mitchell Sturba. All rights reserved. // import Foundation struct Constants { struct StoryBoard { static let homeViewController = "HomeVC" } }
// // UIKitExtension.swift // delinshe_ios // // Created by Xu on 2020/9/28. // Copyright © 2020 com.delinshe. All rights reserved. // import UIKit public enum PostingType: String { case all = "default" case note = "note" case value = "value" case remove_mines = "remove_mines" case dynamic = "no_idea" case qa = "interlocution" } extension UIViewController { } // MARK: ShadowLayer class ShadowLayer: CAShapeLayer { @discardableResult func setFrame(_ frame: CGRect)-> ShadowLayer { self.frame = frame return self } @discardableResult func setPath(_ path: CGPath)-> ShadowLayer { self.shadowPath = path return self } @discardableResult func setOpacity(_ opacity: Float)-> ShadowLayer { self.shadowOpacity = opacity return self } @discardableResult func setOffset(_ offset: CGSize)-> ShadowLayer { self.shadowOffset = offset return self } @discardableResult func setColor(_ color: UIColor?, alpha: CGFloat = 1.0)-> ShadowLayer { if color == nil { self.shadowColor = UIColor.black.withAlphaComponent(alpha).cgColor return self } self.shadowColor = color!.withAlphaComponent(alpha).cgColor return self } func done()-> UIView { let view = UIView(frame: self.frame) view.backgroundColor = .clear view.layer.insertSublayer(self, at: 0) return view } } // MARK: UIView extension UIView { // #if DEBUG // @objc open func injected() { // print("injected UIView") // //find now VC // guard let nowVC = UIApplication.shared.keyWindow?.rootViewController else { // return // } // for subV in nowVC.view.subviews { // subV.removeFromSuperview() // } // nowVC.viewDidLoad() // } // #endif /// 部分圆角 /// /// - Parameters: /// - corners: 需要实现为圆角的角,可传入多个 /// - radii: 圆角半径 func corner(byRoundingCorners corners: UIRectCorner, radii: CGFloat) { let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii)) let maskLayer = CAShapeLayer() maskLayer.frame = self.bounds maskLayer.path = maskPath.cgPath self.layer.mask = maskLayer } func setBackgroundGradientColor(colors:[UIColor], startPoint: CGPoint? = nil , endPoint: CGPoint? = nil, locations: [NSNumber]? = nil, cornerRadius: CGFloat) { let gradientLayer1 = CAGradientLayer() gradientLayer1.frame = self.bounds gradientLayer1.colors = colors.map({ (color) -> CGColor in return color.cgColor }) var start_point = CGPoint(x: 0, y: 0) if startPoint != nil { start_point = startPoint! } var end_point = CGPoint(x: 0, y: 1) if endPoint != nil { end_point = endPoint! } gradientLayer1.startPoint = start_point gradientLayer1.endPoint = end_point if locations != nil { gradientLayer1.locations = locations! } gradientLayer1.cornerRadius = cornerRadius self.layer.insertSublayer(gradientLayer1, at: 0) } } // MARK: UIButton extension UIButton { func setGradientColor(colors:[UIColor], startPoint: CGPoint? = nil , endPoint: CGPoint? = nil, locations: [NSNumber]? = nil, cornerRadius: CGFloat) { let gradientLayer1 = CAGradientLayer() gradientLayer1.frame = self.bounds gradientLayer1.colors = colors.map({ (color) -> CGColor in return color.cgColor }) var start_point = CGPoint(x: 0, y: 0) if startPoint != nil { start_point = startPoint! } var end_point = CGPoint(x: 0, y: 1) if endPoint != nil { end_point = endPoint! } var loca:[NSNumber] = [0, 1] if locations != nil { loca = locations! } gradientLayer1.startPoint = start_point gradientLayer1.endPoint = end_point gradientLayer1.locations = loca gradientLayer1.cornerRadius = cornerRadius self.layer.addSublayer(gradientLayer1) } } // MARK: UITableView extension UITableView { // MARK: - Cell register and reuse /** Register cell nib - parameter aClass: class */ func xz_registerCellNib<T: UITableViewCell>(_ aClass: T.Type) { let name = String(describing: aClass) let nib = UINib(nibName: name, bundle: nil) self.register(nib, forCellReuseIdentifier: name) } /** Register cell class - parameter aClass: class */ func xz_registerCellClass<T: UITableViewCell>(_ aClass: T.Type) { let name = String(describing: aClass) self.register(aClass, forCellReuseIdentifier: name) } /** Reusable Cell - parameter aClass: class - returns: cell */ func xz_dequeueReusableCell<T: UITableViewCell>(_ aClass: T.Type) -> T! { let name = String(describing: aClass) guard let cell = dequeueReusableCell(withIdentifier: name) as? T else { fatalError("\(name) is not registed") } return cell } // MARK: - HeaderFooter register and reuse /** Register cell nib - parameter aClass: class */ func xz_registerHeaderFooterNib<T: UIView>(_ aClass: T.Type) { let name = String(describing: aClass) let nib = UINib(nibName: name, bundle: nil) self.register(nib, forHeaderFooterViewReuseIdentifier: name) } /** Register cell class - parameter aClass: class */ func xz_registerHeaderFooterClass<T: UIView>(_ aClass: T.Type) { let name = String(describing: aClass) self.register(aClass, forHeaderFooterViewReuseIdentifier: name) } /** Reusable Cell - parameter aClass: class - returns: cell */ func xz_dequeueReusableHeaderFooter<T: UIView>(_ aClass: T.Type) -> T! { let name = String(describing: aClass) guard let cell = dequeueReusableHeaderFooterView(withIdentifier: name) as? T else { fatalError("\(name) is not registed") } return cell } } // MARK: UIImage extension UIImage { func byAlpha(_ alpha: CGFloat)-> UIImage? { UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0) if let ctx = UIGraphicsGetCurrentContext() { let area = CGRect(x: 0, y: 0, width: size.width, height: size.height) ctx.scaleBy(x: 1, y: -1); ctx.translateBy(x: 0, y: -area.height) ctx.setBlendMode(.multiply) ctx.setAlpha(alpha) ctx.draw(self.cgImage!, in: area) let new = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return new } return nil } } extension Date { /// 获取当前 秒级 时间戳 - 10位 var timeStamp : String { let timeInterval: TimeInterval = self.timeIntervalSince1970 let timeStamp = Int(timeInterval) return "\(timeStamp)" } /// 获取当前 毫秒级 时间戳 - 13位 var milliStamp : String { let timeInterval: TimeInterval = self.timeIntervalSince1970 let millisecond = CLongLong(round(timeInterval*1000)) return "\(millisecond)" } } extension Array { subscript (safe index: Int)-> Element? { return (0..<count).contains(index) ? self[index] : nil } func isNull()-> Bool { if self == nil, self.count <= 0 { return true } return false } } // 数组切片 extension Sequence { func clump(by clumpsize:Int) -> [[Element]] { let slices : [[Element]] = self.reduce(into:[]) { memo, cur in if memo.count == 0 { return memo.append([cur]) } if memo.last!.count < clumpsize { memo.append(memo.removeLast() + [cur]) } else { memo.append([cur]) } } return slices } } extension String { /// 转换成阅读数 1w+ 10w+ 999w+ var convertToReadNumber: String { if let number = self.toFloat() { if number >= 10000 && number < 10000000 { return String(format: "%.1fw", number) }else { if number >= 10000000 { return "999w" } return String(format: "%.f", number) } } return self } var htmlToAttributedString: NSAttributedString? { guard let data = data(using: .utf8) else { return NSAttributedString() } do { return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil) } catch { return NSAttributedString() } } var htmlToString: String { return htmlToAttributedString?.string ?? "" } /// 生成随机字符串 /// /// - Parameters: /// - count: 生成字符串长度 /// - isLetter: false=大小写字母和数字组成,true=大小写字母组成,默认为false /// - Returns: String static func random(_ count: Int, _ isLetter: Bool = false) -> String { var ch: [CChar] = Array(repeating: 0, count: count) for index in 0..<count { var num = isLetter ? arc4random_uniform(58)+65:arc4random_uniform(75)+48 if num>57 && num<65 && isLetter==false { num = num%57+48 } else if num>90 && num<97 { num = num%90+65 } ch[index] = CChar(num) } return String(cString: ch) } static func currenTimeStampString()-> String { let date = Date() let stamp = date.timeIntervalSince1970 return String(stamp) } func toInt() -> Int? { return Int(self) } func toFloat() -> Float? { return Float(self) } func toDouble() -> Double? { return Double(self) } //MARK:- 去除字符串两端的空白字符 func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } func subString(to: Int) -> String { var to = to if to > self.count { to = self.count } return String(self.prefix(to)) } func subString(from: Int) -> String { if from >= self.count { return "" } let startIndex = self.index(self.startIndex, offsetBy: from) let endIndex = self.endIndex return String(self[startIndex..<endIndex]) } func subString(start: Int, end: Int) -> String { if start < end { let startIndex = self.index(self.startIndex, offsetBy: start) let endIndex = self.index(self.startIndex, offsetBy: end) return String(self[startIndex..<endIndex]) } return "" } } extension UIColor { /// 文字-白色 static var app_main_white: UIColor { UIColor(hexString: "#FFFFFF") } /// App主基调 /// 背景色 static var app_main_background: UIColor { UIColor(hexString: "#F8F8F8") } /// 品牌红色 static var app_main_red: UIColor { UIColor(hexString: "#FF323E") } /// 品牌绿色 static var app_main_green: UIColor { UIColor(hexString: "#57D975") } /// 标题文字颜色 static var app_main_title: UIColor { UIColor(hexString: "#333333") } /// 正文颜色 static var app_main_content: UIColor { UIColor(hexString: "#666666") } /// 辅助信息颜色 static var app_main_subinfo: UIColor { UIColor(hexString: "#999999") } /// 分割线颜色 static var app_main_line: UIColor { UIColor(hexString: "#F3F3F3") } /// 按钮背景颜色 static var app_main_buttonBackground: UIColor { UIColor(hexString: "#EEEEEE") } /// 搜素输入框背景颜色 static var app_main_inputboxBackground: UIColor { UIColor(hexString: "#EEEFF3") } static var app_main_thinRed: UIColor { UIColor(hexString: "#FF5656") } open class var live_yellow: UIColor { get { return UIColor(hexString: "#FFC63C") } } open class var live_blue: UIColor { get { return UIColor(hexString: "#66E0E8") } } open class var black_25: UIColor { get { return UIColor(hexString: "#000000").withAlphaComponent(0.25) } } open class var cellAnimatedColor: UIColor { get { return UIColor(hexString: "#f5f5f5") } } static func setColor(hex: String, alpha: @autoclosure() -> CGFloat)-> UIColor { return UIColor(hexString: hex).withAlphaComponent(alpha()) } func createImage(bounds: CGRect)-> UIImage? { var image = UIImage() UIGraphicsBeginImageContext(bounds.size) if let context = UIGraphicsGetCurrentContext() { context.setFillColor(self.cgColor) context.fill(bounds) image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage() UIGraphicsEndImageContext() } return image } } extension UIFont { static var app_main_big: UIFont { .systemFont(ofSize: 18.0) } static var app_main_section: UIFont { .systemFont(ofSize: 16.0) } static var app_main_tab: UIFont { .systemFont(ofSize: 15.0) } static var app_main_title: UIFont { .systemFont(ofSize: 14.0) } static var app_main_content: UIFont { .systemFont(ofSize: 13.0) } static var app_main_subinfo: UIFont { .systemFont(ofSize: 12.0) } var bold: UIFont { .systemFont(ofSize: pointSize, weight: .bold) } var medium: UIFont { .systemFont(ofSize: pointSize, weight: .medium) } var regular: UIFont { .systemFont(ofSize: pointSize, weight: .regular) } }
// // Enums.swift // Adapt // // Created by 599944 on 11/21/18. // Copyright © 2018 TheATeam. All rights reserved. // import Foundation enum SetType { case rep case Tsec case Tmin case distMi case distKm case distM case NA } enum WorkoutType { case superset case fortime case NA } enum Tier1MuscleGroup{ case arms case legs case chest case neck case back case core } enum Tier2MuscleGroup{ case biceps case triceps case forearms case NA } enum WorkoutEquipment { case barbell case dumbell case speedladder case mat case plyobox case propbox case chair case footprop case soupcans } enum WeightStatus { case none case optional case preferred case required }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4