text
stringlengths
8
1.32M
// // ViewController.swift // OrbitIndicator // // Created by Puyan Lin on 2015/8/31. // Copyright (c) 2015年 Puyan. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let orbitIndicatorView : PYOrbitIndicatorView = NSBundle.mainBundle().loadNibNamed("PYOrbitIndicatorView", owner: self, options: nil)[0] as! PYOrbitIndicatorView orbitIndicatorView.frame=self.view.bounds self.view.addSubview(orbitIndicatorView) orbitIndicatorView.rotateTo(degree: 90) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // CadastroItens.swift // hubAPS // // Created by Ian Manor on 9/27/16. // Copyright © 2016 Hilton Pintor Bezerra Leite. All rights reserved. // import Foundation import CoreLocation class CadastroItens { init(repositorio:IRepositorioItens) { self.repositorio = repositorio } var repositorio : IRepositorioItens func inserirItem(item: Item, callback: @escaping (Error?) -> ()) { repositorio.inserirItem(item: item, callback: callback) } /*func solicitarItensPerto(localizacao: CLLocation, callback: @escaping ([Item]) -> ()) { return repositorio.solicitarItensPerto(localizacao: localizacao, callback: callback) }*/ }
// // ScenePassport.swift // projetoWWDC20 // // Created by Gustavo Feliciano Figueiredo on 02/04/20. // Copyright © 2020 Gustavo Feliciano Figueiredo. All rights reserved. // import SpriteKit import GameplayKit class ScenePassport: SceneState{ override func isValidNextState(_ stateClass: AnyClass) -> Bool { return stateClass is SceneNormal.Type } override func didEnter(from previousState: GKState?) { self.sceneGame.character?.isPaused = true self.sceneGame.touristPopUp?.isPaused = true self.sceneGame.passportPopUp?.isHidden = false showStickerInPassport() } override func willExit(to nextState: GKState) { self.sceneGame.character?.removeAllActions() self.sceneGame.passportPopUp?.keyEsc?.alpha = 0 } func showStickerInPassport(){ let passport = self.sceneGame.passportPopUp?.passport let wait = SKAction.wait(forDuration: 2) let fadeAnimation = SKAction.fadeAlpha(to: 1.0, duration: 1.5) let sequence = SKAction.sequence([wait, fadeAnimation]) switch self.sceneGame.character?.position { case CGPoint(x: -195.0, y: -115.0): passport?.stickerIgrejinha.run(sequence) break case CGPoint(x: -15.0, y: -60.0): passport?.stickerSantuario.run(sequence) break case CGPoint(x: -98.0, y: 140.0): passport?.stickerRuaAlegria.run(sequence) break case CGPoint(x: 138.0, y: 155.0): passport?.stickerFeira.run(sequence) break case CGPoint(x: 270, y: 60.0): self.sceneGame.passportPopUp?.keyEsc?.isHidden = true passport?.stickerMinhaCasa.run(sequence){ if let scene = self.sceneGame.endScene{ scene.anchorPoint = CGPoint(x: 0.5, y: 0.5) scene.position = CGPoint(x: 0, y: 0) // Present the scene self.sceneGame.view!.presentScene(scene, transition: SKTransition.crossFade(withDuration: 2)) } } break default: break } self.sceneGame.passportPopUp?.keyEsc?.run(sequence) } }
// // JobTitleTableViewCell.swift // NYC_JOBS_DATA_FINAL // // Created by Jonathan Cravotta on 6/2/18. // Copyright © 2018 Jonathan Cravotta. All rights reserved. // import Foundation import UIKit class JobTitleTableViewCell: UITableViewCell { private let bubbleView = WorkTimeBubbleView() private let titleLabel = UILabel() private let bottomBorder = UIView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setUpView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUpView() { addSubview(bubbleView) addSubview(titleLabel) addSubview(bottomBorder) bubbleView.layer.cornerRadius = 12 titleLabel.font = UIFont.systemFont(ofSize: 22.0, weight: .bold) titleLabel.numberOfLines = 0 bottomBorder.backgroundColor = .lightGray bubbleView.snp.makeConstraints { make in make.top.equalToSuperview().offset(20) make.height.equalTo(24) make.leading.equalTo(titleLabel) } titleLabel.snp.makeConstraints { make in make.top.equalTo(bubbleView.snp.bottom).offset(7) make.width.equalToSuperview().multipliedBy(0.9) make.centerX.equalToSuperview() make.bottom.equalToSuperview().offset(-20) } bottomBorder.snp.makeConstraints { make in make.width.centerX.equalToSuperview() make.height.equalTo(0.5) make.bottom.equalToSuperview() } } func setUp(withTitle title: String, indicator: WorkTimeIndicator) { bubbleView.setUp(with: indicator) titleLabel.text = title } }
// // CreateMemeViewController.swift // MemeMeSandBox // // Created by Dustin Howell on 2/2/17. // Copyright © 2017 Dustin Howell. All rights reserved. // import UIKit class CreateMemeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { // MARK: Outlets @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var topMemeText: UITextField! @IBOutlet weak var bottomMemeText: UITextField! @IBOutlet weak var bottomToolbar: UIToolbar! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var shareButton: UIBarButtonItem! @IBOutlet weak var nightModeToggleButton: UIBarButtonItem! @IBOutlet weak var cancelButton: UIBarButtonItem! @IBOutlet weak var albumButton: UIBarButtonItem! @IBOutlet weak var memeView: UIView! @IBOutlet weak var containerView: UIView! // MARK: Properties var nightMode = true var rootFrameY: CGFloat = 0 var keyboardShow = false // Colors (for night mode implementation) let darkBarColor = UIColor(colorLiteralRed: 56/255, green: 68/255, blue: 79/255, alpha: 1) let darkIconColor = UIColor(colorLiteralRed: 142/255, green: 201/255, blue: 235/255, alpha: 1) let memeTextAttributes: [String:Any] = [ NSStrokeColorAttributeName: UIColor.black, NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont(name: "Impact", size: 40) as Any, NSStrokeWidthAttributeName: -3.0 ] // MARK: Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() shareButton.isEnabled = false // setup font styles topMemeText.configure(delegate: self, defaultAttributes: memeTextAttributes) bottomMemeText.configure(delegate: self, defaultAttributes: memeTextAttributes) topMemeText.textAlignment = .center bottomMemeText.textAlignment = .center // choose color scheme navigationController?.navigationBar.barTintColor = nightMode ? darkBarColor : darkIconColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("CreateMemeController ViewWillAppear") cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) subscribeToKeyboardNotifications() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) rootFrameY = view.frame.origin.y print("rootFrameY is : \(rootFrameY)") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) unsubscribeToKeyboardNotifications() } // MARK: Actions @IBAction func pickImage(_ sender: UIBarButtonItem) { pickImageFromSource(sourceType: .photoLibrary) } @IBAction func takePicture(_ sender: UIBarButtonItem) { pickImageFromSource(sourceType: .camera) } @IBAction func shareMeme(_ sender: UIBarButtonItem) { let memeImage = generateMemedImage() let shareController = UIActivityViewController(activityItems: [memeImage], applicationActivities: nil) shareController.completionWithItemsHandler = { activity, success, items, error in let meme = Meme(topText: self.topMemeText.text!, bottomText: self.bottomMemeText.text!, originalImage: self.imageView.image!, memedImage: memeImage) (UIApplication.shared.delegate as! AppDelegate).memes.append(meme) self.dismiss(animated: true) } self.present(shareController, animated: true) } @IBAction func toggleNightMode(_ sender: UIBarButtonItem) { nightMode = !nightMode let barColor: UIColor let iconColor: UIColor if nightMode { barColor = darkBarColor iconColor = darkIconColor } else { barColor = darkIconColor iconColor = darkBarColor } navigationController?.navigationBar.barTintColor = barColor bottomToolbar.barTintColor = barColor shareButton.tintColor = iconColor nightModeToggleButton.tintColor = iconColor cancelButton.tintColor = iconColor cameraButton.tintColor = iconColor albumButton.tintColor = iconColor } @IBAction func resetUI(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } // MARK: Image Picker Delegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage { imageView.image = image } dismiss(animated: true, completion: nil) return } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) return } // MARK: Text Field Delegate func textFieldDidBeginEditing(_ textField: UITextField) { let currentText = textField.text if currentText == "TOP" || currentText == "BOTTOM" { textField.text = "" } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // MARK: Notification methods func subscribeToKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) } func unsubscribeToKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) } func keyboardWillShow(_ notification: Notification) { print("keyboard will show") if keyboardShow == false { rootFrameY = view.frame.origin.y let newY = rootFrameY - getKeyboardHeight(notification) print("newY is : \(newY)") view.frame.origin.y = newY } keyboardShow = true } func keyboardWillHide(_ notification: Notification) { print("kebyoard will hide") if keyboardShow == true { view.frame.origin.y = rootFrameY } keyboardShow = false } func getKeyboardHeight(_ notification: Notification) -> CGFloat { // detect if the bottom text field is being edited if bottomMemeText.isEditing { let userInfo = notification.userInfo! let keyboardSize = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue return keyboardSize.cgRectValue.height } // do not move view up if the bottom text field is not being edited return 0 } // MARK: Utility Functions private func generateMemedImage() -> UIImage { UIGraphicsBeginImageContext(memeView.frame.size) memeView.drawHierarchy(in: memeView.bounds, afterScreenUpdates: true) let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return memedImage } private func pickImageFromSource(sourceType: UIImagePickerControllerSourceType) { let pickerController = UIImagePickerController() pickerController.delegate = self pickerController.sourceType = sourceType self.present(pickerController, animated: true, completion: { self.shareButton.isEnabled = true }) } }
// // MapTests.swift // Ruins // // Created by Theodore Abshire on 7/7/16. // Copyright © 2016 Theodore Abshire. All rights reserved. // import XCTest @testable import Ruins class MapTests: XCTestCase { var map:Map! var nameMemory:[String]! override func setUp() { super.setUp() map = Map(width: 10, height: 10) //save the name memory to restore after the test nameMemory = MapGenerator.getNameMemory() MapGenerator.clearNameMemory() } override func tearDown() { super.tearDown() //restore the name memory to its previous state MapGenerator.loadNameMemory(nameMemory) } func testWalkable() { XCTAssertFalse(map.tileAt(x: 0, y: 0).walkable) XCTAssertTrue(map.tileAt(x: 1, y: 1).walkable) map.tileAt(x: 1, y: 1).creature = Creature(enemyType: "test creature", level: 1, x: 1, y: 1) XCTAssertFalse(map.tileAt(x: 1, y: 1).walkable) } func testCalculateVisibility() { map.calculateVisibility(x: 1, y: 1) for y in 1..<map.height { for x in 1..<map.width { let xDis = CGFloat(abs(x - 1)) let yDis = CGFloat(abs(y - 1)) let distance = sqrt(xDis * xDis + yDis * yDis) XCTAssertEqual(distance <= visibilityRange, map.tileAt(x: x, y: y).visible) } } } //MARK: map gen tests func testDefaultMapGen() { //it should have borders at all sides XCTAssertTrue(map.tileAt(x: 0, y: 0).solid) XCTAssertTrue(map.tileAt(x: 9, y: 0).solid) XCTAssertTrue(map.tileAt(x: 0, y: 9).solid) XCTAssertTrue(map.tileAt(x: 9, y: 9).solid) XCTAssertFalse(map.tileAt(x: 1, y: 1).solid) } func testMapStubNoRepeatNames() { //generate 10 map stubs with the exact same flavor and theme and make sure there are no repeat names var stubs = [MapStub]() for _ in 0..<10 { stubs.append(MapStub(flavor: "poisonous", theme: "wasteland", level: 1)) } for stub in stubs { for oStub in stubs { if !(stub === oStub) { XCTAssertNotEqual(stub.name, oStub.name) } } } } func testMapStubNameStressTest() { //I don't care if it repeats or not in the stress test //just if it CAN generate hundreds of map stubs of the same type //so it's gotta have some way of noticing that it's out of unique names and going "oh fuck it" and repeating something for _ in 0..<1000 { let _ = MapStub(flavor: "poisonous", theme: "wasteland", level: 1) } } func testMapStubAttributes() { let stub = MapStub(flavor: "poisonous", theme: "wasteland", level: 1) XCTAssertEqual(stub.keywords.count, 2) if stub.keywords.count == 2 { XCTAssertEqual(stub.keywords[0], "criminal") XCTAssertEqual(stub.keywords[1], "poison") } //also make sure that alternate keywords work let stubTwo = MapStub(flavor: "battlefield", theme: "fort", level: 1) XCTAssertEqual(stubTwo.keywords.count, 2) if stubTwo.keywords.count == 2 { XCTAssertEqual(stubTwo.keywords[0], "military") XCTAssertEqual(stubTwo.keywords[1], "stun") } } func testMapStubEnemyList() { //get a map stub that will have both "military" and "criminal" in order to test the overlap let stub = MapStub(flavor: "lawless", theme: "fort", level: 999) XCTAssertEqual(stub.keywords.count, 2) if stub.keywords.count == 2 { XCTAssertEqual(stub.keywords[0], "military") XCTAssertEqual(stub.keywords[1], "criminal") } let enemies = stub.enemyTypes //this shouldn't include the sample monster, because I should have all its keywords commented out XCTAssertEqual(numberOfOccurencesOf(enemies, of: "sample enemy type"), 0) //this should include the hammerman twice, because the hammerman is military and criminal XCTAssertEqual(numberOfOccurencesOf(enemies, of: "hammerman"), 2) //this should include the bandit and fairy musketeer once, because they only match one keyword XCTAssertEqual(numberOfOccurencesOf(enemies, of: "bandit"), 1) XCTAssertEqual(numberOfOccurencesOf(enemies, of: "fairy musketeer"), 1) } func testMapStubTotalEXP() { let lowLevelStub = MapStub(flavor: "lawless", theme: "fort", level: 1) let midLevelStub = MapStub(flavor: "lawless", theme: "fort", level: 20) let highLevelStub = MapStub(flavor: "lawless", theme: "fort", level: 40) XCTAssertEqual(lowLevelStub.totalEXP, 120) XCTAssertEqual(midLevelStub.totalEXP, 500) XCTAssertEqual(highLevelStub.totalEXP, 900) } func testMapStubEnemyListMaxLevel() { let lowLevelStub = MapStub(flavor: "lawless", theme: "fort", level: 1) let lowLevelStubEnemies = lowLevelStub.enemyTypes let midLevelStub = MapStub(flavor: "lawless", theme: "fort", level: 20) let midLevelStubEnemies = midLevelStub.enemyTypes let highLevelStub = MapStub(flavor: "lawless", theme: "fort", level: 40) let highLevelStubEnemies = highLevelStub.enemyTypes XCTAssertGreaterThan(midLevelStubEnemies.count, lowLevelStubEnemies.count) XCTAssertGreaterThan(highLevelStubEnemies.count, midLevelStubEnemies.count) //make sure no list has any enemy higher level than expected func stubTestByLevel(stub:MapStub, enemies:[String]) -> Bool { for enemy in enemies { let level = DataStore.getInt("EnemyTypes", enemy, "level")! if level > stub.level + expLevelAdd { return false } } return true } XCTAssertTrue(stubTestByLevel(lowLevelStub, enemies: lowLevelStubEnemies)) XCTAssertTrue(stubTestByLevel(midLevelStub, enemies: midLevelStubEnemies)) XCTAssertTrue(stubTestByLevel(highLevelStub, enemies: highLevelStubEnemies)) } func testMapStubGeneration() { //you are guaranteed to get no overlap between elements of map stubs //so generate 30 sets of them to try to confirm there's no overlap for _ in 0..<30 { let stubs = MapGenerator.generateMapStubs(0) XCTAssertEqual(stubs.count, numStubs) for stub in stubs { for oStub in stubs { if !(stub === oStub) { //flavor and theme should both be different XCTAssertNotEqual(stub.flavor, oStub.flavor) XCTAssertNotEqual(stub.theme, oStub.theme) XCTAssertGreaterThanOrEqual(stub.level, 2) XCTAssertLessThanOrEqual(stub.level, 3) } } } //for the sake of convenience, just clear the memory between generations //this test isn't to determine what happens when you run out of names MapGenerator.clearNameMemory() } } func testMapRoomCenter() { let room = MapRoom(x: 10, y: 8, width: 4, height: 6, roomClass: .Normal) XCTAssertEqual(room.centerX, 12) XCTAssertEqual(room.centerY, 11) } func testMapRoomContainsPoint() { let room = MapRoom(x: 10, y: 10, width: 10, height: 10, roomClass: .Normal) XCTAssertTrue(room.containsPoint(x: 10, y: 10)) XCTAssertTrue(room.containsPoint(x: 15, y: 15)) XCTAssertFalse(room.containsPoint(x: 9, y: 10)) } func testMapRoomCollide() { let room = MapRoom(x: 10, y: 10, width: 10, height: 10, roomClass: .Normal) XCTAssertTrue(room.collide(MapRoom(x: 0, y: 10, width: 10, height: 10, roomClass: .Normal))) //there needs to be a gap of 1 XCTAssertTrue(room.collide(MapRoom(x: 12, y: 12, width: 6, height: 6, roomClass: .Normal))) //inside XCTAssertFalse(room.collide(MapRoom(x: 0, y: 10, width: 5, height: 10, roomClass: .Normal))) //not inside } func testMapGeneratorRoomsAlgorithmValidity() { let (solidity, width, height, rooms) = MapGenerator.generateRoomsSolidityMap(MapStub(flavor: "lawless", theme: "city", level: 1)) //firstly, there must be a start room and a boss room locateRoomsThenClosure(rooms) { (startRoom, endRoom) in //secondly, run the general validity test self.validityGeneral(solidity, width: width, height: height, startRoom: startRoom, endRoom: endRoom) //finally, this algorithm is guaranteed to not need to be pruned //therefore, try to prune it and see if anything changes let (croppedSolidity, croppedWidth, croppedHeight) = MapGenerator.pruneSolidity(solidity, width: width, height: height) XCTAssertEqual(croppedWidth, width) XCTAssertEqual(croppedHeight, height) for i in 0..<min(croppedSolidity.count, solidity.count) { XCTAssertEqual(croppedSolidity[i], solidity[i]) } } } func testMapGeneratorClip() { let T = true let F = false let oldSolidity = [T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, T, T, T, T, T, F, F, F, F, F, T, T, T, T, T, F, F, F, T, T, T, T, T] let oldWidth = 10 let oldHeight = 6 let newSolidity = [T, T, T, T, T, T, T, T, T, T, T, T, F, T, T, F, F, F, F, F, T, T, F, F, F, T, T, T, T, T, T, T, T, T, T] let newWidth = 7 let newHeight = 5 let (realSolidity, realWidth, realHeight) = MapGenerator.pruneSolidity(oldSolidity, width: oldWidth, height: oldHeight) XCTAssertEqual(newWidth, realWidth) XCTAssertEqual(newHeight, realHeight) XCTAssertEqual(newSolidity.count, realSolidity.count) for i in 0..<min(newSolidity.count, realSolidity.count) { XCTAssertEqual(newSolidity[i], realSolidity[i]) } } func testPlaceTraps() { //trap placement depends heavily on other factors, so generate a functional map to place the traps in let player = Creature(enemyType: "human player", level: 1, x: 0, y: 0) let stub = MapStub(flavor: "lawless", theme: "city", level: 1) let (solidity, width, height, rooms) = MapGenerator.generateRoomsSolidityMap(stub) let tiles = MapGenerator.solidityToTiles(solidity, width: width, height: height, rooms: rooms, stub: stub) MapGenerator.placeCreatures(tiles, width: width, height: height, rooms: rooms, player: player, stub: stub) //now, place traps MapGenerator.placeTraps(tiles, width: width, height: height, stub: stub) //examine the traps placed for validity var numTraps = 0 for y in 0..<height { for x in 0..<width { let tile = tiles[x + y * width] if let trap = tile.trap { numTraps += 1 //first off, a trap cannot be in a non-walkable tile XCTAssertTrue(tile.walkable) //secondly, a trap cannot have a non-walkable tile or a trap in its surroundings for y in y-1...y+1 { for x in x-1...x+1 { let sTile = tiles[x + y * width] if !(tile === sTile) { XCTAssertTrue(sTile.walkable) XCTAssertNil(sTile.trap) } } } //fourthly, it should have an effective trap power of (15 + 2 * level) XCTAssertEqual(trap.trapPower, 17) //fifthly, it should be the right type for the map XCTAssertEqual(trap.type, "paralysis trap") //finally, all pre-generated traps must be non-good XCTAssertFalse(trap.good) } } } //make sure there are enough traps XCTAssertEqual(numTraps, 15) } func testPlaceCreatures() { //just make a big empty rectangle of tiles to place creatures in let size = 40 var tiles = [Tile]() for y in 0..<size { for x in 0..<size { let solid = x == 0 || y == 0 || x == size - 1 || y == size - 1 let tile = Tile(type: solid ? "sample wall" : "sample floor") tiles.append(tile) } } //place creatures in this rectangle let startRoom = MapRoom(x: 1, y: 1, width: 4, height: 4, roomClass: .Start) let endRoom = MapRoom(x: 5, y: 1, width: 4, height: 4, roomClass: .Boss) let roomOne = MapRoom(x: 15, y: 15, width: 3, height: 3, roomClass: .Normal) let roomTwo = MapRoom(x: 15, y: 20, width: 3, height: 3, roomClass: .Normal) let rooms = [startRoom, endRoom, roomOne, roomTwo] let player = Creature(enemyType: "human player", level: 1, x: 0, y: 0) let stub = MapStub(flavor: "lawless", theme: "city", level: 10) MapGenerator.placeCreatures(tiles, width: size, height: size, rooms: rooms, player: player, stub: stub) //first off, the player should now be at startX, startY XCTAssertEqual(player.x, 3) XCTAssertEqual(player.y, 3) XCTAssertTrue((tiles[3 + 3 * size].creature === player)) //secondly, there should be a boss at the center of the end room let cr = tiles[7 + 3 * size].creature XCTAssertNotNil(cr) if let cr = cr { XCTAssertTrue(cr.boss) } //thirdly, make sure that all the non-player, non-boss enemies generated are in the possible generation list let enemyTypes = stub.enemyTypes var totalEXP = 0 var roomOneHasEnemy = false var roomTwoHasEnemy = false for tile in tiles { if let creature = tile.creature { if !creature.good && !creature.boss { totalEXP += MapGenerator.expValueForEnemyType(creature.enemyType) var isPossibleType = false for enemyType in enemyTypes { if creature.enemyType == enemyType { isPossibleType = true break } } XCTAssertTrue(isPossibleType) //test to make sure it's inside roomOne or roomTwo let rOHE = roomOne.containsPoint(x: creature.x, y: creature.y) let rTHE = roomTwo.containsPoint(x: creature.x, y: creature.y) roomOneHasEnemy = roomOneHasEnemy || rOHE roomTwoHasEnemy = roomTwoHasEnemy || rTHE XCTAssertTrue(rOHE || rTHE) } } } //make sure if roomOne and roomTwo both have at least one enemy inside XCTAssertTrue(roomOneHasEnemy) XCTAssertTrue(roomTwoHasEnemy) //make sure that the enemies ENEMY TYPE levels add up to the proper amount for generation //a little bit under anyway, ideally XCTAssertLessThanOrEqual(totalEXP, stub.totalEXP) XCTAssertGreaterThan(totalEXP, stub.totalEXP / 2) } func testPlacePits() { let T = true let F = false let solidity = [T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F] let megastructure = [T, T, T, F, F, F, T, T, T, F, F, F, T, T, T, F, F, F, T, T, T, F, F, F, T, T, T, F, F, F, T, T, T, F, F, F] let width = 6 let height = 6 let pit = MapGenerator.makePits(solidity, width: width, height: height, megastructure: megastructure, stub: MapStub(flavor: "lawless", theme: "cave", level: 1)) XCTAssertEqual(pit.count, solidity.count) if pit.count == solidity.count { //I can't guarantee the number of pits, because it might try to extend the pit into an invalid area and get over-written //I can only guarantee there will be A pit var hasPit = false for i in 0..<solidity.count { if pit[i] { //the tile must be solid, and free of megastructures XCTAssertTrue(solidity[i]) XCTAssertFalse(megastructure[i]) hasPit = true } } XCTAssertTrue(hasPit) } } func testPlaceDifficultTerrain() { let T = true let F = false let solidity = [T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F] let megastructure = [T, T, T, F, F, F, T, T, T, F, F, F, T, T, T, F, F, F, T, T, T, F, F, F, T, T, T, F, F, F, T, T, T, F, F, F] let width = 6 let height = 6 let difficult = MapGenerator.makeDifficultTiles(solidity, width: width, height: height, megastructure: megastructure, stub: MapStub(flavor: "lawless", theme: "cave", level: 1)) XCTAssertEqual(difficult.count, solidity.count) if difficult.count == solidity.count { var numDifficult = 0 for i in 0..<solidity.count { if difficult[i] { //the tile can't be solid OR home to a megastructure XCTAssertFalse(solidity[i]) XCTAssertFalse(megastructure[i]) numDifficult += 1 } } //with the cave scheme, and with exactly 9 difficult tiles, there should be exactly 3 difficult tiles XCTAssertEqual(numDifficult, 3) } } func testSolidityToTiles() { let T = true let F = false let solidity = [T, T, T, T, T, T, T, T, F, F, F, F, T, T, T, F, T, T, F, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, F, F, F, F, T, T, F, F, F, F, F, T, T, F, F, F, F, F, T, T, F, F, F, F, F, T, T, F, F, F, F, F, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, ] let width = 7 let height = 12 let rooms = [MapRoom(x: 0, y: 4, width: endRoomSize, height: endRoomSize, roomClass: MapRoomClass.Boss)] let tiles = MapGenerator.solidityToTiles(solidity, width: width, height: height, rooms: rooms, stub: MapStub(flavor: "lawless", theme: "cave", level: 1)) //note that the boss room megastructure will clear a 5x5 area in the 7x7 boss room //even if the boss room is entirely solid wall, because it's over-writing tiles //test to see if the solidity matches XCTAssertEqual(tiles.count, solidity.count) var tileTypes = Set<String>() for i in 0..<min(tiles.count, solidity.count) { XCTAssertEqual(solidity[i], tiles[i].solid) tileTypes.insert(tiles[i].type) } //test to see if the tiles are using the appropriate tilesets //including the boss room tiles XCTAssertTrue(tileTypes.contains("cave wall")) XCTAssertTrue(tileTypes.contains("cave floor")) XCTAssertTrue(tileTypes.contains("pit")) XCTAssertTrue(tileTypes.contains("rubble floor")) for i in 1...7 { XCTAssertTrue(tileTypes.contains("throne \(i)")) } XCTAssertTrue(tileTypes.contains("warning floor")) } func testEnemyTypeEXPValue() { XCTAssertEqual(MapGenerator.expValueForEnemyType("bandit"), 12) //enemy with armor XCTAssertEqual(MapGenerator.expValueForEnemyType("rat"), 7) //enemy without armor XCTAssertEqual(MapGenerator.expValueForEnemyType("pixie"), 26) //enemy who ignores terrain XCTAssertEqual(MapGenerator.expValueForEnemyType("hoop snake"), 28) //enemy with extra movement XCTAssertEqual(MapGenerator.expValueForEnemyType("shambler"), 4) //enemy with less movement XCTAssertEqual(MapGenerator.expValueForEnemyType("scout"), 19) //enemy with magic } //MARK: pathfinding tests func testPathfindingStraightLine() { let person = Creature(enemyType: "test pzombie", level: 1, x: 1, y: 1) map.tileAt(x: 1, y: 1).creature = person map.pathfinding(person, movePoints: 4, ignoreTerrainCosts: false) XCTAssertEqual(map.tilesAccessable.count, 15) //from this position, with no obstacles, it should be able to reach 15 tiles //P**** (the starting tile is considered accessable, so that makes 15) //**** //*** //** //* //these are spots you can just barely reach comparePathToExpected(toX: 5, toY: 1, expected: [(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]) comparePathToExpected(toX: 1, toY: 5, expected: [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)]) //this is a spot that's too far XCTAssertNil(map.pathResultAt(x: 6, y: 1)) } func testPathfindingAvoidTrap() { //place a trap just to the right of the person //this should make it very hard to path to anywhere on the right map.tileAt(x: 2, y: 1).trap = Trap(type: "sample trap", trapPower: 10, good: true) let person = Creature(enemyType: "test pzombie", level: 1, x: 1, y: 1) map.tileAt(x: 1, y: 1).creature = person map.pathfinding(person, movePoints: 4, ignoreTerrainCosts: false) //when asked to move to x=3, you should walk over the trap because it's a player trap and just adds 1 move cost comparePathToExpected(toX: 3, toY: 1, expected: [(1, 1), (2, 1), (3, 1)]) //you can't quite reach x=5, because of the effective extra cost XCTAssertNil(map.pathResultAt(x: 5, y: 1)) //now replace that trap with a world trap //the AI should avoid this much more strictly map.tileAt(x: 2, y: 1).trap = Trap(type: "sample trap", trapPower: 10, good: false) map.pathfinding(person, movePoints: 4, ignoreTerrainCosts: false) //now when asked to move to x=3, you should walk around the trap comparePathToExpected(toX: 3, toY: 1, expected: [(1, 1), (1, 2), (2, 2), (3, 2), (3, 1)]) } //TODO: future pathfinding tests: // what if there's difficult terrain? // furthermore, make sure "ignore terrain costs" works // what if there's walls in the way? //MARK: helper functions func validityGeneral(solidity:[Bool], width:Int, height:Int, startRoom:MapRoom, endRoom:MapRoom) { //all non-solid tiles must be accessable //(number of accessable tiles will be 0 if the start is solid) XCTAssertEqual(self.numberOfNonSolidTiles(solidity), self.numberOfAccessableTiles(solidity, startX: startRoom.centerX, startY: startRoom.centerY, width: width, height: height)) //the end area must be an (endRoomSize x endRoomSize) square of non-solid tiles, with only one non-solid tile in the border var innerSolid = 0 var outerSolid = 0 for y in -1..<endRoomSize+1 { for x in -1..<endRoomSize+1 { if solidity[(x + endRoom.x) + (y + endRoom.y) * width] { outerSolid += 1 if !(y == -1 || x == -1 || x == endRoomSize || y == endRoomSize) { innerSolid += 1 } } } } XCTAssertEqual(innerSolid, 0) XCTAssertEqual(outerSolid, endRoomSize * 4 + 4 - 1) //endRoomSize * 4 is the edges, + 4 is the corners, - 1 is the one tile entrance XCTAssertEqual(endRoom.width, endRoomSize) XCTAssertEqual(endRoom.height, endRoomSize) } func locateRoomsThenClosure(rooms:[MapRoom], closure:(startRoom:MapRoom, endRoom:MapRoom)->()) { var startRoom:MapRoom? var endRoom:MapRoom? for room in rooms { switch (room.roomClass) { case .Start: startRoom = room case .Boss: endRoom = room default: break } } XCTAssertNotNil(startRoom) XCTAssertNotNil(endRoom) if let startRoom = startRoom, endRoom = endRoom { closure(startRoom: startRoom, endRoom: endRoom) } } func numberOfNonSolidTiles(solidity:[Bool]) -> Int { var nonSolid = 0 for solid in solidity { if !solid { nonSolid += 1 } } return nonSolid } func numberOfAccessableTiles(solidity:[Bool], startX:Int, startY:Int, width:Int, height:Int) -> Int { var accessable = [Bool]() for _ in solidity { accessable.append(false) } func exploreAround(x x:Int, y:Int) { if x >= 0 && y >= 0 && x < width && y < height { let i = x + y * width if !accessable[i] && !solidity[i] { accessable[i] = true exploreAround(x: x - 1, y: y) exploreAround(x: x + 1, y: y) exploreAround(x: x, y: y - 1) exploreAround(x: x, y: y + 1) } } } exploreAround(x: startX, y: startY) var numAcc = 0 for acc in accessable { if acc { numAcc += 1 } } return numAcc } func comparePathToExpected(toX x:Int, toY y:Int, expected:[(Int, Int)]) { var expected = expected var x = x var y = y while expected.count > 1 { if let result = map.pathResultAt(x: x, y: y) { expected.removeLast() XCTAssertEqual(result.backX, expected.last!.0) XCTAssertEqual(result.backY, expected.last!.1) x = result.backX y = result.backY if x != expected.last!.0 || y != expected.last!.1 { return } } else { XCTAssertTrue(false) return } } } func numberOfOccurencesOf(array:[String], of:String) -> Int { var occ = 0 for value in array { if value == of { occ += 1 } } return occ } }
import PEUtils func solve(n : Int) -> Int { if let sv = TotientSieve(n: n) { var min_i = 0 var min_ratio = Double(n) for i in 2 ..< n { let df_i = DigitFrequency(n: i) let df_totient_i = DigitFrequency(n: sv[i]) if df_i == df_totient_i { let ratio = Double(i) / Double(sv[i]) if ratio < min_ratio { min_ratio = ratio min_i = i } } } return min_i } return 0 } func main(args : [String]) { if args.count < 2 { print("Usage: \(args[0]) <n : Int>") } else { let n_opt = Int(args[1]) if let n = n_opt { let result = solve(n: n) print(result) } } } main(args: CommandLine.arguments)
// // XCTUIElement.swift // ClearScoreUITests // // Created by Sagar Patel on 06/12/2019. // Copyright © 2019 Sagar Patel. All rights reserved. // import XCTest extension XCUIElement { // Syntesise pull to refresh func pullToRefresh() { let start = coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0)) let finish = coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 6)) start.press(forDuration: 0, thenDragTo: finish) } }
// // localethingUITests.swift // localethingUITests // // Created by Akhil Gundawar on 07/07/20. // Copyright © 2020 Idontknowsomething. All rights reserved. // import XCTest class localethingUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func launchAppWithLocale(userApp: XCUIApplication, locale: String) { let locale = locale userApp.launchArguments += ["-AppleLocale", "\"\(locale)\""] userApp.launch() } func launchAppWithLocaleLanguage(userApp: XCUIApplication, lang: String, locale: String) { let deviceLanguage = lang let locale = locale userApp.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))", "-AppleLocale", "\"\(locale)\""] userApp.launch() } func launchAppWithLocaleLanguageKeyboard(userApp: XCUIApplication, lang: String, locale: String, keyboard: String) { let deviceLanguage = lang let locale = locale userApp.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))", "-AppleLocale", "\"\(locale)\"", "-AppleKeyboards", "(\(keyboard))"] userApp.launch() } func testDefaultAppLaunch() { let app = XCUIApplication() app.launch() let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testDefaultAppLaunch") sleep(5) } func testESLocaleLanguage() { let app = XCUIApplication() let deviceLanguage = "es" let locale = "es_ES" launchAppWithLocaleLanguage(userApp: app, lang: deviceLanguage, locale: locale) XCTAssert(app.staticTexts["es"].exists) XCTAssert(app.staticTexts["en_ES"].exists) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testESLocaleLanguage") sleep(5) } func testIELocaleLanguage() { let app = XCUIApplication() let deviceLanguage = "en" let locale = "en_IE" launchAppWithLocaleLanguage(userApp: app, lang: deviceLanguage, locale: locale) XCTAssert(app.staticTexts["en"].exists) XCTAssert(app.staticTexts["en_IE"].exists) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testIELocaleLanguage") sleep(5) } func testUSLocaleLanguage() { let app = XCUIApplication() let deviceLanguage = "en-US" let locale = "en_US" launchAppWithLocaleLanguage(userApp: app, lang: deviceLanguage, locale: locale) XCTAssert(app.staticTexts["en-US"].exists) XCTAssert(app.staticTexts["en_US"].exists) print(app.debugDescription) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testUSLocaleLanguage") sleep(5) } func testESLocale() { let app = XCUIApplication() let locale = "es_ES" launchAppWithLocale(userApp: app, locale: locale) XCTAssert(app.staticTexts["en_ES"].exists) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testESLocale") sleep(5) } func testIELocale() { let app = XCUIApplication() let locale = "en_IE" launchAppWithLocale(userApp: app, locale: locale) XCTAssert(app.staticTexts["en_IE"].exists) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testIELocale") sleep(5) } func testUSLocale() { let app = XCUIApplication() let locale = "en_US" launchAppWithLocale(userApp: app, locale: locale) XCTAssert(app.staticTexts["en_US"].exists) print(app.debugDescription) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testUSLocale") sleep(5) } func testUSLocaleLanguageKeyboard() { let app = XCUIApplication() let deviceLanguage = "en-US" let locale = "en_US" let keyboard = "en_US@sw=QWERTY;hw=Automatic" launchAppWithLocaleLanguageKeyboard(userApp: app, lang: deviceLanguage, locale: locale, keyboard: keyboard) XCTAssert(app.staticTexts["en-US"].exists) XCTAssert(app.staticTexts["en_US"].exists) print(app.debugDescription) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testUSLocaleLanguageKeyboard") sleep(5) } func testIELocaleLanguageKeyboard() { let app = XCUIApplication() let deviceLanguage = "en" let locale = "en_IE" let keyboard = "en_GB" launchAppWithLocaleLanguageKeyboard(userApp: app, lang: deviceLanguage, locale: locale, keyboard: keyboard) XCTAssert(app.staticTexts["en"].exists) XCTAssert(app.staticTexts["en_IE"].exists) print(app.debugDescription) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testIELocaleLanguageKeyboard") sleep(5) } func testUSLocaleLanguageDummyKeyboard() { let app = XCUIApplication() let deviceLanguage = "en-US" let locale = "en_US" let keyboard = "dummy_keyboard" launchAppWithLocaleLanguageKeyboard(userApp: app, lang: deviceLanguage, locale: locale, keyboard: keyboard) XCTAssert(app.staticTexts["en-US"].exists) XCTAssert(app.staticTexts["en_US"].exists) print(app.debugDescription) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testUSLocaleLanguageDummyKeyboard") sleep(5) } func testIELocaleLanguageDummyKeyboard() { let app = XCUIApplication() let deviceLanguage = "en" let locale = "en_IE" let keyboard = "dummy_keyboard" launchAppWithLocaleLanguageKeyboard(userApp: app, lang: deviceLanguage, locale: locale, keyboard: keyboard) XCTAssert(app.staticTexts["en"].exists) XCTAssert(app.staticTexts["en_IE"].exists) print(app.debugDescription) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testIELocaleLanguageDummyKeyboard") sleep(5) } func testUSLocaleLanguageWithGBKeyboard() { let app = XCUIApplication() let deviceLanguage = "en-US" let locale = "en_US" let keyboard = "en_GB" launchAppWithLocaleLanguageKeyboard(userApp: app, lang: deviceLanguage, locale: locale, keyboard: keyboard) XCTAssert(app.staticTexts["en-US"].exists) XCTAssert(app.staticTexts["en_US"].exists) print(app.debugDescription) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testUSLocaleLanguageWithGBKeyboard") sleep(5) } func testIELocaleLanguageWithUSKeyboard() { let app = XCUIApplication() let deviceLanguage = "en" let locale = "en_IE" let keyboard = "en_US" launchAppWithLocaleLanguageKeyboard(userApp: app, lang: deviceLanguage, locale: locale, keyboard: keyboard) XCTAssert(app.staticTexts["en"].exists) XCTAssert(app.staticTexts["en_IE"].exists) print(app.debugDescription) let textField = app.textFields["Enter text"] textField.tap() textField.typeText("testIELocaleLanguageWithUSKeyboard") sleep(5) } }
// // ProductDAO.swift // ios-sklep // // Created by Berry Bonton on 01/07/2017. // Copyright © 2017 jarep. All rights reserved. // import Foundation import CoreData import UIKit class ProductDAO { var context: NSManagedObjectContext? = nil init(appcontext: NSManagedObjectContext) { context = appcontext } func getProducts() -> [NSManagedObject] { var products:[NSManagedObject] = [] let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Product") do { products = try context!.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } return products; } func fetchProducts(){ let json = JSON() json.fetchProductJSON{ products in for product in products { let productDict = product as! NSDictionary let title = productDict.value(forKey: "title") let id = productDict.value(forKey: "id") as! String if(!self.existsProduct(id: id)){ print("Adding product: \(String(describing: title)) into db") let newProduct = Product(context: self.context!) newProduct.id = Int32(productDict.value(forKey: "id") as! String)! newProduct.title = productDict.value(forKey: "title") as! String? newProduct.desc = productDict.value(forKey: "desc") as! String? newProduct.imgUrl = productDict.value(forKey: "imgUrl") as! String? newProduct.categoryId = Int32(productDict.value(forKey: "categoryId") as! String)! newProduct.price = productDict.value(forKey: "price") as! String? self.addProduct(newProduct: newProduct) } else { print("Product \(String(describing: title)) already exists") } } } } func existsProduct(id: String) -> Bool { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Product") request.predicate = NSPredicate(format: "id=%@", id) do { let count = try self.context?.count(for: request) if count! > 0 {return true} } catch { print("Blad.") } return false } func addProduct(newProduct: Product) { do { context?.insert(newProduct) try context?.save() } catch { fatalError("Failure to save context: \(error)") } } func getProductsByCategoryId(categoryId: String) -> [NSManagedObject] { var products:[NSManagedObject] = [] let request = NSFetchRequest<NSManagedObject>(entityName: "Product") request.predicate = NSPredicate(format: "categoryId=%@", categoryId) do { products = try context!.fetch(request) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } return products; } }
// // Functions.swift // GPS Averager // // Created by Mollie on 1/25/15. // Copyright (c) 2015 Proximity Viz LLC. All rights reserved. // import UIKit class Functions: NSObject { class func formatCoordinateString(lat lat: Double, lon: Double) -> (latitude: Double, longitude: Double, latString: String, lonString: String) { let decimalPlaces = 1000000.0 let latitude = round(lat * decimalPlaces) / decimalPlaces let longitude = round(lon * decimalPlaces) / decimalPlaces var latString:String var lonString:String var latZero:String var lonZero:String var latDeg:Int var lonDeg: Int switch coordFormat { case "Decimal minutes" : if latitude < 0 { latDeg = Int(floor(abs(latitude))) * -1 } else { latDeg = Int(floor(latitude)) } if longitude < 0 { lonDeg = Int(floor(abs(longitude))) * -1 } else { lonDeg = Int(floor(longitude)) } let latMin = fabs(latitude % 1) * 60 let lonMin = fabs(longitude % 1) * 60 let latMinRound = round(latMin * 100000.0) / 100000.0 let lonMinRound = round(lonMin * 100000.0) / 100000.0 if latMinRound < 10 {latZero = "0"} else {latZero = ""} if lonMinRound < 10 {lonZero = "0"} else {lonZero = ""} latString = "\(latDeg)\u{00B0} \(latZero)\(latMinRound)'" lonString = "\(lonDeg)\u{00B0} \(lonZero)\(lonMinRound)'" case "Degrees, minutes, seconds" : var latSecZero:String var lonSecZero:String if latitude < 0 { latDeg = Int(floor(abs(latitude))) * -1 } else { latDeg = Int(floor(latitude)) } if longitude < 0 { lonDeg = Int(floor(abs(longitude))) * -1 } else { lonDeg = Int(floor(longitude)) } let latMin = Int(floor(fabs(latitude % 1) * 60)) let lonMin = Int(floor(fabs(longitude % 1) * 60)) if latMin < 10 {latZero = "0"} else {latZero = ""} if lonMin < 10 {lonZero = "0"} else {lonZero = ""} let latSec = ((fabs(latitude % 1) * 60) % 1) * 60 let lonSec = ((fabs(longitude % 1) * 60) % 1) * 60 let latSecRound = round(latSec * 100.0) / 100.0 let lonSecRound = round(lonSec * 100.0) / 100.0 if latSecRound < 10 {latSecZero = "0"} else {latSecZero = ""} if lonSecRound < 10 {lonSecZero = "0"} else {lonSecZero = ""} latString = "\(latDeg)\u{00B0} \(latZero)\(latMin)' \(latSecZero)\(latSecRound)\"" lonString = "\(lonDeg)\u{00B0} \(lonZero)\(lonMin)' \(lonSecZero)\(lonSecRound)\"" default: if latitude * decimalPlaces % 100 == 0 { latZero = "00" } else if latitude * decimalPlaces % 10 == 0 { latZero = "0" } else { latZero = "" } if longitude * decimalPlaces % 100 == 0 { lonZero = "00" } else if longitude * decimalPlaces % 10 == 0 { lonZero = "0" } else { lonZero = "" } latString = "\(latitude)\(latZero)\u{00B0}" lonString = "\(longitude)\(lonZero)\u{00B0}" } return (latitude, longitude, latString, lonString) } class func averageCoordinates(latitudes: [Double], longitudes: [Double]) -> (avgLat: Double, avgLon: Double) { let π = M_PI var avgX = 0 as Double var avgY = 0 as Double var avgZ = 0 as Double var avgLat = 0 as Double var avgLon = 0 as Double for (var i = 0; i < latitudes.count; i++) { // calculate cartesian coordinates let radLat = latitudes[i] * π / 180 let radLon = longitudes[i] * π / 180 // w1 & w2 = 0 // calculate weighted average avgX += (cos(radLat) * cos(radLon)) avgY += (cos(radLat) * sin(radLon)) avgZ += sin(radLat) } // divide to get average avgX /= Double(latitudes.count) avgY /= Double(latitudes.count) avgZ /= Double(latitudes.count) // convert to lat & long, in degrees avgLat = atan2(avgZ, sqrt(avgX * avgX + avgY * avgY)) * 180 / π avgLon = atan2(avgY, avgX) * 180 / π return (avgLat, avgLon) } class func averageOf(numbers: [Float]) -> Float { if numbers.count == 0 { return 0 } var sum:Float = 0 for number in numbers { sum += number } return (sum / Float(numbers.count)) } }
// // Copyright (c) 2023 Related Code - https://relatedcode.com // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import SideMenu import GraphQLite //----------------------------------------------------------------------------------------------------------------------------------------------- class DirectsView: UIViewController { @IBOutlet private var searchBar: UISearchBar! @IBOutlet private var tableView: UITableView! private var observerDirect: String? private var observerDetail: String? private var observerUser: String? private var dbdirects: [DBDirect] = [] //------------------------------------------------------------------------------------------------------------------------------------------- override init(nibName: String?, bundle: Bundle?) { super.init(nibName: nibName, bundle: bundle) tabBarItem.image = UIImage(systemName: "text.bubble") tabBarItem.title = "Directs" NotificationCenter.addObserver(self, selector: #selector(actionCleanup), text: Notifications.UserWillLogout) } //------------------------------------------------------------------------------------------------------------------------------------------- required init?(coder: NSCoder) { super.init(coder: coder) } //------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() title = "Directs" let image = UIImage(systemName: "square.grid.2x2") navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil) navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(actionWorkspaces)) searchBar.setImage(UIImage(), for: .search, state: .normal) tableView.register(UINib(nibName: "DirectsCell", bundle: nil), forCellReuseIdentifier: "DirectsCell") tableView.tableFooterView = UIView() } //------------------------------------------------------------------------------------------------------------------------------------------- override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if (GQLAuth.userId() != "") { loadDirects() createObserver() } } //------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (GQLAuth.userId() != "") { if (Workspace.id() != "") { } else { Workspace.select(self) } } else { Users.login(self) } } } // MARK: - Database methods //----------------------------------------------------------------------------------------------------------------------------------------------- extension DirectsView { //------------------------------------------------------------------------------------------------------------------------------------------- func loadDirects() { dbdirects.removeAll() let userId = GQLAuth.userId() let text = searchBar.text ?? "" let arguments: [String: Any] = [":workspaceId": Workspace.id(), ":userId": "%\(userId)%", ":text": "%\(text)%"] let condition = "workspaceId = :workspaceId AND active LIKE :userId AND lastMessageText LIKE :text" dbdirects = DBDirect.fetchAll(gqldb, condition, arguments, order: "updatedAt DESC") tableView.reloadData() } //------------------------------------------------------------------------------------------------------------------------------------------- func createObserver() { let types: [GQLObserverType] = [.insert, .update] if (observerDirect == nil) { observerDirect = DBDirect.createObserver(gqldb, types) { method, objectId in DispatchQueue.main.async { self.loadDirects() } } } if (observerDetail == nil) { let condition = String(format: "OBJ.userId = '%@'", GQLAuth.userId()) observerDetail = DBDetail.createObserver(gqldb, types, condition) { method, objectId in DispatchQueue.main.async { self.tableView.reloadData() } } } if (observerUser == nil) { observerUser = DBUser.createObserver(gqldb, types) { method, objectId in DispatchQueue.main.async { self.tableView.reloadData() } } } } } // MARK: - User actions //----------------------------------------------------------------------------------------------------------------------------------------------- extension DirectsView { //------------------------------------------------------------------------------------------------------------------------------------------- @objc func actionWorkspaces() { let workspacesView = WorkspacesView() let sideMenu = SideMenuNavigationController(rootViewController: workspacesView) sideMenu.sideMenuDelegate = self sideMenu.leftSide = true sideMenu.statusBarEndAlpha = 0 sideMenu.presentationStyle = .viewSlideOut sideMenu.presentationStyle.onTopShadowOpacity = 2.0 sideMenu.menuWidth = UIScreen.main.bounds.size.width * 0.9 present(sideMenu, animated: true) } //------------------------------------------------------------------------------------------------------------------------------------------- func actionChatDirect(_ dbdirect: DBDirect) { view.endEditing(true) let chatDirectView = ChatDirectView(dbdirect.objectId, dbdirect.userId()) chatDirectView.hidesBottomBarWhenPushed = true navigationController?.pushViewController(chatDirectView, animated: true) } } // MARK: - Cleanup methods //----------------------------------------------------------------------------------------------------------------------------------------------- extension DirectsView { //------------------------------------------------------------------------------------------------------------------------------------------- @objc func actionCleanup() { DBDirect.removeObserver(gqldb, observerDirect) DBDetail.removeObserver(gqldb, observerDetail) DBUser.removeObserver(gqldb, observerUser) observerDirect = nil observerDetail = nil observerUser = nil dbdirects.removeAll() tableView.reloadData() } } // MARK: - SideMenuNavigationControllerDelegate //----------------------------------------------------------------------------------------------------------------------------------------------- extension DirectsView: SideMenuNavigationControllerDelegate { //------------------------------------------------------------------------------------------------------------------------------------------- func sideMenuWillAppear(menu: SideMenuNavigationController, animated: Bool) { } //------------------------------------------------------------------------------------------------------------------------------------------- func sideMenuDidAppear(menu: SideMenuNavigationController, animated: Bool) { } //------------------------------------------------------------------------------------------------------------------------------------------- func sideMenuWillDisappear(menu: SideMenuNavigationController, animated: Bool) { loadDirects() } //------------------------------------------------------------------------------------------------------------------------------------------- func sideMenuDidDisappear(menu: SideMenuNavigationController, animated: Bool) { } } // MARK: - UIScrollViewDelegate //----------------------------------------------------------------------------------------------------------------------------------------------- extension DirectsView: UIScrollViewDelegate { //------------------------------------------------------------------------------------------------------------------------------------------- func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { view.endEditing(true) } } // MARK: - UITableViewDataSource //----------------------------------------------------------------------------------------------------------------------------------------------- extension DirectsView: UITableViewDataSource { //------------------------------------------------------------------------------------------------------------------------------------------- func numberOfSections(in tableView: UITableView) -> Int { return 1 } //------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dbdirects.count } //------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DirectsCell", for: indexPath) as! DirectsCell let dbdirect = dbdirects[indexPath.row] cell.bindData(dbdirect) return cell } } // MARK: - UITableViewDelegate //----------------------------------------------------------------------------------------------------------------------------------------------- extension DirectsView: UITableViewDelegate { //------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let dbdirect = dbdirects[indexPath.row] actionChatDirect(dbdirect) } } // MARK: - UISearchBarDelegate //----------------------------------------------------------------------------------------------------------------------------------------------- extension DirectsView: UISearchBarDelegate { //------------------------------------------------------------------------------------------------------------------------------------------- func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { loadDirects() } //------------------------------------------------------------------------------------------------------------------------------------------- func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } //------------------------------------------------------------------------------------------------------------------------------------------- func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } //------------------------------------------------------------------------------------------------------------------------------------------- func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = "" searchBar.resignFirstResponder() loadDirects() } //------------------------------------------------------------------------------------------------------------------------------------------- func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } }
// // PurchasedTableViewController.swift // Shopping // // Created by ahmed on 17/02/2021. // Copyright © 2021 ahmed. All rights reserved. // import UIKit import JGProgressHUD class PurchasedTableViewController: UITableViewController { // MARK: - VARS var itemArray:[Items]=[] let hud = JGProgressHUD(style: .dark) // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() tableView.rowHeight = 80 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) loadItem() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return itemArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ItemsTableViewCell cell.generateCell(item: itemArray[indexPath.row]) return cell } // MARK: - Helpers private func loadItem(){ downloadItems(User.currentUser()!.purchsedItems) { (allItem) in self.itemArray = allItem print("we have\(allItem.count) Items") self.tableView.reloadData() } } private func emptyItemPurchased(){ itemArray.removeAll() tableView.reloadData() updatingUser([K.kPurchedItems : itemArray]) { (error) in if self.itemArray.count > 0{ if error == nil{ self.hud.textLabel.text = "Item Purchased is Empty right now" self.hud.indicatorView = JGProgressHUDSuccessIndicatorView() self.hud.show(in: self.view) self.hud.dismiss(afterDelay: 2.0, animated: true) }else{ print("error\(error!.localizedDescription)") } }else{ self.hud.textLabel.text = "Item Purchased is Empty already" self.hud.indicatorView = JGProgressHUDSuccessIndicatorView() self.hud.show(in: self.view) self.hud.dismiss(afterDelay: 2.0, animated: true) } } } @IBAction func removePurchasedItems(_ sender:UIBarButtonItem){ emptyItemPurchased() } /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
@testable import Workshops_Module2 import Nimble import Quick class RootControllerFactorySpec: QuickSpec { override func spec() { describe("RootControllerFactory") { var sut: RootControllerFactory! beforeEach { sut = RootControllerFactory() } afterEach { sut = nil } it("should conform to RootControllerFactoryProtocol") { expect(sut).to(beAKindOf(RootControllerFactoryProtocol.self)) } context("when creating root controller") { it("should NOT throw assertion when creates root controller") { var controller: UIViewController? expect { controller = sut.makeRootController() }.toNot(throwAssertion()) expect(controller).to(beAnInstanceOf(UINavigationController.self)) } it("should set TimetableViewController as root view controller") { let rootController = sut.makeRootController() as? UINavigationController expect(rootController?.children).to(haveCount(1)) expect(rootController?.viewControllers.first).to(beAnInstanceOf(TimetableViewController.self)) } } } } }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit public struct Navigation<Route, Source, Destination> where Route: AnyNavigationRoute, Source: AnyNavigationSource, Destination: UIViewController { public let route: Route public let source: Source public let destination: Destination } public struct AnyNavigation { public let route: AnyNavigationRoute public let source: AnyNavigationSource public let destination: UIViewController }
// // HTTPClient.swift // RijksMuseum // // Created by Alexandre Mantovani Tavares on 18/05/20. // import Combine import Foundation class HTTPClient { enum RequestError: Swift.Error { case unableToCreateRequest } @Locatable private var urlSession: URLSession @Locatable private var cache: RequestCache func perform<T: Decodable>(request: Request) -> AnyPublisher<T, Error> { guard let urlRequest = request.asURLRequest() else { return Fail<T, Error>(error: RequestError.unableToCreateRequest) .eraseToAnyPublisher() } logger.debug(urlRequest.curlString) if let cached = cache[request], let value = cached as? T { return Result.Publisher(value).eraseToAnyPublisher() } return urlSession.dataTaskPublisher(for: urlRequest) .tryMap { data, _ in try JSONDecoder().decode(T.self, from: data) } .handleEvents(receiveOutput: { [cache] output in cache[request] = output }) .logErrors() .eraseToAnyPublisher() } }
// // ViewController.swift // // Copyright 2011-present Parse Inc. All rights reserved. // import UIKit import Parse import FBSDKCoreKit class ViewController: UIViewController { @IBAction func signupFacebook(sender: AnyObject) { let permissions = ["public_profile", "email"] PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions, block: { (user: PFUser?, error: NSError?) -> Void in if let error = error { println(error) } else { if let user = user { if let interestedinWomen: AnyObject = user["interestedinWomen"] { self.performSegueWithIdentifier("logUserIn", sender: self) } else { self.performSegueWithIdentifier("showSigninScreen", sender: self) } } } }) } override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { if let username = PFUser.currentUser()?.username { if let interestedinWomen: AnyObject = PFUser.currentUser()?["interestedinWomen"] { self.performSegueWithIdentifier("logUserIn", sender: self) } else { self.performSegueWithIdentifier("showSigninScreen", sender: self) } } } /* var xFromCenter : CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() let push = PFPush() push.setChannel("hello") push.setMessage("bye") push.sendPushInBackground() // Do any additional setup after loading the view, typically from a nib. var label: UILabel = UILabel(frame: CGRectMake(self.view.bounds.width / 2 - 100, self.view.bounds.height / 2 - 50, 200, 100)) label.text = "Drag Me" label.textAlignment = NSTextAlignment.Center self.view.addSubview(label) var gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:")) label.addGestureRecognizer(gesture) label.userInteractionEnabled = true } func wasDragged(gesture: UIPanGestureRecognizer) { let translation = gesture.translationInView(self.view) var label = gesture.view! xFromCenter += translation.x var scale = min(100 / abs(xFromCenter), 1) label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y) gesture.setTranslation(CGPointZero, inView: self.view) var rotetion: CGAffineTransform = CGAffineTransformMakeRotation(xFromCenter / (self.view.bounds.width / 2)) var stretch: CGAffineTransform = CGAffineTransformScale(rotetion, scale, scale) label.transform = stretch if label.center.x < 100 { } else if label.center.x > self.view.bounds.width - 100 { } if gesture.state == UIGestureRecognizerState.Ended { label.center = CGPointMake(self.view.bounds.width / 2, self.view.bounds.height / 2) scale = min(100 / abs(xFromCenter), 1) rotetion = CGAffineTransformMakeRotation(0 / 2) stretch = CGAffineTransformScale(rotetion, scale, scale) label.transform = stretch } } */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // DataBase.swift // iOSshopTestApp // // Created by Elias on 24/06/2019. // Copyright © 2019 Elias. All rights reserved. // import Foundation import SQLite public class DataBase { public static func getDataConnection() -> Connection { let dbDirrectory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let fileUrl = dbDirrectory?.appendingPathComponent("User").appendingPathExtension("sqlite3") let dataBase = try? Connection(fileUrl!.path) return dataBase! } public static func checkIfTablesExist(dataBase : Connection) -> Bool { let table = Table("Favorites") do { _ = try dataBase.scalar(table.exists) print("Table Exists") return true //exists } catch { //doesn't print("Table Not Exists") return false } } public static func createFavTable(dataBase : Connection) { let table = Table("Favorites") do { try dataBase.run(table.create(ifNotExists: true) { t in t.column(Expression<Int64>("id")) }) print("Table has been created") } catch { print("Table has not been created") print(error) } } public static func checkIfFav(dataBase : Connection, id : Int) -> Bool { var status = false let source = try! dataBase.prepare("SELECT id FROM Favorites WHERE id == \(id)") for row in source { // print("name: \(data[0]!)") if(row[0].self != nil) { status = true } } return status } public static func printAllFav(dataBase : Connection) { let source = try! dataBase.prepare("SELECT id FROM Favorites") for row in source { print("id: \(row[0]!)") } } public static func deleteRow(dataBase : Connection, id : Int) { do { try dataBase.scalar("DELETE FROM Favorites WHERE id == \(id)") } catch { print(error) } } public static func deleteAllRows(dataBase : Connection) { let table = Table("Favorites") do { try dataBase.run(table.delete()) } catch { print(error) } } public static func addRow(dataBase : Connection, id : Int) { do { try dataBase.run(Table("Favorites").insert(Expression<Int64>("id") <- Int64(id))) } catch { print(error) } } }
// // Album+CoreDataProperties.swift // Electro // // Created by John Davis on 5/22/16. // Copyright © 2016 John Davis. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension Album { @NSManaged var id: NSNumber? @NSManaged var albumElements: NSSet? }
// // ViewController.swift // ProximityReminders // // Created by Joanna Lingenfelter on 3/13/17. // Copyright © 2017 JoLingenfelter. All rights reserved. // import UIKit class RemindersViewController: UIViewController { lazy var tableView: UITableView = { let tableView = UITableView() tableView.delegate = self tableView.register(ReminderCell.self, forCellReuseIdentifier: ReminderCell.reuseIdentifier) return tableView }() lazy var dataSource: RemindersDataSource = { let reminderDataSource = RemindersDataSource(fetchRequest: Reminder.remindersFetchRequest, tableView: self.tableView) return reminderDataSource }() let instructionsLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() navigationBarSetup() tableView.dataSource = dataSource self.title = "Proximity Reminders" } override func viewDidLayoutSubviews() { // Layout tableView view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), tableView.leftAnchor.constraint(equalTo: view.leftAnchor), tableView.rightAnchor.constraint(equalTo: view.rightAnchor)]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK : - UITableViewControllerDelegate extension RemindersViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let reminder = dataSource.fetchedResultsController.object(at: indexPath) as! Reminder if reminder.completed == false { let reminderDetailViewController = ReminderDetailViewController(style: .grouped) reminderDetailViewController.reminder = reminder let navigationController = UINavigationController(rootViewController: reminderDetailViewController) self.present(navigationController, animated: true, completion: nil) } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let reminder = dataSource.fetchedResultsController.object(at: indexPath) as! Reminder let cell = cell as! ReminderCell cell.selectionStyle = .none let lineView = UIView(frame: CGRect(x: 15, y: cell.contentView.frame.size.height - 1.0, width: cell.contentView.frame.size.width - 20, height: 0.75)) lineView.backgroundColor = UIColor(red: 200/255.0, green: 199/255.0, blue: 204/255.0, alpha: 0.8) cell.contentView.addSubview(lineView) if reminder.completed == true { cell.completedButton.setImage(UIImage(named: "check"), for: .normal) cell.reminderTextLabel.textColor = .lightGray if let reminder = reminder.text { let attributedText = NSMutableAttributedString(string: reminder) attributedText.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSRange(location: 0, length: attributedText.length)) cell.reminderTextLabel.attributedText = attributedText } } else { cell.completedButton.setImage(UIImage(named: "uncheck"), for: .normal) cell.reminderTextLabel.textColor = .black } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } } // MARK: - Navigation extension RemindersViewController { func navigationBarSetup() { let addReminderButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(newReminderPressed)) addReminderButton.tintColor = .white navigationItem.rightBarButtonItem = addReminderButton } @objc func newReminderPressed() { let reminderDetailViewController = ReminderDetailViewController(style: .grouped) let navigationController = UINavigationController(rootViewController: reminderDetailViewController) self.present(navigationController, animated: true, completion: nil) } }
// // FootDetector.swift // FootTracking // // Created by Yang on 2020/07/08. // Copyright © 2020 Minestrone. All rights reserved. // import CoreML import Vision public class FootDetector { private let visionQueue = DispatchQueue(label: "com.minestrone.FootTracking.visionqueue") private lazy var predictionRequest: VNCoreMLRequest = { //ML 모델 로딩, Vision request 를 생성 do { let model = try VNCoreMLModel(for: FootModel().model) let request = VNCoreMLRequest(model: model) request.imageCropAndScaleOption = VNImageCropAndScaleOption.scaleFill return request } catch { fatalError("ML 모델 로딩 실패: \(error)") } }() public func performDetection(inputBuffer: CVPixelBuffer, completion: @escaping (_ outputBuffer: CVPixelBuffer?, _ error: Error?) -> Void) { //애플 기기에서 캡처된 이미지의 픽셀데이터는 카메라 센서의 기본 방향으로 인코딩 되기 때문에 .right로 설정 let requestHandler = VNImageRequestHandler(cvPixelBuffer: inputBuffer, orientation: .right) //CoreML Requests 를 비동기로 실행 visionQueue.async { do { try requestHandler.perform([self.predictionRequest]) guard let observation = self.predictionRequest.results?.first as? VNPixelBufferObservation else { fatalError("Unexpected result type from VNCoreMLRequest") } // 결과 이미지 (마스크 이미지)를 observation.pixelBuffer로 사용가능 completion(observation.pixelBuffer, nil) } catch { completion(nil, error) } } } }
// // BullsEyeGame.swift // BullsEye // // Created by Mirshad Oz on 6/9/20. // Copyright © 2020 Ray Wenderlich. All rights reserved. // import Foundation class BullsEyeGame { var currentValue: Int var targetValue = BullsEyeGame.getTargetValue() var score: Int var round: Int var gameSlider = Slider(value: 25.0) static func getTargetValue() -> Int { return Int.random(in: 1...100) } init(currentValue: Int, score: Int, round: Int) { self.currentValue = currentValue self.score = score self.round = round } func startNewGame() { score = 0 round = 0 startNewRound() } func startNewRound() { round += 1 targetValue = Int.random(in: 1...100) currentValue = 50 gameSlider.value = Float(currentValue) } }
// // ViewController.swift // SceneKitRotatingText // // Created by Marc on 2/4/15. // Copyright (c) 2015 Marc. All rights reserved. // import UIKit import SceneKit class ViewController: UIViewController { @IBOutlet weak var sceneView: SCNView! override var prefersStatusBarHidden : Bool { return true } func degreesToRadians (_ value:Double) -> CGFloat { return (CGFloat)(value * Double.pi / 180.0) } override func viewDidLoad() { super.viewDidLoad() // Set up scene, floor, camera and lighting let scene = SCNScene() // Light let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = SCNLight.LightType.ambient ambientLightNode.light!.color = UIColor(white: 0.5, alpha: 1.0) scene.rootNode.addChildNode(ambientLightNode) // This will give us some nice shadows let omniLightNode = SCNNode() omniLightNode.light = SCNLight() omniLightNode.light!.type = SCNLight.LightType.omni omniLightNode.light!.color = UIColor(white: 1, alpha: 1.0) omniLightNode.position = SCNVector3Make(0, 20, 0) scene.rootNode.addChildNode(omniLightNode) // Floor let floor = SCNFloor() // Set the material floor.firstMaterial?.diffuse.contents = UIColor(red: 0, green: 109 / 255, blue: 0, alpha: 1) floor.reflectivity = 0.5 let floorNode = SCNNode(geometry: floor) scene.rootNode.addChildNode(floorNode) let cameraNode = SCNNode() cameraNode.camera = SCNCamera() // You will need this so the text does not get clipped. Refer to documentation cameraNode.camera?.automaticallyAdjustsZRange = true // Position the camera off the floor vertically by 3 points, and place us away by 18 points cameraNode.position = SCNVector3Make(0, 3, 18) // Angle camera downward by -10 degrees cameraNode.rotation = SCNVector4Make((Float)(degreesToRadians(-10)), 0, 0, 0) // You could also achieve the same effect through a transform instead of setting values directly // let matrix: SCNMatrix4 = SCNMatrix4MakeTranslation(0, 3, 18) // Rotate the already translated matrix // cameraNode.transform = SCNMatrix4Rotate(matrix, (Float)(degreesToRadians(-10)), 1, 0, 0) scene.rootNode.addChildNode(cameraNode) // Set up text let text = SCNText(string: "Hello SceneKit!", extrusionDepth: 4) text.font = UIFont(name: "Zapfino", size: 10) // alignmentMode is currently broken on iOS, but works on the Mac. This is visible when doing multi line text. Refer to the documentation as to why containerFrame is needed. // text.containerFrame = CGRectMake(0, 0, 50, 50) // text.truncationMode = kCATruncationEnd // text.wrapped = true // text.alignmentMode = kCAAlignmentCenter let textNode = SCNNode(geometry: text) // Scale it to 20% on all axes textNode.scale = SCNVector3Make(0.2, 0.2, 0.2) // Axes: (left/right, low/high, close/far) textNode.position = SCNVector3Make(0, 5, -15) // Smoother rendering, refer to documentation text.flatness = 0.1 // We must pivot the text so that it is centered at 0.5, 0.5 var minVec = SCNVector3Zero var maxVec = SCNVector3Zero if textNode.__getBoundingBoxMin(&minVec, max: &maxVec) { let distance = SCNVector3( x: maxVec.x - minVec.x, y: maxVec.y - minVec.y, z: maxVec.z - minVec.z) textNode.pivot = SCNMatrix4MakeTranslation(distance.x / 2, distance.y / 2, distance.z / 2) } text.firstMaterial!.diffuse.contents = UIColor(red: 245/255, green: 216/255, blue: 0, alpha: 1) text.firstMaterial!.specular.contents = UIColor.white scene.rootNode.addChildNode(textNode) self.sceneView.scene = scene // Animation sequence // Relative rotations on x and y axes let horizontalAction = SCNAction.rotate(by: degreesToRadians(-45), around: SCNVector3Make(0, 1, 0), duration: 2) horizontalAction.timingMode = .easeInEaseOut let reverseHorizontalAction = horizontalAction.reversed() let verticalAction = SCNAction.rotate(by: degreesToRadians(-45), around: SCNVector3Make(1, 0, 0), duration: 2) verticalAction.timingMode = .easeInEaseOut let reverseVerticalAction = verticalAction.reversed() // Create a sequence of animations var sequence = SCNAction.sequence([ horizontalAction, // pan left reverseHorizontalAction, // center back reverseHorizontalAction, // pan right horizontalAction, // center back verticalAction, // pan down reverseVerticalAction, // center back reverseVerticalAction, // pan up verticalAction]) // center back // Make the sequence repeat forever sequence = SCNAction.repeatForever(sequence) textNode.runAction(sequence) } }
import UIKit import SectionsTableView import ThemeKit class NotificationSettingsSelectorViewController: ThemeViewController { private let onSelect: (AlertState) -> () private let selectedState: AlertState private let tableView = SectionsTableView(style: .grouped) init(selectedState: AlertState, onSelect: @escaping (AlertState) -> ()) { self.selectedState = selectedState self.onSelect = onSelect super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.registerCell(forClass: SingleLineCheckmarkCell.self) tableView.sectionDataSource = self tableView.backgroundColor = .clear tableView.separatorStyle = .none view.addSubview(tableView) tableView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } tableView.buildSections() } } extension NotificationSettingsSelectorViewController: SectionsDataSource { func buildSections() -> [SectionProtocol] { let allCases = AlertState.allCases return [ Section( id: "values", headerState: .margin(height: .margin3x), footerState: .margin(height: .margin8x), rows: allCases.enumerated().map { (index, state) in Row<SingleLineCheckmarkCell>( id: "\(state)", height: CGFloat.heightSingleLineCell, bind: { [unowned self] cell, _ in cell.bind( text: "\(state)", checkmarkVisible: self.selectedState == state, last: index == allCases.count - 1 ) }, action: { [weak self] _ in self?.onSelect(state) self?.navigationController?.popViewController(animated: true) } ) } ) ] } }
// // HabitCollectionViewCell.swift // Continuous // // Created by Chloe on 2016-02-23. // Copyright © 2016 Chloe Horgan. All rights reserved. // import UIKit class HabitCollectionViewCell: UICollectionViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var frequencyLabel: UILabel! @IBOutlet weak var intervalLabel: UILabel! }
// // LongDivisonViewModel.swift // LearnMath // // Created by varmabhupatiraju on 11/05/17. // Copyright © 2017 StellentSoft. All rights reserved. // import Foundation import UIKit import AudioToolbox class LongDivisionViewModel{ var longDivisionVCDelegate:LongDivisionViewController! // Custom Method to initialize the swipe Gestures to all directions in the view. func swiperInitializeMethod() { // Swipe Left let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: longDivisionVCDelegate, action: #selector(longDivisionVCDelegate.swipeLeft(recognizer:))) swipeLeft.direction = .left longDivisionVCDelegate.view.addGestureRecognizer(swipeLeft) // Swipe Right let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: longDivisionVCDelegate, action: #selector(longDivisionVCDelegate.swipeRight(recognizer:))) swipeRight.direction = .right longDivisionVCDelegate.view.addGestureRecognizer(swipeRight) // Swipe up let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: longDivisionVCDelegate, action: #selector(longDivisionVCDelegate.swipeUp(recognizer:))) swipeUp.direction = .up longDivisionVCDelegate.view.addGestureRecognizer(swipeUp) // Swipe Down let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: longDivisionVCDelegate, action: #selector(longDivisionVCDelegate.swipeDown(recognizer:))) swipeDown.direction = .down longDivisionVCDelegate.view.addGestureRecognizer(swipeDown) } // Custom Method to get the common data i.e level, range , question category from the appdelegate. func dataFromAppDelegate() { //Define appDelegate object so we can access common variables longDivisionVCDelegate.mfLevel = AppdelegateRef.appDelegate.MathFactsLevel print("Long Division: fetch of appDelegate mathFactsLevel \(longDivisionVCDelegate.mfLevel).") longDivisionVCDelegate.mfRange = AppdelegateRef.appDelegate.MathFactsRange print("Long Division: fetch of appDelegate MathFactsRange \(longDivisionVCDelegate.mfRange)") longDivisionVCDelegate.questionCategory = AppdelegateRef.appDelegate.MathFactsCatagory print("Long Division: fetch of appDelegate MathFactsCatagory \(longDivisionVCDelegate.questionCategory)") } // Custom method for the images design and the buttons creation. func initialDesign() { for index in 0...2 { //var imageData:Data! let imageData = try! Data(contentsOf: Bundle.main.url(forResource: Constant.gifsArray[index], withExtension: "gif")!) longDivisionVCDelegate.gifImagesArray.append(imageData) } if DeviceModel.IS_IPHONE_4_OR_LESS { longDivisionVCDelegate.alertPopOverView.frame = CGRect(x: longDivisionVCDelegate.alertPopOverView.frame.origin.x, y: 0, width: longDivisionVCDelegate.alertPopOverView.frame.size.width, height: longDivisionVCDelegate.alertPopOverView.frame.size.height+20) longDivisionVCDelegate.headerView.frame = CGRect(x: longDivisionVCDelegate.headerView.frame.origin.x, y: longDivisionVCDelegate.headerView.frame.origin.y-5, width: longDivisionVCDelegate.headerView.frame.size.width, height: longDivisionVCDelegate.headerView.frame.size.height) longDivisionVCDelegate.pageControl.frame = CGRect(x: longDivisionVCDelegate.headerView.center.x-5, y: longDivisionVCDelegate.headerView.frame.origin.y+longDivisionVCDelegate.applyFactsLbl.frame.size.height+20, width: 10, height:1) longDivisionVCDelegate.alertPopOverView.frame = CGRect(x: longDivisionVCDelegate.alertPopOverView.frame.origin.x, y: 0, width: longDivisionVCDelegate.alertPopOverView.frame.size.width, height: longDivisionVCDelegate.alertPopOverView.frame.size.height) longDivisionVCDelegate.popUpTitleView.frame = CGRect(x: 0, y: 0, width: DeviceModel.SCREEN_WIDTH, height: 40) longDivisionVCDelegate.popUpmessageView.frame = CGRect(x: 0, y: 40, width: DeviceModel.SCREEN_WIDTH, height: 376) } else { longDivisionVCDelegate.pageControl.frame = CGRect(x: longDivisionVCDelegate.headerView.center.x-5, y: longDivisionVCDelegate.headerView.frame.origin.y+longDivisionVCDelegate.applyFactsLbl.frame.size.height+17, width: 10, height:1) } longDivisionVCDelegate.pageControl.frame = CGRect(x: longDivisionVCDelegate.headerView.center.x-5, y: longDivisionVCDelegate.headerView.frame.origin.y+longDivisionVCDelegate.applyFactsLbl.frame.size.height+17, width: 10, height:1) longDivisionVCDelegate.pageControl.numberOfPages = 3 longDivisionVCDelegate.pageControl.currentPage = 1 longDivisionVCDelegate.pageControl.pageIndicatorTintColor = #colorLiteral(red: 0.8470588235, green: 0.8470588235, blue: 0.8470588235, alpha: 1) longDivisionVCDelegate.pageControl.currentPageIndicatorTintColor = #colorLiteral(red: 0.2392156863, green: 0.3960784314, blue: 0.4980392157, alpha: 1) longDivisionVCDelegate.headerView.addSubview(longDivisionVCDelegate.pageControl) longDivisionVCDelegate.alertPopOverView.isHidden = true longDivisionVCDelegate.divDropArrow2.isHidden = true longDivisionVCDelegate.divDropArrow3.isHidden = true longDivisionVCDelegate.divDropArrow4.isHidden = true ///////// longDivisionVCDelegate.divRemArrow = UIImageView(image: #imageLiteral(resourceName: "Up Arrow 23x26") ) longDivisionVCDelegate.divRemArrow.frame = CGRect(x: (longDivisionVCDelegate.dividendLabel.intrinsicContentSize.width+longDivisionVCDelegate.dividendLabel.frame.origin.x), y: (longDivisionVCDelegate.dividendLabel.intrinsicContentSize.height+longDivisionVCDelegate.dividendLabel.frame.origin.y), width: 23, height: 26) longDivisionVCDelegate.view.addSubview(longDivisionVCDelegate.divRemArrow) longDivisionVCDelegate.divRemArrow.isHidden = true longDivisionVCDelegate.view.bringSubview(toFront: longDivisionVCDelegate.divRemArrow) if DeviceModel.IS_IPHONE_5{ longDivisionVCDelegate.arrowsView.frame = CGRect(x: longDivisionVCDelegate.arrowsView.frame.origin.x+4, y: longDivisionVCDelegate.arrowsView.frame.origin.y, width: longDivisionVCDelegate.arrowsView.frame.size.width, height: longDivisionVCDelegate.arrowsView.frame.size.height) longDivisionVCDelegate.divDropArrow4.frame = CGRect(x: longDivisionVCDelegate.divDropArrow4.frame.origin.x+3, y: longDivisionVCDelegate.divDropArrow4.frame.origin.y, width: longDivisionVCDelegate.divDropArrow4.frame.size.width, height: longDivisionVCDelegate.divDropArrow4.frame.size.height) } else if DeviceModel.IS_IPHONE_6 { longDivisionVCDelegate.arrowsView.frame = CGRect(x: longDivisionVCDelegate.arrowsView.frame.origin.x, y: longDivisionVCDelegate.arrowsView.frame.origin.y, width: longDivisionVCDelegate.arrowsView.frame.size.width, height: longDivisionVCDelegate.arrowsView.frame.size.height) } else if DeviceModel.IS_IPHONE_6P { longDivisionVCDelegate.arrowsView.frame = CGRect(x: longDivisionVCDelegate.arrowsView.frame.origin.x-2, y: longDivisionVCDelegate.arrowsView.frame.origin.y, width: longDivisionVCDelegate.arrowsView.frame.size.width, height: longDivisionVCDelegate.arrowsView.frame.size.height) longDivisionVCDelegate.divDropArrow4.frame = CGRect(x: longDivisionVCDelegate.divDropArrow4.frame.origin.x-2, y: longDivisionVCDelegate.divDropArrow4.frame.origin.y, width: longDivisionVCDelegate.divDropArrow4.frame.size.width, height: longDivisionVCDelegate.divDropArrow4.frame.size.height) } // Set up images to flash math signs after swiping let xVal = (DeviceModel.SCREEN_WIDTH-150)/2 // plus image longDivisionVCDelegate.iconPlusSignLarge = UIImageView(image:#imageLiteral(resourceName: "Plus205x205dot")) longDivisionVCDelegate.iconPlusSignLarge.frame = CGRect(x: CGFloat(xVal), y: CGFloat(30), width: CGFloat(150), height: CGFloat(150)) longDivisionVCDelegate.view.addSubview(longDivisionVCDelegate.iconPlusSignLarge) longDivisionVCDelegate.iconPlusSignLarge.isHidden = false longDivisionVCDelegate.iconPlusSignLarge.alpha = 0.0 // Minus Image longDivisionVCDelegate.iconMinusSignLarge = UIImageView(image: #imageLiteral(resourceName: "Minus205x205dot")) longDivisionVCDelegate.iconMinusSignLarge.frame = CGRect(x: CGFloat(xVal), y: CGFloat(30), width: CGFloat(150), height: CGFloat(150)) longDivisionVCDelegate.view.addSubview(longDivisionVCDelegate.iconMinusSignLarge) longDivisionVCDelegate.iconMinusSignLarge.isHidden = false longDivisionVCDelegate.iconMinusSignLarge.alpha = 0.0 // Times Image longDivisionVCDelegate.iconTimesSignLarge = UIImageView(image: #imageLiteral(resourceName: "Times205x205dot")) longDivisionVCDelegate.iconTimesSignLarge.frame = CGRect(x: CGFloat(xVal), y: CGFloat(30), width: CGFloat(150), height: CGFloat(150)) longDivisionVCDelegate.view.addSubview(longDivisionVCDelegate.iconTimesSignLarge) longDivisionVCDelegate.iconTimesSignLarge.isHidden = false longDivisionVCDelegate.iconTimesSignLarge.alpha = 0.0 // Divide Image longDivisionVCDelegate.iconDivideSignLarge = UIImageView(image: #imageLiteral(resourceName: "Divide205x205dot")) longDivisionVCDelegate.iconDivideSignLarge.frame = CGRect(x: CGFloat(xVal), y: CGFloat(30), width: CGFloat(150), height: CGFloat(150)) longDivisionVCDelegate.view.addSubview(longDivisionVCDelegate.iconDivideSignLarge) longDivisionVCDelegate.iconDivideSignLarge.isHidden = false longDivisionVCDelegate.iconDivideSignLarge.alpha = 0.0 longDivisionVCDelegate.animationView.isHidden = true //TapGesture for PopView let popViewTapgeasture:UITapGestureRecognizer = UITapGestureRecognizer.init(target: longDivisionVCDelegate, action: #selector(longDivisionVCDelegate.alertCloseBtnAction)) popViewTapgeasture.numberOfTapsRequired = 1; longDivisionVCDelegate.alertPopOverView.addGestureRecognizer(popViewTapgeasture) } // Custom method to show the flash image which was select in initial screen with the fade animations. func flashIcon() { AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.ffftsoundFileObject) switch longDivisionVCDelegate.questionCategory { case 0: longDivisionVCDelegate.iconCurrentSignLarge = longDivisionVCDelegate.iconPlusSignLarge break case 1: longDivisionVCDelegate.iconCurrentSignLarge = longDivisionVCDelegate.iconMinusSignLarge break case 2: longDivisionVCDelegate.iconCurrentSignLarge = longDivisionVCDelegate.iconTimesSignLarge break case 3: longDivisionVCDelegate.iconCurrentSignLarge = longDivisionVCDelegate.iconDivideSignLarge break default: break } UIView.beginAnimations("fade in image", context: nil) UIView.setAnimationDuration(0.25) UIView.setAnimationDelay(0.0) UIView.setAnimationCurve(.easeInOut) longDivisionVCDelegate.iconCurrentSignLarge.alpha = 1.0 UIView.setAnimationDelegate(longDivisionVCDelegate) UIView.setAnimationDidStop(#selector(longDivisionVCDelegate.fadeAnimation)) UIView.commitAnimations() } // Custom method to start the fade out animation to dismiss the selected flash image func fadeInAnimationFinished(){ UIView.beginAnimations("fade out image", context: nil) UIView.setAnimationDuration(0.5) UIView.setAnimationDelay(0.25) UIView.setAnimationCurve(.easeInOut) longDivisionVCDelegate.iconPlusSignLarge.alpha = 0.0 longDivisionVCDelegate.iconMinusSignLarge.alpha = 0.0 longDivisionVCDelegate.iconTimesSignLarge.alpha = 0.0 longDivisionVCDelegate.iconDivideSignLarge.alpha = 0.0 UIView.commitAnimations() } // Custom method to get the random numbers by using the level which was user selected. func getNumbers() { var indexToRndArray:Int = 1 //Define appDelegate so we can access common variables switch longDivisionVCDelegate.mfLevel { case 0: repeat { indexToRndArray = AppdelegateRef.appDelegate.RandomNumInRange } while ((AppdelegateRef.appDelegate.RandomNumSecondVal * AppdelegateRef.appDelegate.RandomNumFirstVal) > 25) longDivisionVCDelegate.intDividend = AppdelegateRef.appDelegate.RandomNumFirstVal * AppdelegateRef.appDelegate.RandomNumSecondVal longDivisionVCDelegate.intDivisor = AppdelegateRef.appDelegate.RandomNumFirstVal break case 1: indexToRndArray = AppdelegateRef.appDelegate.RandomNumInRange longDivisionVCDelegate.intDividend = Int(arc4random_uniform(UInt32(100))) longDivisionVCDelegate.intDivisor = AppdelegateRef.appDelegate.RandomNumFirstVal break case 2: longDivisionVCDelegate.intDividend = Int(arc4random_uniform(UInt32(1000))) longDivisionVCDelegate.intDivisor = (Int(arc4random_uniform(UInt32(8)))) + 2 break case 3: longDivisionVCDelegate.intDividend = Int(arc4random_uniform(UInt32(10000))) longDivisionVCDelegate.intDivisor = (Int(arc4random_uniform(UInt32(8)))) + 2 break default: break } if (indexToRndArray > 1000){ print("Long Division: indextoarray out of bounds") } if (longDivisionVCDelegate.intDivisor == 0) { print("Long Division: Divide by zero atempted in longDivision") // This should never happen, but just in case bump divisor. longDivisionVCDelegate.intDivisor = longDivisionVCDelegate.intDivisor+1 } longDivisionVCDelegate.intQuotient = longDivisionVCDelegate.intDividend / longDivisionVCDelegate.intDivisor longDivisionVCDelegate.firstProductLabel.text = "" longDivisionVCDelegate.firstRemPartDivLabel.text = "" longDivisionVCDelegate.secondProductLabel.text = "" longDivisionVCDelegate.secondRemPartDivLabel.text = "" longDivisionVCDelegate.thirdProductLabel.text = "" longDivisionVCDelegate.thirdRemPartDivLabel.text = "" longDivisionVCDelegate.fourthProductLabel.text = "" longDivisionVCDelegate.fourthRemPartDivLabel.text = "" longDivisionVCDelegate.quotientLabel.text = "" // Ajay Commented //longDivisionVCDelegate.questionCount = longDivisionVCDelegate.questionCount+1 longDivisionVCDelegate.firstProductLineLabel.isHidden = true longDivisionVCDelegate.secondProductLineLabel.isHidden = true longDivisionVCDelegate.thirdProductLineLabel.isHidden = true longDivisionVCDelegate.fourthProductLineLabel.isHidden = true longDivisionVCDelegate.inputPhase = 0 longDivisionVCDelegate.ErrorOnThisQuestion = false // Display composite equation longDivisionVCDelegate.divisorLabel.text = String(longDivisionVCDelegate.intDivisor) longDivisionVCDelegate.dividendLabel.text = String(longDivisionVCDelegate.intDividend) if (longDivisionVCDelegate.intDividend > 9999) { print("Long Division: Dividend is too big to process > 9999") // Get new numberss } if (longDivisionVCDelegate.intDividend < 10) { longDivisionVCDelegate.numDividendDigits = 1 longDivisionVCDelegate.firstDigit = longDivisionVCDelegate.intDividend print("Long Division: Dividend\(longDivisionVCDelegate.intDividend) 1st digit\(longDivisionVCDelegate.firstDigit)") } else if (longDivisionVCDelegate.intDividend < 100) { longDivisionVCDelegate.firstDigit = longDivisionVCDelegate.intDividend / 100 longDivisionVCDelegate.numDividendDigits = 2 longDivisionVCDelegate.firstDigit = longDivisionVCDelegate.intDividend / 10 longDivisionVCDelegate.secondDigit = longDivisionVCDelegate.intDividend % 10 print("Long Division: Dividend=\(longDivisionVCDelegate.intDividend) 1st digit=\(longDivisionVCDelegate.firstDigit), 2nd=\(longDivisionVCDelegate.secondDigit)") } else if (longDivisionVCDelegate.intDividend < 1000) { longDivisionVCDelegate.numDividendDigits = 3 longDivisionVCDelegate.firstDigit = longDivisionVCDelegate.intDividend / 100 longDivisionVCDelegate.secondDigit = longDivisionVCDelegate.intDividend % 100 / 10 longDivisionVCDelegate.thirdDigit = longDivisionVCDelegate.intDividend % 10 } else if (longDivisionVCDelegate.intDividend < 10000) { longDivisionVCDelegate.numDividendDigits = 4 longDivisionVCDelegate.firstDigit = longDivisionVCDelegate.intDividend / 1000 longDivisionVCDelegate.secondDigit = longDivisionVCDelegate.intDividend % 1000 / 100 longDivisionVCDelegate.thirdDigit = longDivisionVCDelegate.intDividend % 100 / 10 longDivisionVCDelegate.fourthDigit = longDivisionVCDelegate.intDividend % 10 } longDivisionVCDelegate.animationView.isHidden = true } func attributedStr() -> NSMutableAttributedString { let str2 = NSMutableAttributedString(string: "-", attributes: [NSFontAttributeName:UIFont(name: "SFNS Display", size: 24.0)!, NSForegroundColorAttributeName: #colorLiteral(red: 0.5137254902, green: 0.4117647059, blue: 0.2862745098, alpha: 1)]) return str2 } //MARK:- Swipe methods // Custom method to push to the `SpeedDrilVC` when user swipes left side. func handleSwipeLeft(recognizer: UISwipeGestureRecognizer) { let location: CGPoint = recognizer.location(in: longDivisionVCDelegate.view) print("Fact: left swipe started at (\(location.x), \(location.y))") let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers.kSpeedDrilVC) as! MultiSpeedDrillViewController nextVC.modalTransitionStyle = .flipHorizontal AppdelegateRef.appDelegate.islaunch = false longDivisionVCDelegate.present(nextVC, animated: true, completion: nil) AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.wooshsoundFileObject) } // Custom method to push to the `MathFactsVC` when user swipes right side. func handleSwipeRight(recognizer: UISwipeGestureRecognizer) { let location: CGPoint = recognizer.location(in: longDivisionVCDelegate.view) print("Fact: left swipe started at (\(location.x), \(location.y))") let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers.kMathFactsVC) as! MathFactsViewController nextVC.modalTransitionStyle = .flipHorizontal AppdelegateRef.appDelegate.islaunch = false longDivisionVCDelegate.present(nextVC, animated: true, completion: nil) } // Custom method to push to the `MultiAppVC` when user swipes up side. func handleSwipeUp(recognizer: UISwipeGestureRecognizer) { let location: CGPoint = recognizer.location(in: longDivisionVCDelegate.view) print("Long Division: Up swipe started at (\(location.x), \(location.y))") //Define appDelegate objext so we can access common variables longDivisionVCDelegate.questionCategory = 0 flashIcon() /// to flash up the new math operator sign briefly AppdelegateRef.appDelegate.setMathFactsCatagory(newCatagory: longDivisionVCDelegate.questionCategory) // Set it to Addd print("Long Division: Updated appDelegate with selectedSegmentBasics to \(longDivisionVCDelegate.questionCategory).") let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers.kMultiAppVC) as! MultiAppViewController nextVC.questionCount = longDivisionVCDelegate.questionCount nextVC.selectedGifIndex = longDivisionVCDelegate.selectedGifIndex nextVC.modalTransitionStyle = .crossDissolve longDivisionVCDelegate.present(nextVC, animated: true, completion: nil) } // Custom method to push to the `MultiAppVC` when user swipes down side. func handleSwipeDown(recognizer: UISwipeGestureRecognizer) { let location: CGPoint = recognizer.location(in: longDivisionVCDelegate.view) print("Long Division: Down swipe started at (\(location.x), \(location.y))") //Define appDelegate objext so we can access common variables longDivisionVCDelegate.questionCategory = 2 flashIcon() /// to flash up the new math operator sign briefly AppdelegateRef.appDelegate.setMathFactsCatagory(newCatagory: longDivisionVCDelegate.questionCategory) // Set it to Addd print("Long Division: Updated appDelegate with selectedSegmentBasics to \(longDivisionVCDelegate.questionCategory).") let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers.kMultiAppVC) as! MultiAppViewController nextVC.questionCount = longDivisionVCDelegate.questionCount nextVC.selectedGifIndex = longDivisionVCDelegate.selectedGifIndex nextVC.modalTransitionStyle = .crossDissolve longDivisionVCDelegate.present(nextVC, animated: true, completion: nil) } //This function is called when home button is selected for displaying the Animation in MathFactsViewController func homeButtonAction(sender: UIButton) { let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers .kMathFactsVC) as! MathFactsViewController AppdelegateRef.appDelegate.islaunch = true longDivisionVCDelegate.present(nextVC, animated: false, completion: nil) AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.wooshsoundFileObject) } //MARK:- Custom Button Actions // Custom method to present the `MenuViewController`. Which is used to select the level, categori and the number range. func buttonMenuView() { let nextVC = StoryBoards.kMainStoryBoard.instantiateViewController(withIdentifier: ViewControllerIdentifiers.kMenuVC) as! MenuViewController longDivisionVCDelegate.present(nextVC, animated: true, completion: nil) } // Custom method to do the functionality of the arithmetic operation according to the button was selected in the number pad. If user selects the correct answer it will go to the next step of arithmetic operation otherwise gives a error sound. func buttonWasSelected(sender:UIButton){ switch longDivisionVCDelegate.inputPhase { // Ones Place case 0: // 1st digit of Quotient longDivisionVCDelegate.intFirstQuoDigit = longDivisionVCDelegate.firstDigit / longDivisionVCDelegate.intDivisor if (sender.tag == longDivisionVCDelegate.intFirstQuoDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit) longDivisionVCDelegate.inputPhase = 1 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break case 1: // First Product (only one digit) longDivisionVCDelegate.intFirstProduct = (longDivisionVCDelegate.firstDigit / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor // Int division to drop remainder if (sender.tag == longDivisionVCDelegate.intFirstProduct) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.intFirstProduct))) longDivisionVCDelegate.firstProductLabel.attributedText = str longDivisionVCDelegate.firstProductLineLabel.isHidden = false longDivisionVCDelegate.inputPhase = 2 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break case 2: // 1st digit of First Remainder longDivisionVCDelegate.intFirstRem = longDivisionVCDelegate.firstDigit - longDivisionVCDelegate.intFirstProduct if (sender.tag == longDivisionVCDelegate.intFirstRem) { longDivisionVCDelegate.firstRemPartDivLabel.text = String(longDivisionVCDelegate.intFirstRem) longDivisionVCDelegate.intRemainderQuoDigit = longDivisionVCDelegate.intFirstRem if (longDivisionVCDelegate.numDividendDigits == 1){ if (longDivisionVCDelegate.intRemainderQuoDigit == 0) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.dingsoundFileObject) if (longDivisionVCDelegate.ErrorOnThisQuestion == false && (longDivisionVCDelegate.questionCount > 4)) { longDivisionVCDelegate.animationView.isHidden = false longDivisionVCDelegate.animationImage.image = UIImage.gifImageWithData(longDivisionVCDelegate.gifImagesArray[longDivisionVCDelegate.selectedGifIndex]) if longDivisionVCDelegate.selectedGifIndex==2 { longDivisionVCDelegate.selectedGifIndex=0 } else { longDivisionVCDelegate.selectedGifIndex = longDivisionVCDelegate.selectedGifIndex+1 } longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 8.1, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) longDivisionVCDelegate.questionCount = 0 } else { longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 4, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) } longDivisionVCDelegate.questionCount = longDivisionVCDelegate.questionCount+1 longDivisionVCDelegate.inputPhase = 999 } else { longDivisionVCDelegate.inputPhase = 18 // Process remainder AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // Click } } else { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // Click longDivisionVCDelegate.inputPhase = 3 } } else { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) // Quack } break case 3: // 2nd digit of First Remainder if (sender.tag == longDivisionVCDelegate.secondDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) longDivisionVCDelegate.firstRemPartDivLabel.text = String(longDivisionVCDelegate.intFirstRem)+String(longDivisionVCDelegate.secondDigit) longDivisionVCDelegate.intFirstRem = (longDivisionVCDelegate.intFirstRem * 10) + longDivisionVCDelegate.secondDigit longDivisionVCDelegate.inputPhase = 4 longDivisionVCDelegate.divDropArrow2.isHidden = true } else { // Quack AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.soundFileObject) longDivisionVCDelegate.divDropArrow2.isHidden = false } break case 4: // 2nd digit of Quotient longDivisionVCDelegate.intSecondQuoDigit = (longDivisionVCDelegate.intFirstRem / longDivisionVCDelegate.intDivisor) if (sender.tag == longDivisionVCDelegate.intSecondQuoDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit) + String(longDivisionVCDelegate.intSecondQuoDigit) longDivisionVCDelegate.inputPhase = 5 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break case 5: // 1st digit of Second Product longDivisionVCDelegate.intSecondProduct = (longDivisionVCDelegate.intFirstRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor // Interger math eliminates remainders if (longDivisionVCDelegate.intSecondProduct > 9) { longDivisionVCDelegate.intSecondProduct = longDivisionVCDelegate.intSecondProduct / 10 // Get 'tens' place (1st digit). Interger math eliminates remainders if (sender.tag == longDivisionVCDelegate.intSecondProduct) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.intSecondProduct))) longDivisionVCDelegate.secondProductLabel.attributedText = str longDivisionVCDelegate.inputPhase = 6 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break } fallthrough // Else we will let it fall through to be processed in CASE 6 as a single digit case 6: // 2nd digit of Second Product longDivisionVCDelegate.calculatedDigit = (longDivisionVCDelegate.intFirstRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor % 10 // Interger math eliminates remainders if (sender.tag == longDivisionVCDelegate.calculatedDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) if (((longDivisionVCDelegate.intFirstRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor) < 10){ let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.calculatedDigit))) longDivisionVCDelegate.secondProductLabel.attributedText = str // Note TWO leading space (no 'tens' place) } else { longDivisionVCDelegate.intSecondProduct = (longDivisionVCDelegate.intFirstRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.intSecondProduct))) longDivisionVCDelegate.secondProductLabel.attributedText = str // Over with 1 digit with 2 digit value } longDivisionVCDelegate.secondProductLineLabel.isHidden = false longDivisionVCDelegate.inputPhase = 7 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break case 7: // 1st digit of Second Remainder longDivisionVCDelegate.intSecondRem = longDivisionVCDelegate.intFirstRem - longDivisionVCDelegate.intSecondProduct if (sender.tag == longDivisionVCDelegate.intSecondRem) { longDivisionVCDelegate.secondRemPartDivLabel.text = String(longDivisionVCDelegate.intSecondRem) longDivisionVCDelegate.intRemainderQuoDigit = longDivisionVCDelegate.intSecondRem if (longDivisionVCDelegate.numDividendDigits == 2){ if (longDivisionVCDelegate.intRemainderQuoDigit == 0) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.dingsoundFileObject) if (longDivisionVCDelegate.ErrorOnThisQuestion == false && (longDivisionVCDelegate.questionCount > 4)) { longDivisionVCDelegate.animationView.isHidden = false longDivisionVCDelegate.animationImage.image = UIImage.gifImageWithData(longDivisionVCDelegate.gifImagesArray[longDivisionVCDelegate.selectedGifIndex]) if longDivisionVCDelegate.selectedGifIndex==2 { longDivisionVCDelegate.selectedGifIndex=0 } else { longDivisionVCDelegate.selectedGifIndex = longDivisionVCDelegate.selectedGifIndex+1 } longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 8.1, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) longDivisionVCDelegate.questionCount = 0 } else { longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 4, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) } longDivisionVCDelegate.questionCount = longDivisionVCDelegate.questionCount+1 longDivisionVCDelegate.inputPhase = 999 } else { longDivisionVCDelegate.inputPhase = 18 // Process remainder AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // Click } } else { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // Click longDivisionVCDelegate.inputPhase = 8 } } else { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) // Quack } break case 8: // 2nd digit of Second Remainder if (sender.tag == longDivisionVCDelegate.thirdDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) longDivisionVCDelegate.secondRemPartDivLabel.text = String(longDivisionVCDelegate.intSecondRem)+String(longDivisionVCDelegate.thirdDigit) longDivisionVCDelegate.intSecondRem = (longDivisionVCDelegate.intSecondRem * 10) + longDivisionVCDelegate.thirdDigit longDivisionVCDelegate.inputPhase = 9 longDivisionVCDelegate.divDropArrow3.isHidden = true } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) longDivisionVCDelegate.divDropArrow3.isHidden = false } break case 9: // 3rd digit of Quotient longDivisionVCDelegate.intThirdQuoDigit = (longDivisionVCDelegate.intSecondRem / longDivisionVCDelegate.intDivisor) if (sender.tag == longDivisionVCDelegate.intThirdQuoDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit)+String(longDivisionVCDelegate.intSecondQuoDigit)+String(longDivisionVCDelegate.intThirdQuoDigit) longDivisionVCDelegate.inputPhase = 10 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break case 10: // 1st digit of Third Product longDivisionVCDelegate.intThirdProduct = (longDivisionVCDelegate.intSecondRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor // Interger math eliminates remainders if (longDivisionVCDelegate.intThirdProduct > 9) { longDivisionVCDelegate.intThirdProduct = longDivisionVCDelegate.intThirdProduct / 10 // Get 'tens' place (1st digit). Interger math eliminates remainders if (sender.tag == longDivisionVCDelegate.intThirdProduct) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.intThirdProduct))) longDivisionVCDelegate.thirdProductLabel.attributedText = str longDivisionVCDelegate.inputPhase = 11 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break } fallthrough // Else we will let it fall through to be processed in CASE 11 as a single digit case 11: // 2nd digit of Third Product longDivisionVCDelegate.calculatedDigit = ((longDivisionVCDelegate.intSecondRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor) % 10 // Interger math eliminates remainders if (sender.tag == longDivisionVCDelegate.calculatedDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) if (((longDivisionVCDelegate.intSecondRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor) < 10) { let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.calculatedDigit))) longDivisionVCDelegate.thirdProductLabel.attributedText = str } else { longDivisionVCDelegate.intThirdProduct = (longDivisionVCDelegate.intSecondRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.intThirdProduct))) longDivisionVCDelegate.thirdProductLabel.attributedText = str } longDivisionVCDelegate.thirdProductLineLabel.isHidden = false longDivisionVCDelegate.inputPhase = 12 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break case 12: // 1st digit of Third Remainder longDivisionVCDelegate.intThirdRem = longDivisionVCDelegate.intSecondRem - longDivisionVCDelegate.intThirdProduct if (sender.tag == longDivisionVCDelegate.intThirdRem) { longDivisionVCDelegate.thirdRemPartDivLabel.text = String(longDivisionVCDelegate.intThirdRem) longDivisionVCDelegate.intRemainderQuoDigit = longDivisionVCDelegate.intThirdRem if (longDivisionVCDelegate.numDividendDigits == 3){ if (longDivisionVCDelegate.intRemainderQuoDigit == 0) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.dingsoundFileObject) if (longDivisionVCDelegate.ErrorOnThisQuestion == false && (longDivisionVCDelegate.questionCount > 4)) { longDivisionVCDelegate.animationView.isHidden = false longDivisionVCDelegate.animationImage.image = UIImage.gifImageWithData(longDivisionVCDelegate.gifImagesArray[longDivisionVCDelegate.selectedGifIndex]) if longDivisionVCDelegate.selectedGifIndex==2 { longDivisionVCDelegate.selectedGifIndex=0 } else { longDivisionVCDelegate.selectedGifIndex = longDivisionVCDelegate.selectedGifIndex+1 } longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 8.1, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) longDivisionVCDelegate.questionCount = 0 } else { longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 4, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) } longDivisionVCDelegate.questionCount = longDivisionVCDelegate.questionCount+1 longDivisionVCDelegate.inputPhase = 999 } else { longDivisionVCDelegate.inputPhase = 18 // Process remainder AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // Click } } else { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // Click longDivisionVCDelegate.inputPhase = 13 } } else { AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.soundFileObject) // Quack } break case 13: // 2nd digit of Third Remainder if (sender.tag == longDivisionVCDelegate.fourthDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) longDivisionVCDelegate.thirdRemPartDivLabel.text = String(longDivisionVCDelegate.intThirdRem)+String(longDivisionVCDelegate.fourthDigit) longDivisionVCDelegate.intThirdRem = (longDivisionVCDelegate.intThirdRem * 10) + longDivisionVCDelegate.fourthDigit longDivisionVCDelegate.inputPhase = 14 longDivisionVCDelegate.divDropArrow4.isHidden = true } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) longDivisionVCDelegate.divDropArrow4.isHidden = false } break case 14: // 4th digit of Quotient longDivisionVCDelegate.intFourthQuoDigit = (longDivisionVCDelegate.intThirdRem / longDivisionVCDelegate.intDivisor) if (sender.tag == longDivisionVCDelegate.intFourthQuoDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit)+String(longDivisionVCDelegate.intSecondQuoDigit)+String(longDivisionVCDelegate.intThirdQuoDigit)+String(longDivisionVCDelegate.intFourthQuoDigit) longDivisionVCDelegate.inputPhase = 15 } else { // Quack AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.soundFileObject) } break case 15: // 1st digit of Fourth Product longDivisionVCDelegate.intFourthProduct = (longDivisionVCDelegate.intThirdRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor // Interger math eliminates remainders if (longDivisionVCDelegate.intFourthProduct > 9) { longDivisionVCDelegate.intFourthProduct = longDivisionVCDelegate.intFourthProduct / 10 // Get 'tens' place (1st digit). Interger math eliminates remainders if (sender.tag == longDivisionVCDelegate.intFourthProduct) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.intFourthProduct))) longDivisionVCDelegate.fourthProductLabel.attributedText = str longDivisionVCDelegate.inputPhase = 16 } else {// Quack AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.soundFileObject) } break } fallthrough case 16: // 2nd digit of Fourth Product longDivisionVCDelegate.calculatedDigit = ((longDivisionVCDelegate.intThirdRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor) % 10 // Interger math eliminates remainders if (sender.tag == longDivisionVCDelegate.calculatedDigit) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) if (((longDivisionVCDelegate.intThirdRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor) < 10) { let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.calculatedDigit))) longDivisionVCDelegate.fourthProductLabel.attributedText = str // Note leading space (no 'tens' place) } else { longDivisionVCDelegate.intFourthProduct = (longDivisionVCDelegate.intThirdRem / longDivisionVCDelegate.intDivisor) * longDivisionVCDelegate.intDivisor let str = attributedStr() str.append(NSAttributedString(string: " ")) str.append(NSAttributedString(string: String(longDivisionVCDelegate.intFourthProduct))) longDivisionVCDelegate.fourthProductLabel.attributedText = str // Over with 1 digit with 2 digit value } longDivisionVCDelegate.fourthProductLineLabel.isHidden = false longDivisionVCDelegate.inputPhase = 17 } else { // Quack AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.soundFileObject) } break case 17: // 1st digit of Fourth Remainder longDivisionVCDelegate.intFourthRem = longDivisionVCDelegate.intThirdRem - longDivisionVCDelegate.intFourthProduct if (sender.tag == longDivisionVCDelegate.intFourthRem) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) longDivisionVCDelegate.fourthRemPartDivLabel.text = String(longDivisionVCDelegate.intFourthRem) longDivisionVCDelegate.intRemainderQuoDigit = longDivisionVCDelegate.intFourthRem if (longDivisionVCDelegate.numDividendDigits == 4){ if (longDivisionVCDelegate.intRemainderQuoDigit == 0) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.dingsoundFileObject) if (longDivisionVCDelegate.ErrorOnThisQuestion == false && (longDivisionVCDelegate.questionCount > 4)) { longDivisionVCDelegate.animationView.isHidden = false longDivisionVCDelegate.animationImage.image = UIImage.gifImageWithData(longDivisionVCDelegate.gifImagesArray[longDivisionVCDelegate.selectedGifIndex]) if longDivisionVCDelegate.selectedGifIndex==2 { longDivisionVCDelegate.selectedGifIndex=0 } else { longDivisionVCDelegate.selectedGifIndex = longDivisionVCDelegate.selectedGifIndex+1 } longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 8.1, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) longDivisionVCDelegate.questionCount = 0 } else { longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 4, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) } longDivisionVCDelegate.questionCount = longDivisionVCDelegate.questionCount+1 longDivisionVCDelegate.inputPhase = 999 } else { longDivisionVCDelegate.inputPhase = 18 // Process remainder AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // Click } } else { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) // Click longDivisionVCDelegate.inputPhase = 18 } } else { AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.soundFileObject) // Quack } break case 18: // Remainder of Quotient if (sender.tag == 10) { AudioServicesPlaySystemSound (AudioFilesConstant.kSoundFileObject.clicksoundFileObject) if (longDivisionVCDelegate.numDividendDigits == 1) { longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit)+" r." } else if (longDivisionVCDelegate.numDividendDigits == 2){ longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit) + String(longDivisionVCDelegate.intSecondQuoDigit)+" r." } else if (longDivisionVCDelegate.numDividendDigits == 3){ longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit) + String(longDivisionVCDelegate.intSecondQuoDigit) + String(longDivisionVCDelegate.intThirdQuoDigit)+" r." } else if (longDivisionVCDelegate.numDividendDigits == 4){ longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit) + String(longDivisionVCDelegate.intSecondQuoDigit) + String(longDivisionVCDelegate.intThirdQuoDigit) + String(longDivisionVCDelegate.intFourthQuoDigit)+" r." } longDivisionVCDelegate.inputPhase = 19 longDivisionVCDelegate.divRemArrow.isHidden = true } else { // Quack AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.soundFileObject) longDivisionVCDelegate.divRemArrow.isHidden = false longDivisionVCDelegate.view.bringSubview(toFront: longDivisionVCDelegate.divRemArrow) } break case 19: // Remainder of Quotient if (sender.tag == longDivisionVCDelegate.intRemainderQuoDigit) { AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.dingsoundFileObject) if (longDivisionVCDelegate.numDividendDigits == 1) { longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit)+" r."+String(longDivisionVCDelegate.intRemainderQuoDigit) } else if (longDivisionVCDelegate.numDividendDigits == 2) { longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit)+String(longDivisionVCDelegate.intSecondQuoDigit)+" r."+String(longDivisionVCDelegate.intRemainderQuoDigit) } else if (longDivisionVCDelegate.numDividendDigits == 3){ longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit)+String(longDivisionVCDelegate.intSecondQuoDigit)+String(longDivisionVCDelegate.intThirdQuoDigit)+" r."+String(longDivisionVCDelegate.intRemainderQuoDigit) } else if (longDivisionVCDelegate.numDividendDigits == 4){ longDivisionVCDelegate.quotientLabel.text = String(longDivisionVCDelegate.intFirstQuoDigit)+String(longDivisionVCDelegate.intSecondQuoDigit)+String(longDivisionVCDelegate.intThirdQuoDigit)+String(longDivisionVCDelegate.intFourthQuoDigit)+" r."+String(longDivisionVCDelegate.intRemainderQuoDigit) } if (longDivisionVCDelegate.ErrorOnThisQuestion == false && (longDivisionVCDelegate.questionCount > 4)) { longDivisionVCDelegate.animationView.isHidden = false longDivisionVCDelegate.animationImage.image = UIImage.gifImageWithData(longDivisionVCDelegate.gifImagesArray[longDivisionVCDelegate.selectedGifIndex]) if longDivisionVCDelegate.selectedGifIndex==2 { longDivisionVCDelegate.selectedGifIndex=0 } else { longDivisionVCDelegate.selectedGifIndex = longDivisionVCDelegate.selectedGifIndex+1 } longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 8.1, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) longDivisionVCDelegate.questionCount = 0 } else { longDivisionVCDelegate.timeForNewNumbers = Timer.scheduledTimer(timeInterval: 4, target: longDivisionVCDelegate, selector: #selector(longDivisionVCDelegate.getNewNumber), userInfo: nil, repeats: false) } longDivisionVCDelegate.questionCount = longDivisionVCDelegate.questionCount+1 longDivisionVCDelegate.inputPhase = 999 } else { // Quack AudioServicesPlaySystemSound(AudioFilesConstant.kSoundFileObject.soundFileObject) } break default: break } } }
// // LoginController.swift // UberClone // // Created by Ankit Singh on 15/10/21. // import UIKit class LoginController: UIViewController { //MARK: - Properties private let titleLable : UILabel = { let label = UILabel() label.text = "UBER" label.font = UIFont(name: "Avenir-Light", size: 36) label.textColor = UIColor(white: 1, alpha: 0.8) return label }() private lazy var emailContainerView : UIView = { let view = UIView().inputContainerView(image: #imageLiteral(resourceName: "ic_mail_outline_white_2x"), textField: emailTextField) view.heightAnchor.constraint(equalToConstant: 50).isActive = true return view }() private lazy var passwordContainerView : UIView = { let view = UIView().inputContainerView(image: #imageLiteral(resourceName: "ic_lock_outline_white_2x"), textField: passwordTextField) view.heightAnchor.constraint(equalToConstant: 50).isActive = true return view }() private let emailTextField : UITextField = { return UITextField().textField(withPlaceHolder: "Email", isSecureTextEntry: false) }() private let passwordTextField : UITextField = { return UITextField().textField(withPlaceHolder: "Password", isSecureTextEntry: true) }() private let loginButton : UIButton = { let button = UIButton(type: .system) button.setTitle("Log In", for: .normal) button.setTitleColor(UIColor(white: 1, alpha: 0.85), for: .normal) button.backgroundColor = .mainBlueTint button.layer.cornerRadius = 5 button.heightAnchor.constraint(equalToConstant: 50).isActive = true button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) return button }() private let dontHaveAccountButton : UIButton = { let button = UIButton(type: .system) let attributedTitle = NSMutableAttributedString( string: "Don't have an account yet? ", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor : UIColor.lightGray]) attributedTitle.append(NSAttributedString(string: "Sign Up", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor : UIColor.mainBlueTint])) button.addTarget(self, action: #selector(handleShowSignUp), for: .touchUpInside) button.setAttributedTitle(attributedTitle, for: .normal) return button }() //MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() configureUI() } //MARK: - Selectors/Actions @objc func handleShowSignUp(){ print("Showing SignUp View") let controller = SignUpController() navigationController?.pushViewController(controller, animated: true) } //MARK: - Helper Functions func configureUI() { configureNavigationBar() view.backgroundColor = .backgroundColor view.addSubview(titleLable) titleLable.anchor(top:view.safeAreaLayoutGuide.topAnchor) titleLable.centerX(inView: view) let stackView = UIStackView(arrangedSubviews: [emailContainerView, passwordContainerView, loginButton]) stackView.axis = .vertical stackView.distribution = .fillEqually stackView.spacing = 16 view.addSubview(stackView) stackView.anchor(top:titleLable.bottomAnchor,left: view.leftAnchor,right: view.rightAnchor,paddingTop: 40,paddingLeft:16, paddingRight: 16) view.addSubview(dontHaveAccountButton) dontHaveAccountButton.centerX(inView: view) dontHaveAccountButton.anchor(bottom:view.safeAreaLayoutGuide.bottomAnchor,height: 32) } func configureNavigationBar() { navigationController?.navigationBar.isHidden = true navigationController?.navigationBar.barStyle = .black } }
// // File.swift // // // Created by Adam Wulf on 2/4/23. // import Foundation import os // // File.swift // // // Created by Adam Wulf on 2/4/23. // public extension ProcessInfo { /// A flag indicating if the app is running as a unit test. static let isUnitTesting: Bool = ProcessInfo.processInfo.environment.keys.firstIndex(where: { $0.hasPrefix("XCTest") }) != nil || ProcessInfo.processInfo.environment.keys.firstIndex(where: { $0.hasPrefix("CI") }) != nil /// A struct representing the memory information of a process. struct Memory { /// The memory footprint of the process let footprint: ByteSize /// The available memory for the process let available: ByteSize /// The total available memory process. This is the sum of both `footprint` and `avaialable` let limit: ByteSize /// Returns the memory information as a dictionary of human-readable strings. var loggingContext: [String: String] { return ["footprint": self.footprint.humanReadable, "available": self.available.humanReadable, "limit": self.limit.humanReadable] } } /// Returns the current and peak memory usage of the process. var memory: (current: Memory, peak: Memory)? { guard let stats = Self.processMemory(), let footprint = ByteSize(stats.phys_footprint), let footprint_peak = ByteSize(stats.ledger_phys_footprint_peak) else { return nil } let available = Self.memoryAvailable(footprint: footprint) let likelyLimit = available + footprint let current = Memory(footprint: footprint, available: available, limit: likelyLimit) let peak = Memory(footprint: footprint_peak, available: likelyLimit - footprint_peak, limit: likelyLimit) return (current, peak) } private static func memoryAvailable(footprint: ByteSize) -> ByteSize { #if os(iOS) #if targetEnvironment(simulator) // Reasonable default of 2Gb return max(.zero, ByteSize.gigabyte(2) - footprint) #elseif targetEnvironment(macCatalyst) return max(.zero, (ByteSize(ProcessInfo.processInfo.physicalMemory) ?? .zero) - footprint) #else return ByteSize(rawValue: os_proc_available_memory()) #endif #else return max(.zero, (ByteSize(ProcessInfo.processInfo.physicalMemory) ?? .zero) - footprint) #endif } private static func processMemory() -> task_vm_info_data_t? { let TASK_VM_INFO_COUNT = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size) guard let offset = MemoryLayout.offset(of: \task_vm_info_data_t.min_address) else { return nil } let TASK_VM_INFO_REV1_COUNT = mach_msg_type_number_t(offset / MemoryLayout<integer_t>.size) var info = task_vm_info_data_t() var count = TASK_VM_INFO_COUNT let kr = withUnsafeMutablePointer(to: &info) { infoPtr in infoPtr.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { intPtr in task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), intPtr, &count) } } guard kr == KERN_SUCCESS, count >= TASK_VM_INFO_REV1_COUNT else { return nil } return info } } /// Represents the thermal state of the device, which indicates the temperature and cooling capability. public extension ProcessInfo.ThermalState { /// Returns a string representation of the thermal state. var stringValue: String { switch self { case .nominal: return "nominal" case .fair: return "fair" case .serious: return "serious" case .critical: return "critical" @unknown default: return "unknown" } } }
// // DocViewController.swift // huicheng // // Created by lvxin on 2018/5/15. // Copyright © 2018年 lvxin. All rights reserved. // 函件管理 import UIKit class DocViewController: BaseViewController ,UITableViewDataSource,UITableViewDelegate,Work2RequestVCDelegate { let mainTabelView : UITableView = UITableView() let requestVC = Work2RequestVC() var dataArr : [docgetlistModel] = [] var pageNum : Int = 1 /// 分所id var bidStr = "" /// 函件编号 var dnStr = "" /// 合同编号 var nStr = "" /// 申请人 var kwStr = "" /// 律师名称 var uStr = "" /// 案件名称 var cnStr = "" /// 开始时间 var bStr = "" /// 结束时间 var eStr = "" // MARK: - life override func viewWillLayoutSubviews() { mainTabelView.snp.makeConstraints { (make) in make.top.equalTo(self.view).offset(0) make.left.right.equalTo(self.view).offset(0) make.bottom.equalTo(self.view).offset(0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = viewBackColor self.navigation_title_fontsize(name: "函件管理", fontsize: 18) self.navigationBar_rightBtn_image(image: #imageLiteral(resourceName: "mine_search")) self.navigationBar_leftBtn_image(image: #imageLiteral(resourceName: "pub_arrow")) self.creatUI() self.requestApi() } // MARK: - UI func creatUI() { mainTabelView.backgroundColor = UIColor.clear mainTabelView.delegate = self; mainTabelView.dataSource = self; mainTabelView.tableFooterView = UIView() mainTabelView.separatorStyle = .none mainTabelView.showsVerticalScrollIndicator = false mainTabelView.showsHorizontalScrollIndicator = false mainTabelView.backgroundView?.backgroundColor = .clear mainTabelView.register(UINib.init(nibName: "DocTableViewCell", bundle: nil), forCellReuseIdentifier: DocTableViewCellID) mainTabelView.mj_footer = self.creactFoot() mainTabelView.mj_footer.setRefreshingTarget(self, refreshingAction: #selector(loadMoreData)) self.view.addSubview(mainTabelView) } // MARK: - delegate func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : DocTableViewCell = tableView.dequeueReusableCell(withIdentifier: DocTableViewCellID, for: indexPath) as! DocTableViewCell if indexPath.row < self.dataArr.count { let model : docgetlistModel = self.dataArr[indexPath.row] cell.setData_doc(model: model) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row < self.dataArr.count { let model : docgetlistModel = self.dataArr[indexPath.row] requestVC.docgetinfoRequset(id: "\(model.id!)") } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return DocTableViewCellH } // MARK: - net func requestApi() { requestVC.delegate = self requestVC.docgetlistRequset(p: pageNum, c: 8, n: nStr, bid: bidStr, dn: dnStr, s: kwStr, lv: uStr, nm: cnStr, bd: bStr, ed: eStr) } func reflishData() { if self.dataArr.count > 0 { self.dataArr.removeAll() } pageNum = 1 self.requestApi() } @objc func loadMoreData() { HCLog(message: "加载更多") pageNum = pageNum + 1 self.requestApi() } func requestSucceed_work2(data: Any,type : Work2RequestVC_enum) { if type == .doc_getlist { let arr : [docgetlistModel] = data as! [docgetlistModel] if arr.count > 0 { self.dataArr = self.dataArr + arr } else { if pageNum > 1 { SVPMessageShow.showErro(infoStr: "暂无数据") } else { } } self.mainTabelView.reloadData() if mainTabelView.mj_footer.isRefreshing { mainTabelView.mj_footer.endRefreshing() } } else if type == .doc_getinfo { let model : docgetinfoModel = data as! docgetinfoModel let vc = ReadPdfViewController() vc.url = URL(string: base_imageOrFile_api + model.pdf!) vc.type = .tabIteam vc.pdfstate = model.state! vc.id = model.id vc.zhang = model.zhang! vc.pdfStr = model.pdf! // HCLog(message: "121212") HCLog(message: model.state) vc.noteStr = model.note vc.time = model.applytime vc.delDocSucessBlock = { self.reflishData() } self.navigationController?.pushViewController(vc, animated: true) } } func requestFail_work2() { } override func navigationLeftBtnClick() { self.navigationController?.popViewController(animated: true) } override func navigationRightBtnClick() { HCLog(message: "搜索") // let vc = SearchViewController() // vc.type = .deal_type // weak var weakself = self // vc.sureDealBlock = {content in // weakself?.numStr = content // weakself?.reflishData() // } // self.navigationController?.pushViewController(vc, animated: true) let vc = SearchViewController() vc.type = .doc_search vc.typeSub = 10 weak var weakself = self vc.sureDocSearchSure = {(nStr,dnStr,kwStr,uStr,cnStr,bidStr,startTimeStr,endTimeStr) in HCLog(message: startTimeStr) HCLog(message: endTimeStr) weakself?.nStr = nStr weakself?.dnStr = dnStr weakself?.kwStr = kwStr weakself?.uStr = uStr weakself?.cnStr = cnStr weakself?.bidStr = bidStr weakself?.bStr = startTimeStr weakself?.eStr = endTimeStr weakself?.reflishData() } self.navigationController?.pushViewController(vc, animated: true) } /* // 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. } */ }
// // SignUPVC.swift // DakkenApp // // Created by Sayed Abdo on 10/17/18. // Copyright © 2018 sayedAbdo. All rights reserved. // import UIKit import Alamofire import JSSAlertView class SignUPVC: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{ //OutLet @IBOutlet weak var imagebtn: UIButton! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var confirmTextField: UITextField! @IBOutlet weak var signUpBtn: UIButton! @IBOutlet weak var selectLocationBtn: UIButton! @IBOutlet weak var mapContinerView: UIView! @IBOutlet weak var imageas: UIImageView! @IBOutlet weak var VCTitle: UILabel! //Var var role : Int! var imagedone : Bool = false let REGISTER_URL = "https://dkaken.alsalil.net/api/register" //Start viewDidLoad override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. imagebtn.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "chooseprofileimage", comment: ""), for: .normal) nameTextField.placeholder = LocalizationSystem.sharedInstance.localizedStringForKey(key: "namePlaceHolder", comment: "") emailTextField.placeholder = LocalizationSystem.sharedInstance.localizedStringForKey(key: "emailPlaceHolder", comment: "") passwordTextField.placeholder = LocalizationSystem.sharedInstance.localizedStringForKey(key: "passwordPlaceHolder", comment: "") phoneTextField.placeholder = LocalizationSystem.sharedInstance.localizedStringForKey(key: "phonePlaceHolder", comment: "") confirmTextField.placeholder = LocalizationSystem.sharedInstance.localizedStringForKey(key: "confirmpasswordPlaceHolder", comment: "") buttonborder(button_outlet_name:signUpBtn) buttonborder(button_outlet_name:imagebtn) self.hideKeyboardWhenTappedAround() if(role == 0 ){ VCTitle.text = "\(LocalizationSystem.sharedInstance.localizedStringForKey(key: "VCSignUpTitle0", comment: ""))" } if(role == 1 ){ VCTitle.text = "\(LocalizationSystem.sharedInstance.localizedStringForKey(key: "VCSignUpTitle1", comment: ""))" } } //End viewDidLoad //Start Back Buttton Action @IBAction func back(_ sender: Any) { dismiss(animated: true, completion: nil) } //End Back Buttton Action @IBAction func signUpAction(_ sender: Any) { //Start Validation //check if the nameTextField textfield is empty or not if(nameTextField.text?.isEmpty)!{ JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "username", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } //check if the email textfield is valid or not let EmailAddress = emailTextField.text let isEmailAddressValid = isValidEmailAddress(emailAddressString: EmailAddress!) if isEmailAddressValid {} else { JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "email", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } //check if the password textfield is empty or not if(passwordTextField.text?.isEmpty)!{ JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "password", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } //check password lenght let pass = passwordTextField.text! if(Int(pass.count) < 6){ JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "passwordlenght", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } //check if the confirm password textfield is empty or not if(confirmTextField.text?.isEmpty)!{ JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "confirmpassword", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } //check if password and confirm is matched if(confirmTextField.text! != passwordTextField.text!){ JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "password", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } //check if the phoneTextField textfield is empty or not if(phoneTextField.text?.isEmpty)!{ JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "phone", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } if(imagedone == false){ JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "profile image", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } //End Validation //Call signUp function SignUpWithData() } //Start choosr image from calary or camera as a Acction Sheet @IBAction func trytochosseimage(_ sender: UITapGestureRecognizer) { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (alert:UIAlertAction!) -> Void in self.camera() })) actionSheet.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { (alert:UIAlertAction!) -> Void in self.photoLibrary() })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } @IBAction func changeimage(_ sender: Any) { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (alert:UIAlertAction!) -> Void in self.camera() })) actionSheet.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { (alert:UIAlertAction!) -> Void in self.photoLibrary() })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } //open Camera func camera() { if UIImagePickerController.isSourceTypeAvailable(.camera){ let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = .camera present(myPickerController, animated: true, completion: nil) } } //open galary photo func photoLibrary() { if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){ let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = .photoLibrary present(myPickerController, animated: true, completion: nil) } } ////display selected Image func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imageas.image = pickedImage imagedone = true } picker.dismiss(animated: true, completion: nil) } //Start show map Action @IBAction func showMap(_ sender: Any) { mapContinerView.isHidden = false } //End show map Action //////// //Start SignUpWithData func SignUpWithData(){ Alamofire.upload(multipartFormData: { multipartFormData in let params = [ "name" : "\(self.nameTextField.text!)", "email" : "\(self.emailTextField.text!)", "password" : "\(self.passwordTextField.text!)", "confirmpass" : "\(self.confirmTextField.text!)", "phone" : "\(self.phoneTextField.text!)", "country" : "2", "address" : "b", "firebase_token" : "b", "device_id" : "\(UIDevice.current.identifierForVendor!.uuidString)", "role" : "\(self.role)", "job" : "0", "image" : "" ] for (key, value) in params { if let data = value.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) { multipartFormData.append(data, withName: key) } } let imageData1 = UIImageJPEGRepresentation(self.imageas.image as! UIImage, 0.1)! multipartFormData.append(imageData1, withName: "image", fileName: "image.jpg", mimeType: "image/jpeg") print("success"); }, to: self.REGISTER_URL,method:HTTPMethod.post, headers:nil, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload .validate() .responseJSON { response in switch response.result { case .success(let value): print("responseObject: \(value)") let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC nextViewController.userEmail = self.emailTextField.text! nextViewController.userPassword = self.passwordTextField.text! nextViewController.fromsignUp = true self.present(nextViewController, animated:true, completion:nil) case .failure(let responseError): print("responseError: \(responseError)") JSSAlertView().danger( self, title: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Error", comment: ""), text: LocalizationSystem.sharedInstance.localizedStringForKey(key: "signuperror", comment: ""), buttonText: LocalizationSystem.sharedInstance.localizedStringForKey(key: "Try Again", comment: "")) return } } case .failure(let encodingError): print("encodingError: \(encodingError)") } }) } //End SignUpWithData } extension SignUPVC { //Hideen Keyboard func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SignUPVC.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } }
// // PatientCell.swift // MedDesktop // // Created by Igor Ogai on 09.07.2021. // import UIKit class PatientCell: UITableViewCell { //MARK:- Public Properties static var reuseIdentifier = "patientCell" //MARK:- Private Properties private lazy var cardNumberLabel: UILabel = { let label = UILabel() // label.backgroundColor = .green label.textColor = .black label.textAlignment = .left label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.font = UIFont(name: "HelveticaNeue-Light", size: 30) label.translatesAutoresizingMaskIntoConstraints = false return label }() private lazy var fullNameLabel: UILabel = { let label = UILabel() label.textColor = .black // label.backgroundColor = .yellow label.font = UIFont(name: "HelveticaNeue-Light", size: 30) label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.translatesAutoresizingMaskIntoConstraints = false return label }() private lazy var dateOfBirthLabel: UILabel = { let label = UILabel() label.textColor = .black label.textAlignment = .right // label.backgroundColor = .blue label.font = UIFont(name: "HelveticaNeue-Light", size: 30) label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.translatesAutoresizingMaskIntoConstraints = false return label }() private lazy var ageLabel: UILabel = { let label = UILabel() label.textColor = .black label.textAlignment = .right // label.backgroundColor = .red label.font = UIFont(name: "HelveticaNeue-Light", size: 30) label.translatesAutoresizingMaskIntoConstraints = false return label }() //MARK:- Public Methods func configure(patientModel: Patient) { backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1) guard let patientPatronymic = patientModel.patronymic else { return } fullNameLabel.text = "\(patientModel.surname + " " + patientModel.name + " " + patientPatronymic)" dateOfBirthLabel.text = patientModel.dateOfBirth ageLabel.text = calcAge(birthday: patientModel.dateOfBirth) cardNumberLabel.text = String(patientModel.cardNumber) } //MARK:- Initializers override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: PatientCell.reuseIdentifier) setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:- Private Methods private func setup() { contentView.addSubview(cardNumberLabel) contentView.addSubview(fullNameLabel) contentView.addSubview(dateOfBirthLabel) contentView.addSubview(ageLabel) NSLayoutConstraint.activate([ cardNumberLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), cardNumberLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), cardNumberLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8), cardNumberLabel.widthAnchor.constraint(equalToConstant: 70), fullNameLabel.centerYAnchor.constraint(equalTo: cardNumberLabel.centerYAnchor), fullNameLabel.leftAnchor.constraint(equalTo: cardNumberLabel.rightAnchor, constant: 8), fullNameLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 400), dateOfBirthLabel.leftAnchor.constraint(equalTo: fullNameLabel.rightAnchor, constant: 8), dateOfBirthLabel.centerYAnchor.constraint(equalTo: fullNameLabel.centerYAnchor), dateOfBirthLabel.widthAnchor.constraint(equalToConstant: 160), ageLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16), ageLabel.leftAnchor.constraint(equalTo: dateOfBirthLabel.rightAnchor, constant: 8), ageLabel.centerYAnchor.constraint(equalTo: cardNumberLabel.centerYAnchor), ageLabel.widthAnchor.constraint(equalToConstant: 150) ]) } private func calcAge(birthday: String) -> String! { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd.MM.yyyy" let birthdayDate = dateFormatter.date(from: birthday) let now = Date() let calendar = Calendar.current let calcAge = calendar.dateComponents([.year, .month], from: birthdayDate!, to: now) guard let age = calcAge.year else { return "0" } if age == 0 { guard let month = calcAge.month else { return "0" } return "\(month)мес." } else { return "\(age)" } } }
import UIKit class InfiniteScrollImage: UIView { var imageArray: [UIImage] = [UIImage(named: "image1")!,UIImage(named: "image2")!,UIImage(named: "image3")!] fileprivate lazy var currentIndex = 0 fileprivate lazy var nextIndex = 0 override func layoutSubviews() { addSubview(scrollView) scrollView.addSubview(currentImage) scrollView.addSubview(nextImage) addSubview(pageControl) } fileprivate lazy var scrollView: UIScrollView = { let scrollView = UIScrollView.init(frame: CGRect(x: 0, y: self.bounds.minY, width: self.bounds.width, height: self.bounds.height)) scrollView.contentSize = CGSize(width: self.bounds.width * 3, height: scrollView.contentSize.height) scrollView.contentOffset = CGPoint(x: self.bounds.maxX, y: 0) scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.isPagingEnabled = true scrollView.delegate = self return scrollView }() fileprivate lazy var currentImage: UIImageView = { let currentImage = UIImageView.init(frame: CGRect(x: self.bounds.maxX + 10, y: 0, width: self.bounds.width - 20, height: self.bounds.height)) currentImage.layer.cornerRadius = 22.0 currentImage.layer.masksToBounds = true currentImage.image = self.imageArray[0] currentImage.backgroundColor = UIColor.gray return currentImage }() fileprivate lazy var nextImage: UIImageView = { let otherImage = UIImageView.init() otherImage.layer.cornerRadius = 22.0 otherImage.layer.masksToBounds = true return otherImage }() fileprivate lazy var pageControl: UIPageControl = { let pageControl = UIPageControl.init(frame: CGRect(x: self.bounds.width / 2 - 50, y: self.bounds.maxY + 3, width: 100, height: 20)) pageControl.numberOfPages = self.imageArray.count pageControl.pageIndicatorTintColor = UIColor.gray pageControl.currentPageIndicatorTintColor = UIColor.blue return pageControl }() enum Direction { case none case right case left } fileprivate var direction: Direction? { didSet { if direction == .right { nextImage.frame = CGRect(x: currentImage.frame.maxX + 20, y: 0, width: self.bounds.width - 20, height: self.bounds.height) self.nextIndex = self.currentIndex + 1 if self.nextIndex > self.imageArray.count - 1 { self.nextIndex = 0 } } else if direction == .left { self.nextImage.frame = CGRect(x: 0, y: 0, width: self.bounds.width - 20, height: self.bounds.height) self.nextIndex = self.currentIndex - 1 if self.nextIndex < 0 { self.nextIndex = self.imageArray.count - 1 } } self.nextImage.image = self.imageArray[self.nextIndex] } } } extension InfiniteScrollImage: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { direction = scrollView.contentOffset.x > UIScreen.main.bounds.width ? .right : .left } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollDidStop() } private func scrollDidStop() { self.direction = .none let index = scrollView.contentOffset.x / scrollView.bounds.size.width if index == 1 { return } currentImage.image = nextImage.image currentIndex = nextIndex scrollView.contentOffset = CGPoint(x: self.bounds.width, y: scrollView.contentOffset.y) pageControl.currentPage = currentIndex } }
// // 118_杨辉三角.swift // algorithm.swift // // Created by yaoning on 1/21/20. // Copyright © 2020 yaoning. All rights reserved. // import Foundation //给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 //在杨辉三角中,每个数是它左上方和右上方的数的和。 // //示例: // //输入: 5 //输出: //[ // [1], // [1,1], // [1,2,1], // [1,3,3,1], // [1,4,6,4,1] //] // //来源:力扣(LeetCode) //链接:https://leetcode-cn.com/problems/pascals-triangle //著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 // 解题思路 // 观察可以得到 第n行的第i个元素 = 第n-1行的第i-1个元素和第i个元素之和 // n的边界条件为大于2 i的边界条件为非n的第一个和最后一个 // 求解第n行 需要第n-1行 求解n-1行 需要n-2行 可以自然得到递归的解法 // 递归的退出条件为 n为第1和第2行 class Solution118 { func generate(_ numRows: Int) -> [[Int]] { var res: [[Int]] = [] if numRows == 0 { return res } if numRows == 1 { res.append([1]) return res } res = generate(numRows - 1) var lastLine = Array<Int>(repeating: 1, count: numRows) for i in 1..<numRows - 1 { if let la = res.last { lastLine[i] = la[i - 1] + la[i] } } res.append(lastLine) return res } static func test() { print("118_杨辉三角") let res = Solution118().generate(5) for (index, row) in res.enumerated() { print("第\(index + 1)行: \(row)") } } }
// // BreedListViewModelTests_usingPublisherSpy.swift // CombineCollectionTests // // import Combine import XCTest @testable import CombineCollection // RunOnMainQueueSchedulerの使用を前提としている // PublisherSpyを利用することで // publisherの出力するEventを時系列に追っていくことができる class BreedListViewModelTests_usingPublisherSpy: XCTestCase { var cancellabels = Set<AnyCancellable>() func test_whenInit_thenNotGetData() { // Given let viewModel = BreedListViewModel(loader: .emptyLoader) let spy = PublisherSpy(viewModel.$breeds.eraseToAnyPublisher()) // When // Then assertEquals(spy.receivedEvents, [.value([])]) } func test_whenFetchSuccess_thenGetList() { // Given let apiResponse = [anyBreed] let expected = apiResponse.map { $0.toDisplayBreed } let viewModel = BreedListViewModel(loader: .loader(apiResponse)) let spy = PublisherSpy(viewModel.$breeds.eraseToAnyPublisher()) // When viewModel.fetchList() // Then assertEquals(spy.receivedEvents, [.value([]), .value(expected)]) } func test_whenFetchFailure_thenGetError() { // Given struct TestError: Error {} let expected = TestError() let viewModel = BreedListViewModel(loader: .error(expected)) let errorSpy = PublisherSpy(viewModel.$error.eraseToAnyPublisher()) // When viewModel.fetchList() // Then assertEquals( errorSpy.receivedEvents, [.value(nil), .value(nil), .value(expected)], isEqual: { switch ($0, $1) { case (.value(let l), .value(let r)): return l?.localizedDescription == r?.localizedDescription default: return false } }) } func test_whenFetchTwiceSuccess_thenGetSameList() { // Given let apiResponse = [anyBreed] let expected = apiResponse.map { $0.toDisplayBreed } let viewModel = BreedListViewModel(loader: .loader(apiResponse)) let spy = PublisherSpy(viewModel.$breeds.eraseToAnyPublisher()) // When viewModel.fetchList() viewModel.fetchList() // Then assertEquals(spy.receivedEvents, [.value([]), .value(expected), .value(expected)]) } } // MARK: - PublisherSpy final class PublisherSpy<Success, Failure: Error> { enum Event { case value(Success) case finished case failure(Error) } var cancellable: AnyCancellable? var receivedEvents: [Event] = [] init(_ publisher: AnyPublisher<Success, Failure>) { cancellable = publisher.sink { [self] finished in switch finished { case .finished: receivedEvents.append(.finished) case .failure(let error): receivedEvents.append(.failure(error)) } } receiveValue: { [self] value in receivedEvents.append(.value(value)) } } } extension XCTestCase { func assertEquals<Success, Failure>( _ expected: [PublisherSpy<Success, Failure>.Event], _ received: [PublisherSpy<Success, Failure>.Event], isEqual: @escaping (PublisherSpy<Success, Failure>.Event, PublisherSpy<Success, Failure>.Event) -> Bool, file: StaticString = #filePath, line: UInt = #line) { for (e, r) in zip(expected, received) { e.assertEqual(r, isEqual: isEqual, file: file, line: line) } } func assertEquals<Success, Failure>( _ expected: [PublisherSpy<Success, Failure>.Event], _ received: [PublisherSpy<Success, Failure>.Event], file: StaticString = #filePath, line: UInt = #line) where Success: Equatable { for (e, r) in zip(expected, received) { e.assertEqual(r, file: file, line: line) } } } extension PublisherSpy.Event { func assertEqual( _ expected: Self, isEqual: @escaping (Self, Self) -> Bool, file: StaticString = #filePath, line: UInt = #line) { if !isEqual(self, expected) { XCTFail("unmatched", file: file, line: line) } } func assertEqual( _ expected: PublisherSpy.Event, file: StaticString = #filePath, line: UInt = #line) where Success: Equatable { switch (self, expected) { case (let .value(l), let .value(r)): if l != r { XCTFail("unmatched", file: file, line: line) } case (.finished, .finished): break case (let .failure(l), let .failure(r)): if l.localizedDescription != r.localizedDescription { XCTFail("unmatched", file: file, line: line) } default: XCTFail("unmatched", file: file, line: line) } } }
// // AvailabilitiesView.swift // time2assemble // // Created by Julia Chun on 4/1/18. // Copyright © 2018 Julia Chun. All rights reserved. // import UIKit //used for clicking the cells to display names of people available during the time class AvailabilitiesView: UIStackView { var selected : Bool var isSelectable : Bool init(_ isSelectable: Bool) { selected = false self.isSelectable = isSelectable super.init(frame: CGRect()) if !isSelectable { backgroundColor = .lightGray } else { backgroundColor = .white } layer.borderWidth = 1 } required init(coder aDecoder: NSCoder) { selected = false isSelectable = true super.init(coder: aDecoder) backgroundColor = .white } func makeSelectable() { } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
import XCTest @testable import CountriesQL final class CountryListViewModelTests: XCTestCase { private var service: CountryListServiceMock! private var delegate: ViewModelDelegateMock! private var sut: CountryListViewModel! func setup(result: Result<[CountryListServiceProtocol.Country], NetworkError>) { service = CountryListServiceMock(result: result) delegate = ViewModelDelegateMock() sut = CountryListViewModel(continent: .dummy, service: service) sut.delegate = delegate } func testDataRequested() { setup(result: .failure(.generic)) sut.requestData() XCTAssertEqual(service.getCountriesCalled, ["123"]) } func testFailure() { setup(result: .failure(.generic)) sut.requestData() XCTAssertTrue(sut.countries.isEmpty) XCTAssertEqual(delegate.setLoadingCalled, [true, false]) XCTAssertEqual(delegate.showErrorCalled, ["Oops! Something went wrong!"]) XCTAssertEqual(delegate.reloadTableCounter, 1) } func testSuccess() { setup(result: .success([.dummy])) sut.requestData() XCTAssertEqual(sut.countries, [.dummy]) XCTAssertEqual(delegate.setLoadingCalled, [true, false]) XCTAssertEqual(delegate.showErrorCalled, []) XCTAssertEqual(delegate.reloadTableCounter, 1) } } private final class CountryListServiceMock: CountryListServiceProtocol { var getCountriesCalled: [String] = [] let result: Result<[Country], NetworkError> init(result: Result<[Country], NetworkError>) { self.result = result } func getCountries(continentID: String, completion: @escaping ((Result<[Country], NetworkError>) -> Void)) { getCountriesCalled.append(continentID) completion(result) } } private final class ViewModelDelegateMock: CountryListViewModelDelegate { var setLoadingCalled: [Bool] = [] var reloadTableCounter = 0 var showErrorCalled: [String] = [] func setLoading(_ loading: Bool) { setLoadingCalled.append(loading) } func reloadTable() { reloadTableCounter += 1 } func showError(message: String) { showErrorCalled.append(message) } }
// // TestCollectionViewController.swift // DynamicTableViewRowsDemo // // Created by Subash Poudel on 2/26/17. // Copyright © 2017 leapfrog. All rights reserved. // import UIKit class TestCollectionViewController: UIViewController { class func getVC() -> TestCollectionViewController { let storyboard = UIStoryboard(name: "Main", bundle: nil); let vc = storyboard.instantiateViewController(withIdentifier: String(describing: TestCollectionViewController.self)) as! TestCollectionViewController return vc } let reuse = "reuse" @IBOutlet var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() title = "TestCollectionViewController" collectionView.register(VignetteHeaderView, forSupplementaryViewOfKind: UICollection, withReuseIdentifier: <#T##String#>) } }
// // UIButtonExt.swift // versi-teacher-build // // Created by Caleb Stultz on 8/2/17. // Copyright © 2017 Caleb Stultz. All rights reserved. // import UIKit //extension UIButton { // func setSelectedColor() { // self.backgroundColor = darkPurple // } // // func setDeselectedColor() { // self.backgroundColor = lightPurple // } //}
import UIKit //var str = "aabbccc" //var str = "abbbbbbbbbbbb" var str = "aaabbaa" let a = 120 / 10 func compress(_ chars: inout [Character]) -> Int { if chars.count < 2 { return chars.count } var markIndex = 0 var rangeCount = 0 for flag in 0..<(chars.count) { rangeCount += 1 if flag == chars.count - 1 || chars[flag] != chars[flag + 1] { // 计算阶段 chars[markIndex] = chars[flag] markIndex += 1 if rangeCount > 1 { let rangeString = "\(rangeCount)" let rangeArray = Array(rangeString) var rangeIndex = 0 print(rangeString, rangeArray) while rangeIndex < rangeArray.count { let rangeChar = rangeArray[rangeIndex] chars[markIndex] = rangeChar markIndex += 1 rangeIndex += 1 } } rangeCount = 0 } } return markIndex } var array = Array(str) print("\(compress(&array))个") print(array)
// // SelectDepartmentView.swift // AP5004 // // Created by ducmanh on 3/21/19. // Copyright © 2019 Phạm Đức Mạnh. All rights reserved. // import Foundation protocol SelectDepartmentView: BaseView { }
// // InReadAdmobScrollViewController.swift // TeadsSampleApp // // Copyright © 2018 Teads. All rights reserved. // import GoogleMobileAds import TeadsAdMobAdapter import TeadsSDK import UIKit class InReadAdmobScrollViewController: TeadsViewController { var bannerView: GAMBannerView! @IBOutlet var slotView: UIView! @IBOutlet var slotViewHeightConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // 1. Create AdMob view and add it to hierarchy bannerView = GAMBannerView(adSize: GADAdSizeFluid) slotView.addSubview(bannerView) bannerView.translatesAutoresizingMaskIntoConstraints = false bannerView.centerXAnchor.constraint(equalTo: slotView.centerXAnchor).isActive = true bannerView.centerYAnchor.constraint(equalTo: slotView.centerYAnchor).isActive = true // 2. Attach Delegate (will include Teads events) bannerView.adUnitID = pid // Replace with your adunit bannerView.rootViewController = self bannerView.delegate = self // 3. Load a new ad (this will call AdMob and Teads afterward) let adSettings = TeadsAdapterSettings { settings in settings.enableDebug() try? settings.registerAdView(bannerView, delegate: self) // Needed by european regulation // See https://mobile.teads.tv/sdk/documentation/ios/gdpr-consent // settings.userConsent(subjectToGDPR: "1", consent: "0001100101010101") // The article url if you are a news publisher // settings.pageUrl("http://page.com/article1") } let request = GADRequest() request.register(adSettings) bannerView.load(request) } private func resizeAd(height: CGFloat) { slotViewHeightConstraint.constant = height bannerView.resize(GADAdSizeFromCGSize(CGSize(width: slotView.frame.width, height: height))) } } extension InReadAdmobScrollViewController: GADBannerViewDelegate { func bannerViewDidReceiveAd(_: GADBannerView) { // not used } /// Tells the delegate an ad request failed. func bannerView(_: GADBannerView, didFailToReceiveAdWithError error: Error) { resizeAd(height: 0) print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)") } /// Tells the delegate that a full-screen view will be presented in response /// to the user clicking on an ad. func bannerViewWillPresentScreen(_: GADBannerView) { // not used } /// Tells the delegate that the full-screen view will be dismissed. func bannerViewWillDismissScreen(_: GADBannerView) { // not used } /// Tells the delegate that the full-screen view has been dismissed. func bannerViewDidDismissScreen(_: GADBannerView) { // not used } } extension InReadAdmobScrollViewController: TeadsMediatedAdViewDelegate { func didUpdateRatio(_: UIView, adRatio: TeadsAdRatio) { resizeAd(height: adRatio.calculateHeight(for: slotView.frame.width)) } }
// // DYAVKitHelper.swift // Dayang // // Created by 田向阳 on 2017/11/28. // Copyright © 2017年 田向阳. All rights reserved. // import UIKit class DYAVKitHelper: NSObject { }
// // DoneViewController.swift // instaPay // // Created by Ebtsam alkhuzai on 15/11/1439 AH. // Copyright © 1439 Ebtsam alkhuzai. All rights reserved. // import UIKit import NVActivityIndicatorView class DoneViewController: UIViewController , NVActivityIndicatorViewable { @IBOutlet weak var doneLabel: UILabel! @IBOutlet weak var done: UIImageView! @IBOutlet weak var check: NVActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() check.color = .white check.type = NVActivityIndicatorType.ballClipRotate check.startAnimating() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { self.check.stopAnimating() self.done.image = UIImage(named: "success") self.doneLabel.text = "Done successfuly" } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) { self.performSegue(withIdentifier: "done", sender: self) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // AppleIDLoginDelegateSpy.swift // AppleIDButtonWrapper // // Created by Genaro Arvizu on 05/10/20. // Copyright © 2020 Luis Genaro Arvizu Vega. All rights reserved. // import Foundation @testable import AppleSignInWrapper class AppleIDLoginDelegateSpy: AppleIDLoginDelegate { var isSignIn: Bool = false var user: UserInformation! var error: Error = NSError() func appleSignInWrapper(didComplete withError: Error) { isSignIn = false user = nil error = withError } func appleSignInWrapper(didComplete withUser: UserInformation, nonce: String?) { isSignIn = true user = withUser } }
// // CreateRoasterViewController.swift // CoffeeNerd // // Created by Baptiste Leguey on 06/11/2017. // Copyright © 2017 Baptiste Leguey. All rights reserved. // import UIKit import Firebase class CreateRoasterViewController: UIViewController { // MARK: IBOutlets @IBOutlet var roasterNameTextfield: UITextField! // MARK: Properties var ref: DatabaseReference! override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference(withPath: "roaster-list") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func addRoasterTapped(_ sender: Any) { if let roasterName = roasterNameTextfield.text { let roasterRef = self.ref.childByAutoId() roasterRef.setValue(["name": roasterName]) } else { print("roaster name missing") } } }
// // Enemy.swift // TechDra // // Created by Master on 2015/03/24. // Copyright (c) 2015年 net.masuhara. All rights reserved. // import UIKit class Enemy: NSObject { var name: String! var maxHP: Float! var currentHP: Float! var attackPoint: Float! var defencePoint: Float! var speed: Float! var image: UIImage! override init() { super.init() name = "ドラゴン" maxHP = 10000 currentHP = 10000 attackPoint = 50 defencePoint = 10 speed = 1.2 image = UIImage(named: "dragon.png") } }
// // Validators.swift // YourCityEvents // // Created by Yaroslav Zarechnyy on 11/15/19. // Copyright © 2019 Yaroslav Zarechnyy. All rights reserved. // import Foundation protocol PValidator { func validate(_ text: String?) -> Bool }
// // UserListInteractor.swift // FinanteqInterview // // Created by Patryk Domagala on 12/06/2018. // Copyright © 2018 Dom-Pat. All rights reserved. // import Foundation protocol UserListInteractorOutput { func fetchUsers(response: UserListScene.FetchUsers.Response) func navigateToUserDetail(response: UserListScene.NavigateToUserDetails.Response) func updateTableViewState(response: UserListScene.UpdateTableViewState.Response) } protocol UserListDataSource {} class UserListInteractor: UserListDataSource { var output: UserListInteractorOutput? fileprivate let userWorker = UserWorker() fileprivate var users: [User] = [] //MARK: Responses fileprivate func fetchUsersResponse(users: [User]) { let response = UserListScene.FetchUsers.Response(userList: users) output?.fetchUsers(response: response) } fileprivate func navigateToUserdetailsResponse(user: User) { let response = UserListScene.NavigateToUserDetails.Response(user: user) output?.navigateToUserDetail(response: response) } fileprivate func updateTableViewStateResponse(state: HGTableViewState) { let response = UserListScene.UpdateTableViewState.Response(state: state) output?.updateTableViewState(response: response) } } // MARK: UserListViewControllerOutput extension UserListInteractor: UserListViewControllerOutput { func fetchUsers(request: UserListScene.FetchUsers.Request) { updateTableViewStateResponse(state: .loading) userWorker.fetchUsers().then { fetchedUsers in self.users = fetchedUsers self.fetchUsersResponse(users: self.users) let tableState: HGTableViewState = self.users.isEmpty ? .empty : .content self.updateTableViewStateResponse(state: tableState) }.catch { error in self.updateTableViewStateResponse(state: .error) } } func selectUser(request: UserListScene.SelectUser.Request) { navigateToUserdetailsResponse(user: users[request.index]) } }
// // CreatePersonViewController.swift // App // // Created by developer on 09.05.16. // Copyright © 2016 developer. All rights reserved. // import UIKit import BNRCoreDataStack class CreatePersonViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var personSegmentedControl: UISegmentedControl! @IBOutlet weak var bottomSpacingConstraint: NSLayoutConstraint! var person: Person? var doneButton: UIBarButtonItem! var stack: CoreDataStack var delegate: CreatePersonViewControllerDelegate? var attributes = [Attribute]() var manager = AttributeManager() override func viewDidLoad() { super.viewDidLoad() createBarButtons() configureView() configureSegmentedControl() configureKeyboardNotification() } init(coreDataStack stack: CoreDataStack) { self.stack = stack super.init(nibName: nil, bundle: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } required init?(coder aDecoder: NSCoder) { preconditionFailure("init(coder:) has not been implemented") } // MARK: Navigator func configureView() { tableView.delegate = self tableView.dataSource = self tableView.registerNib(UINib(nibName: "StringTableViewCell", bundle: nil), forCellReuseIdentifier: CellType.String.rawValue) tableView.registerNib(UINib(nibName: "NumberTableViewCell", bundle: nil), forCellReuseIdentifier: CellType.Number.rawValue) tableView.registerNib(UINib(nibName: "RangeTimeTableViewCell", bundle: nil), forCellReuseIdentifier: CellType.RangeTime.rawValue) tableView.registerNib(UINib(nibName: "AccountantTypeTableViewCell", bundle: nil), forCellReuseIdentifier: CellType.AccountantType.rawValue) if let person = person { title = "Update profile" manager = person.attributes() } else { title = "Create profile" updateTableView(FellowWorker.entityName) personSegmentedControl.selectedSegmentIndex = 0 } doneButton.enabled = false tableView.sectionHeaderHeight = 20 } func configureSegmentedControl() { if let person = person, entity = person.entity.name { switch entity { case Accountant.entityName: personSegmentedControl.selectedSegmentIndex = 2 case Director.entityName: personSegmentedControl.selectedSegmentIndex = 1 case FellowWorker.entityName: personSegmentedControl.selectedSegmentIndex = 0 default: break } } } func createBarButtons() { self.navigationController?.navigationBar.translucent = false self.edgesForExtendedLayout = UIRectEdge.None doneButton = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: #selector(CreatePersonViewController.done)) navigationItem.rightBarButtonItem = doneButton navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(CreatePersonViewController.dismiss)) } @objc private func dismiss() { dismissViewControllerAnimated(true, completion: nil) } @objc private func done() { if let entity = personSegmentedControl.titleForSegmentAtIndex(personSegmentedControl.selectedSegmentIndex) { if let person = person { if person.entity.name == entity { person.update(manager.dictionary()) } else { stack.mainQueueContext.deleteObject(person) self.person = Person.createPerson(entity, stack: stack, manager: manager) self.person?.sectionOrder = personSegmentedControl.selectedSegmentIndex - 1 } } else { person = Person.createPerson(entity, stack: stack, manager: manager) self.person?.sectionOrder = personSegmentedControl.selectedSegmentIndex - 1 } stack.mainQueueContext.saveContext() delegate?.createPersonViewController(didUpdatePerson: person) } dismissViewControllerAnimated(true, completion: nil) } // MARK: -Segment controller action @IBAction func changeValueSegmentController(sender: UISegmentedControl) { let select = sender.selectedSegmentIndex if let nameSegment = personSegmentedControl.titleForSegmentAtIndex(select) { updateTableView(nameSegment) } } func updateTableView(nameEntity: String) { manager = Person.attributes(nameEntity, stack: stack, oldManger: manager) tableView.reloadData() isValid() } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return manager.sections.count ?? 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return manager.sections[section].count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let attribute = manager.attribute(forIndexPath: indexPath) let cell = tableView.dequeueReusableCellWithIdentifier(attribute.type.rawValue, forIndexPath: indexPath) if let cell = cell as? DataCell { cell.indexPath = indexPath cell.updateUI(attribute) .onChange {[unowned self] value, indexPath in self.manager.setValue(forIndexPath: indexPath, value: value) self.isValid() } } return cell } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return tableView.sectionHeaderHeight } return tableView.sectionHeaderHeight } func isValid() { self.doneButton.enabled = (manager.isValid()) ? true : false } // MARK: Keyboard space func configureKeyboardNotification() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CreatePersonViewController.keyboardNotification(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CreatePersonViewController.keyboardNotification(_:)), name: UIKeyboardWillHideNotification, object: nil) } func keyboardNotification(notification: NSNotification) { let isShowing = notification.name == UIKeyboardWillShowNotification if let userInfo = notification.userInfo { let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() let endFrameHeight = endFrame?.size.height ?? 0.0 let duration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.unsignedLongValue ?? UIViewAnimationOptions.CurveEaseInOut.rawValue let animationCurve: UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw) self.bottomSpacingConstraint?.constant = isShowing ? endFrameHeight : 0.0 UIView.animateWithDuration(duration, delay: NSTimeInterval(0), options: animationCurve, animations: { self.view.layoutIfNeeded() }, completion: nil) } } } protocol CreatePersonViewControllerDelegate { func createPersonViewController(didUpdatePerson person: Person?) }
/* Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. diff21(19) → 2 diff21(10) → 11 diff21(21) → 0 */ func diff21(n: Int) -> Int { if n > 21 { return 2 * (n - 21) } else { return 21 - n } }
/** The way this code works is that we have a queue that will be the one that will have all the nodes at each level. This is done when we check for left and right at each level. after the root it has one left and one right but when we check the left we add its left and right and we do the same for the right one. But they won't be in the while loop since we store a count for it. WHich effectively gives us nodes per level **/ func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { guard root != nil else { return [] } var stack: [[Int]] = [] var queue: [TreeNode?] = [] queue.append(root) while !queue.isEmpty { var count = queue.count - 1 var temp = [Int]() while count >= 0 { if let node = queue.removeFirst() { temp.append(node.val) if let left = node.left { queue.append(left) } if let right = node.right { queue.append(right) } count -= 1 } } !temp.isEmpty ? stack.insert(temp, at: 0) : nil } return stack }
// // MessagesAPIResponse.swift // CleanSwiftSample // // Created by Okhan Okbay on 24.10.2020. // import Foundation struct MessagesWrapper: Decodable { let messages: [Message] } struct Message: Decodable { let id: String let text: String let timestamp: TimeInterval let user: User } struct User: Decodable { let id: String let avatarURL: String? let nickname: String }
// // Hopper.swift // Cryptohopper-iOS-SDK // // Created by Kaan Baris Bayrak on 26/10/2020. // import Foundation public class Hopper : Codable { public private(set) var id : String? public private(set) var name : String? public private(set) var exchange : HopperConfigExchange? public private(set) var baseCurrency : String? public private(set) var buyingEnabled : Int? public private(set) var sellingEnabled : Int? public private(set) var enabled : Int? public private(set) var errorMessage : String? public private(set) var configError : String? public private(set) var created : String? public private(set) var startBalance : String? public private(set) var subscriptionId : String? public private(set) var statTime : String? public private(set) var endTime : String? public private(set) var subscriptionStatus : String? public private(set) var autoRenewal : String? public private(set) var subscription : String? public private(set) var planName : String? public private(set) var planDescription : String? public private(set) var productId : String? public private(set) var lastLoadedConfig : Bool? public private(set) var image : String? public private(set) var setDefault : String? public private(set) var lastSignal : String? public private(set) var lastSignalEncoding : String? public private(set) var totalCurrency : String? public private(set) var botType : String? public private(set) var userId : String? public private(set) var allowedCoins : [String]? public private(set) var paperTrading : Int? private enum CodingKeys: String, CodingKey { case id = "id" case name = "name" case exchange = "exchange" case baseCurrency = "base_currency" case buyingEnabled = "buying_enabled" case sellingEnabled = "selling_enabled" case enabled = "enabled" case errorMessage = "error_message" case configError = "config_error" case created = "created" case startBalance = "start_balance" case subscriptionId = "subscription_id" case statTime = "start_time" case endTime = "end_time" case subscriptionStatus = "subscription_status" case autoRenewal = "auto_renewal" case subscription = "subscription" case planName = "plan_name" case planDescription = "plan_description" case productId = "product_id" case lastLoadedConfig = "last_loaded_config" case image = "image" case setDefault = "set_default" case lastSignal = "last_signal" case lastSignalEncoding = "last_signal_encoding" case totalCurrency = "total_cur" case botType = "bot_type" case userId = "user_id" case allowedCoins = "allowed_coins" case paperTrading = "paper_trading" } }
// // CheckingOutView.swift // Grillhome // // Created by Parasochka Danil on 31.05.2021. // Copyright © 2021 Евгений Григорьян. All rights reserved. // import SwiftUI struct CheckingOutView: View { @EnvironmentObject var homeViewModel: HomeViewModel var body: some View { VStack { ZStack { HStack { Button(action: { homeViewModel.isCheckingOutShowing = false }, label: { Image(systemName: "chevron.left") .font(.title) .foregroundColor(.black) .padding(.leading, 20) }) Spacer() } HStack { Text("Введите данные") .font(.title3) .fontWeight(.black) } } VStack { TextField("Имя", text: $homeViewModel.userName) .padding() .background(Color.gray.opacity(0.3).cornerRadius(10)) .foregroundColor(.black) .font(.headline) TextField("Адрес", text: $homeViewModel.address) .padding() .background(Color.gray.opacity(0.3).cornerRadius(10)) .foregroundColor(.black) .font(.headline) TextField("Телефон", text: $homeViewModel.phoneNumber) .padding() .background(Color.gray.opacity(0.3).cornerRadius(10)) .foregroundColor(.black) .font(.headline) } .padding() Button(action: {homeViewModel.makeOrder()}, label: { ZStack { RoundedRectangle(cornerRadius: 10) .foregroundColor(homeViewModel.isOrdered ? .green : .red) .frame(width: UIScreen.main.bounds.width * 0.9, height: 65, alignment: .center) Text(homeViewModel.isOrdered ? "Товар доставляется" : "Подтвердить заказ") .font(.title) .foregroundColor(.white) } .padding(.horizontal) .padding(.vertical, 5) }) Spacer() } } } struct CheckingOutView_Previews: PreviewProvider { static var previews: some View { CheckingOutView().environmentObject(HomeViewModel()) } }
// // ColorShiftPIX.swift // PixelKit // // Created by Anton Heestand on 2018-09-04. // Open Source - MIT License // import Foundation import CoreGraphics import RenderKit import Resolution import PixelColor @available(*, deprecated, renamed: "ColorShiftPIX") public typealias HueSaturationPIX = ColorShiftPIX final public class ColorShiftPIX: PIXSingleEffect, PIXViewable { override public var shaderName: String { return "effectSingleColorShiftPIX" } // MARK: - Public Properties @LiveFloat("hue", range: -0.5...0.5) public var hue: CGFloat = 0.0 @LiveFloat("saturation", range: 0.0...2.0) public var saturation: CGFloat = 1.0 @LiveColor("tintColor") public var tintColor: PixelColor = .white // MARK: - Property Helpers public override var liveList: [LiveWrap] { [_hue, _saturation, _tintColor] } override public var values: [Floatable] { return [hue, saturation, tintColor] } // MARK: - Life Cycle public required init() { super.init(name: "Color Shift", typeName: "pix-effect-single-color-shift") } public required init(from decoder: Decoder) throws { try super.init(from: decoder) } } public extension NODEOut { func pixTint(_ tintColor: PixelColor) -> ColorShiftPIX { let colorShiftPix = ColorShiftPIX() colorShiftPix.name = "tint:colorShift" colorShiftPix.input = self as? PIX & NODEOut colorShiftPix.tintColor = tintColor return colorShiftPix } func pixHue(_ hue: CGFloat) -> ColorShiftPIX { let colorShiftPix = ColorShiftPIX() colorShiftPix.name = "hue:colorShift" colorShiftPix.input = self as? PIX & NODEOut colorShiftPix.hue = hue return colorShiftPix } func pixSaturation(_ saturation: CGFloat) -> ColorShiftPIX { let colorShiftPix = ColorShiftPIX() colorShiftPix.name = "saturation:colorShift" colorShiftPix.input = self as? PIX & NODEOut colorShiftPix.saturation = saturation return colorShiftPix } func pixMonochrome(_ tintColor: PixelColor = .white) -> ColorShiftPIX { let colorShiftPix = ColorShiftPIX() colorShiftPix.name = "monochrome:colorShift" colorShiftPix.input = self as? PIX & NODEOut colorShiftPix.saturation = 0.0 colorShiftPix.tintColor = tintColor return colorShiftPix } }
// // ViewController.swift // Lab1 // import UIKit class MoviesListViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var movies: [Movie] = [] override func viewDidLoad() { super.viewDidLoad() movies = loadMovieData() tableView.delegate = self tableView.dataSource = self } func loadMovieData() -> [Movie]{ guard let path = Bundle.main.path(forResource: "MoviesList", ofType: "txt") else { return [] } let url = URL(fileURLWithPath: path) // array of Movie structures var movies = [Movie]() do { let data = try Data(contentsOf: url) let response = try JSONDecoder().decode(Response.self, from: data) movies = response.Search } catch { print(error) } return movies } } extension MoviesListViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let movie = movies[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell") as! MovieCell cell.setMovie(movie: movie) return cell } }
// // Todos.swift // TodoList // // Created by Bushmaks on 01.08.2018. // Copyright © 2018 Bushmaks. All rights reserved. // import Foundation class Todo { let id: Int let text: String var isCompleted: Bool let project_id: Int init(id: Int, text: String, isCompleted: Bool, project_id: Int) { self.id = id self.text = text self.isCompleted = isCompleted self.project_id = project_id } }
// // TodosTableViewController.swift // TodoList // // Created by Christian Oberdörfer on 19.03.19. // Copyright © 2019 Christian Oberdörfer. All rights reserved. // import CoreStore import GameIcons import UIKit protocol TodosTableViewControllerDelegate: class { /** Creates a new todo */ func add() /** Deletes a todo - parameter todo: The todo to delete */ func delete(_ todo: Todo) /** Selects a todo - parameter todo: The todo to select */ func select(_ todo: Todo) /** Shows the settings */ func showSettings() /** Toggles the done state of a todo - parameter todo: The todo to toggle */ func toggle(_ todo: Todo) } class TodosTableViewController: UITableViewController { let monitor = Database.dataStack.monitorSectionedList(From<Todo>() .sectionBy(\.dueDay) .orderBy(.ascending("dueDay"), .ascending("title"), .ascending("id")) .tweak { $0.fetchBatchSize = 20 } ) weak var delegate: TodosTableViewControllerDelegate? init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Localization self.title = Texts.TodosTableViewController.viewControllerTitle // Style self.setTheme() // Register self as observer to monitor self.monitor.addObserver(self) // Remove empty cells self.tableView.tableFooterView = UIView() // Register table cell class from nib self.tableView.register(UINib(nibName: "TodoTableViewCell", bundle: nil), forCellReuseIdentifier: "TodoTableViewCell") // Add bar buttons self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: GameIcon.cog.tabBarImage, style: .plain, target: self, action: #selector(showSettings)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return self.monitor.numberOfSections() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.monitor.numberOfObjectsInSection(section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TodoTableViewCell", for: indexPath) as! TodoTableViewCell cell.delegate = self let todo = self.monitor[indexPath] cell.set(todo) return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let todo = self.monitor[IndexPath(item: 0, section: section)] let date = todo.dueDate if Calendar.current.isDateInYesterday(date) { return Texts.yesterday } else if Calendar.current.isDateInToday(date) { return Texts.today } else if Calendar.current.isDateInTomorrow(date) { return Texts.tomorrow } else { return date.dayString } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let todo = self.monitor[indexPath] self.delegate?.select(todo) } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .delete } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let todo = self.monitor[indexPath] self.delegate?.delete(todo) } } // MARK: - Navigation /** Function to forward adding to the delegate */ @objc func add() { self.delegate?.add() } /** Function to forward settings showing to the delegate */ @objc func showSettings() { self.delegate?.showSettings() } } // MARK: - ListObserver extension TodosTableViewController: ListObserver { func listMonitorWillChange(_ monitor: ListMonitor<Todo>) { self.tableView.beginUpdates() } func listMonitorDidChange(_ monitor: ListMonitor<Todo>) { self.tableView.endUpdates() } func listMonitorWillRefetch(_ monitor: ListMonitor<Todo>) { } func listMonitorDidRefetch(_ monitor: ListMonitor<Todo>) { self.tableView.reloadData() } } // MARK: - ListObjectObserver extension TodosTableViewController: ListObjectObserver { func listMonitor(_ monitor: ListMonitor<Todo>, didInsertObject object: Todo, toIndexPath indexPath: IndexPath) { self.tableView.insertRows(at: [indexPath], with: .automatic) } func listMonitor(_ monitor: ListMonitor<Todo>, didDeleteObject object: Todo, fromIndexPath indexPath: IndexPath) { self.tableView.deleteRows(at: [indexPath], with: .automatic) } func listMonitor(_ monitor: ListMonitor<Todo>, didUpdateObject object: Todo, atIndexPath indexPath: IndexPath) { if let cell = self.tableView.cellForRow(at: indexPath) as? TodoTableViewCell { cell.set(object) } } func listMonitor(_ monitor: ListMonitor<Todo>, didMoveObject object: Todo, fromIndexPath: IndexPath, toIndexPath: IndexPath) { self.tableView.deleteRows(at: [fromIndexPath], with: .automatic) self.tableView.insertRows(at: [toIndexPath], with: .automatic) } } // MARK: - ListSectionObserver extension TodosTableViewController: ListSectionObserver { func listMonitor(_ monitor: ListMonitor<Todo>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int) { self.tableView.insertSections([sectionIndex], with: .automatic) } func listMonitor(_ monitor: ListMonitor<Todo>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int) { self.tableView.deleteSections([sectionIndex], with: .automatic) } } // MARK: - TodosTableViewControllerDelegate extension TodosTableViewController: TodoTableViewCellDelegate { func toggle(_ todo: Todo) { self.delegate?.toggle(todo) } }
// // PartiesTableViewController.swift // SFParties // // Created by Genady Okrain on 4/27/16. // Copyright © 2016 Okrain. All rights reserved. // import UIKit import CoreLocation protocol PartiesTableViewControllerDelegate { func load(completion: (() -> Void)?) } class PartiesTableViewController: UITableViewController, PartyTableViewControllerDelegate, UIViewControllerPreviewingDelegate { var selectedSegmentIndex = 0 { didSet { reloadData() } } var delegate: PartiesTableViewControllerDelegate? private var parties = PartiesManager.sharedInstance.parties override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // Peek & Pop if traitCollection.forceTouchCapability == .Available { registerForPreviewingWithDelegate(self, sourceView: view) } } @IBAction func refresh(sender: UIRefreshControl?) { delegate?.load() { sender?.endRefreshing() } } func buttonClicked(sender: UIButton) { performSegueWithIdentifier("map", sender: sender) } // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if selectedSegmentIndex == 1 && parties.count == 0 { return 1 } else { return parties.count } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if selectedSegmentIndex == 1 && parties.count == 0 { return 1 } else { return parties[section].count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if selectedSegmentIndex == 1 && parties.count == 0 { return tableView.dequeueReusableCellWithIdentifier("empty", forIndexPath: indexPath) } else { let cell = tableView.dequeueReusableCellWithIdentifier("party", forIndexPath: indexPath) as! PartyTableViewCell cell.party = parties[indexPath.section][indexPath.row] cell.separatorView.hidden = parties[indexPath.section].count == indexPath.row+1 return cell } } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if selectedSegmentIndex == 1 && parties.count == 0 { let navigationControllerHeight = navigationController?.navigationBar.frame.size.height ?? 0 return UIScreen.mainScreen().bounds.size.height-navigationControllerHeight-UIApplication.sharedApplication().statusBarFrame.size.height } else { return 75 } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if selectedSegmentIndex == 1 && parties.count == 0 { return 0 } else { return 40 } } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var view = UIView() if !(selectedSegmentIndex == 1 && parties.count == 0) && parties.count > section && parties[section].count > 0 { view = UIView(frame: CGRectMake(0.0, 0.0, tableView.frame.size.width, 40.0)) view.autoresizingMask = .FlexibleWidth let bgView = UIView(frame: CGRectMake(0.0, 0.0, tableView.frame.size.width, 40.0)) bgView.autoresizingMask = .FlexibleWidth bgView.backgroundColor = UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0) view.addSubview(bgView) let label = UILabel(frame: CGRectMake(8.0, 0.0, tableView.frame.size.width-22.0*2, 40.0)) label.autoresizingMask = .FlexibleRightMargin label.font = UIFont.systemFontOfSize(15.0, weight: UIFontWeightRegular) label.text = parties[section][0].date label.textColor = UIColor(red: 117.0/255.0, green: 117.0/255.0, blue: 117.0/255.0, alpha: 1.0) view.addSubview(label) let mapImageView = UIImageView(image: UIImage(named: "map")) mapImageView.autoresizingMask = .FlexibleLeftMargin mapImageView.frame = CGRectMake(tableView.frame.size.width-33.0, 6.0, 20.0, 28.0) view.addSubview(mapImageView) let button = UIButton(type: .Custom) button.autoresizingMask = .FlexibleWidth button.frame = view.frame button.addTarget(self, action: #selector(PartiesTableViewController.buttonClicked(_:)), forControlEvents: .TouchDown) button.tag = section view.addSubview(button) } return view } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) performSegueWithIdentifier("party", sender: indexPath) } // MARK: PartyTableViewControllerDelegate func reloadData() { if selectedSegmentIndex == 0 { parties = PartiesManager.sharedInstance.parties tableView.scrollEnabled = true } else { var pparties = [[Party]]() for p in PartiesManager.sharedInstance.parties { let filteredP = p.filter({ $0.isGoing }) if filteredP.count > 0 { pparties.append(filteredP) } } parties = pparties tableView.scrollEnabled = parties.count > 0 } tableView.reloadData() } // MARK: UIViewControllerPreviewingDelegate func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRowAtPoint(location), cell = tableView.cellForRowAtIndexPath(indexPath) as? PartyTableViewCell, nvc = storyboard?.instantiateViewControllerWithIdentifier("partyNVC") as? PartyNavigationController, vc = nvc.viewControllers[0] as? PartyTableViewController where tableView.bounds.contains(tableView.rectForRowAtIndexPath(indexPath)) else { return nil } previewingContext.sourceRect = cell.frame vc.party = parties[indexPath.section][indexPath.row] return nvc } func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) { navigationController?.pushViewController(viewControllerToCommit, animated: false) } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let nvc = segue.destinationViewController as? PartyNavigationController, vc = nvc.viewControllers[0] as? PartyTableViewController, indexPath = sender as? NSIndexPath where segue.identifier == "party" { vc.delegate = self vc.party = parties[indexPath.section][indexPath.row] } else if let nvc = segue.destinationViewController as? UINavigationController, vc = nvc.viewControllers[0] as? MapDayViewController, button = sender as? UIButton where segue.identifier == "map" { vc.navigationItem.title = parties[button.tag][0].date vc.parties = parties[button.tag] } } }
// // RegionTableViewController.swift // Goalscorer // // Created by tichinose1 on 2018/12/30. // Copyright © 2018 example.com. All rights reserved. // import UIKit import RealmSwift class AssociationTableViewController: UITableViewController { static func instantiate(association: Association) -> AssociationTableViewController { let vc = UIStoryboard(name: "Association", bundle: nil).instantiateInitialViewController() as! AssociationTableViewController vc.association = association return vc } var association: Association! private lazy var items: [Scorer] = association!.competitions .flatMap { $0.scorers.sorted(byKeyPath: "season", ascending: false) } override func viewDidLoad() { super.viewDidLoad() title = association.name } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setScreenName("Association") } } // MARK: - UITableViewDataSource extension AssociationTableViewController { // override func numberOfSections(in tableView: UITableView) -> Int { // return 0 // } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = items[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "regionCell", for: indexPath) cell.textLabel?.text = item.title cell.imageView?.image = item.competition.association.image return cell } } // MARK: - UITableViewDelegate extension AssociationTableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = items[indexPath.row] presentSafariViewController(url: item.url, contentType: "scorer", itemID: item.title) } }
// // MasterViewController.swift // The API Awakens // // Created by Gary Luce on 17/09/2016. // Copyright © 2016 gloos. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var icons = [["Characters": #imageLiteral(resourceName: "icon-characters")], ["Vehicles": #imageLiteral(resourceName: "icon-vehicles")], ["Starships": #imageLiteral(resourceName: "icon-starships")]] override func viewDidLoad() { super.viewDidLoad() } // MARK: - Segues // Depending on the initiated segue, we present the relevant VC override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showPerson" { SWAPIClient(type: .people, configuration: .default).fetch() { json in if let jason = json["results"] as? [[String:AnyObject]] { var people: [Person] = [] for person in jason { if let pers = Person(json: person) { people.append(pers) } } let destionationVC = segue.destination as! CharacterViewController destionationVC.people = people } } } else if segue.identifier == "showStarship" { SWAPIClient(type: .starships, configuration: .default).fetch() { json in if let jason = json["results"] as? [[String:AnyObject]] { var starships: [Spaceship] = [] for spaceship in jason { if let ship = Spaceship(json: spaceship) { starships.append(ship) } } let destionationVC = segue.destination as! SpaceshipViewController destionationVC.starships = starships } } } else if segue.identifier == "showVehicle" { SWAPIClient(type: .vehicles, configuration: .default).fetch() { json in if let jason = json["results"] as? [[String:AnyObject]] { var vehicles: [Vehicle] = [] for vehicle in jason { if let ship = Vehicle(json: vehicle) { vehicles.append(ship) } } let destionationVC = segue.destination as! VehicleViewController destionationVC.vehicles = vehicles } } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return icons.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! HomeTableviewCell let data = icons[indexPath.row] for (key, value) in data { cell.labelView.text = key cell.artworkView.image = value } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: self.performSegue(withIdentifier: "showPerson", sender: indexPath) case 1: self.performSegue(withIdentifier: "showVehicle", sender: indexPath) case 2: self.performSegue(withIdentifier: "showStarship", sender: indexPath) default: break } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } }
// // Post.swift // Captioned // // Created by Przemysław Pająk on 08.01.2018. // Copyright © 2018 FEARLESS SPIDER. All rights reserved. // import Foundation import ObjectMapper import Alamofire import AlamofireObjectMapper public final class Post: Mappable { var id: Int? var post_date: String? var title: String? var content: String? var photo: String? var user_data: [String: AnyObject]? var comments_count: Int! var likes_count: Int! var comments_data: [AnyObject]? var likes_data: [String: AnyObject]? var liked_data: Bool! = false required public init?(map: Map){ } public func mapping(map: Map) { id <- map["id"] post_date <- map["post_date"] title <- map["caption"] photo <- map["photo"] user_data <- map["user"] comments_count <- map["comments_count"] likes_count <- map["likes_count"] comments_data <- map["comments"] likes_data <- map["likes_data"] liked_data <- map["liked"] } public func postID() -> String! { return self.id?.description } public func postDate() -> NSDate! { let formatter: DateFormatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ" let dateRecorded: NSDate = formatter.date(from: self.post_date!)! as NSDate return dateRecorded } public func sharedURL() -> NSURL! { return NSURL(string: self.photo!) } public func photoURL() -> NSURL! { if self.photo != nil { if ((self.photo!.contains("http"))) { return NSURL(string: self.photo!) } else { return NSURL(string: Captioned.domain + self.photo!) } } return nil } public func captionText() -> String! { return self.title } @available(iOS 2.0, *) public func caption() -> [NSObject : AnyObject]! { return nil } @available(iOS 2.0, *) public func likes() -> [NSObject : AnyObject]! { return self.likes_data as! [NSObject : AnyObject] } public func comments() -> [AnyObject]! { let commentsArray:NSMutableArray = NSMutableArray() for data in self.comments_data! { let comment:Comment = Comment(JSON:data as! [String : AnyObject])! commentsArray.add(comment) } return commentsArray as [AnyObject] } public func liked() -> Bool { return self.liked_data } public func totalLikes() -> Int { return self.likes_count } public func totalComments() -> Int { return self.comments_count } public func user() -> User! { return User(JSON:self.user_data!) } }
// // WeatherServiceProtocol.swift // smartWeather // // Created by Florian on 20/10/15. // Copyright © 2015 FH Joanneum. All rights reserved. // import Foundation protocol WeatherServiceProtocol { func getUpcomingWeatherForLocation(location: Location, completionHandler: [DayWeather] -> Void, errorHandler: NSError -> Void) func getWeatherAroundPosition(position: Geoposition, maxCnt: Int, restrictToGroup: WeatherGroup, completionHandler: [DayWeather] -> Void, errorHandler: NSError -> Void) } enum WeatherGroup: String { case Sunny case Rainy case Cloudy case Snowy case All }
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation struct PoolMetalParam { let ksizeX: Int32 let ksizeY: Int32 let strideX: Int32 let strideY: Int32 let paddingX: Int32 let paddingY: Int32 let poolType: Int32 } class PoolKernel<P: PrecisionProtocol>: Kernel, Computable{ var metalParam: PoolMetalParam required init(device: MTLDevice, param: PoolParam<P>, initContext: InitContext) { param.output.initTexture(device: device, inTranspose: param.input.transpose, computePrecision: GlobalConfig.shared.computePrecision) var poolType: Int32 switch param.poolType { case "max": poolType = 0 case "avg": poolType = 1 default: fatalError() } metalParam = PoolMetalParam.init( ksizeX: param.ksize[0], ksizeY: param.ksize[1], strideX: param.stride[0], strideY: param.stride[1], paddingX: param.padding[0], paddingY: param.padding[1], poolType: poolType ) if GlobalConfig.shared.computePrecision == .Float32 { super.init(device: device, inFunctionName: "pool_float", initContext: initContext) } else if GlobalConfig.shared.computePrecision == .Float16 { super.init(device: device, inFunctionName: "pool_half", initContext: initContext) } else { fatalError() } } func compute(commandBuffer: MTLCommandBuffer, param: PoolParam<P>) throws { guard let encoder = commandBuffer.makeComputeCommandEncoder() else { throw PaddleMobileError.predictError(message: " encoder is nil") } encoder.setTexture(param.input.metalTexture, index: 0) encoder.setTexture(param.output.metalTexture, index: 1) encoder.setBytes(&metalParam, length: MemoryLayout<PoolMetalParam>.size, index: 0) encoder.dispatch(computePipline: pipline, outTexture: param.output.metalTexture) encoder.endEncoding() } }
// // RowSelection.swift // radio // // Created by MacBook 13 on 10/19/18. // Copyright © 2018 MacBook 13. All rights reserved. // import Foundation protocol RowSelection{ func onRowSelection(genre:GenreModel) }
// // ViewController.swift // tips3 // // Created by Jacob Hughes on 12/9/15. // Copyright © 2015 Jacob Hughes. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var twoPeople: UILabel! @IBOutlet weak var threePeople: UILabel! @IBOutlet weak var fourPeople: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Made the keyboard pop up at beginning billField.becomeFirstResponder() tipLabel.text = "$0.00" totalLabel.text = "$0.00" twoPeople.text = "$0.00" threePeople.text = "$0.00" fourPeople.text = "$0.00" let defaults = NSUserDefaults.standardUserDefaults() let lastEdit: NSDate? = defaults.objectForKey("LastUsed") as! NSDate? if lastEdit != nil { let timeInterval: NSTimeInterval = NSDate().timeIntervalSinceDate(lastEdit!) if timeInterval <= 600 { billField.text = defaults.objectForKey("billAmount") as? String onEditingChanged(self) } else { billField.text = "" onEditingChanged(self) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onEditingChanged(sender: AnyObject) { let defaults = NSUserDefaults.standardUserDefaults() let tipPercentages = [0.18, 0.20, 0.22] let LastUsed = NSDate() defaults.setObject(LastUsed, forKey: "Dates") defaults.setObject(billField.text, forKey: "billAmount") let tipPercentage = tipPercentages[tipControl.selectedSegmentIndex] let billAmount = NSString(string: billField.text!).doubleValue let tip = billAmount * tipPercentage let total = billAmount + tip let twoPeople1 = (total/2) let threePeople1 = (total/3) let fourPeople1 = (total/4) // Localized the Currency let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle formatter.locale = NSLocale.currentLocale() tipLabel.text = formatter.stringFromNumber(tip) totalLabel.text = formatter.stringFromNumber(total) twoPeople.text = formatter.stringFromNumber(twoPeople1) threePeople.text = formatter.stringFromNumber(threePeople1) fourPeople.text = formatter.stringFromNumber(fourPeople1) //tipLabel.text = String(format: "$%.2f", tip) //totalLabel.text = String(format: "$%.2f", total) } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } override func viewWillAppear(animated: Bool) { let defaults = NSUserDefaults.standardUserDefaults() tipControl.selectedSegmentIndex = defaults.integerForKey("DefaultSetting") onEditingChanged(self) let ColorScheme = defaults.integerForKey("Color") if ColorScheme == 0 { self.view.backgroundColor = UIColor.greenColor() } else { self.view.backgroundColor = UIColor.yellowColor() } } }
// // ToRouseController.swift // gjs_user // // Created by 大杉网络 on 2019/9/1. // Copyright © 2019 大杉网络. All rights reserved. // class ToRouseController: ViewController { let smsBalanceView = SmsBalance(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 60)) override func viewDidLoad() { super.viewDidLoad() setNavigation() view.backgroundColor = kBGGrayColor view.addSubview(smsBalanceView) let smsTemplate = SmsTemplate(frame: CGRect(x: 0, y: 60, width: kScreenW, height: 450), nav: navigationController) view.addSubview(smsTemplate) let smsFooter = SmsFooter(frame: CGRect(x: 0, y: kScreenH - headerHeight - 60, width: kScreenW, height: 60), nav: navigationController) view.addSubview(smsFooter) if let smsData = smsData { self.smsBalanceView.smsBalance.text = "短信余额:\(smsData.smsBalance!)" self.smsBalanceView.smsCost.text = "短信收费标准:\(smsData.smsCost!)元/条" } else { self.smsBalanceView.smsBalance.text = "短信余额:0.0" self.smsBalanceView.smsCost.text = "短信收费标准:0.0元/条" } } func setNavigation () { setNav(titleStr: "唤醒会员", titleColor: kMainTextColor, navItem: navigationItem, navController: navigationController) let mesagebtn = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 18)) mesagebtn.addTarget(self, action: #selector(toFlow), for: .touchUpInside) mesagebtn.setTitle("余额明细", for: .normal) mesagebtn.setTitleColor(kMainTextColor, for: .normal) mesagebtn.titleLabel?.font = FontSize(14) let mesagebtn1 = UIBarButtonItem(customView: mesagebtn) // mesagebtn.addTarget(self, action: #selector(toNews), for: .touchUpInside) navigationItem.rightBarButtonItem = mesagebtn1 } @objc func toFlow (_ btn: UIButton) { navigationController?.pushViewController(FlowController(), animated: true) } }
// // CGFloatExtension.swift // CurveCharacterization // // Created by Shenyao Ke on 2/23/20. // Copyright © 2020 Shenyao Ke. All rights reserved. // import Foundation extension CGFloat { func isFuzzyZero() -> Bool { return self > -CGFloat.ulpOfOne && self < CGFloat.ulpOfOne } func isFuzzyEqual(other: CGFloat) -> Bool { let dist = self - other return dist.isFuzzyZero() } func sqr() -> CGFloat { return self * self } }
// // UIButtonState.swift // Saturn // // Created by Quinn McHenry on 11/16/15. // Copyright © 2015 Small Planet. All rights reserved. // @objc public class UIButtonState : NSObject { var state: String? var image: String? var backgroundImage: String? var title: String? var titleColor: String? var titleShadowColor: String? public override func loadIntoParent(parent: AnyObject) { guard let button = parent as? UIButton else { assertionFailure("UIButtonState can only be a child of a UIButton") return } guard let state = state else { assertionFailure("UIButtonState must have a control state") return } let controlState = UIControlState(stringLiteral: state) if let image = image { button.setImage(UIImage(stringLiteral: image), forState: controlState) } if let backgroundImage = backgroundImage { button.setBackgroundImage(UIImage(stringLiteral: backgroundImage), forState: controlState) } if let title = title { button.setTitle(title, forState: controlState) } if let titleColor = titleColor { button.setTitleColor(UIColor(stringLiteral: titleColor), forState: controlState) } if let titleShadowColor = titleShadowColor { button.setTitleShadowColor(UIColor(stringLiteral: titleShadowColor), forState: controlState) } } public override func setAttribute(attribute: String, forProperty property: String) { switch property.lowercaseString { case "state": state = attribute case "image": image = attribute case "backgroundimage": backgroundImage = attribute case "title": title = attribute case "titlecolor": titleColor = attribute case "titleshadowcolor": titleShadowColor = attribute default: break } } }
// // Package.swift // FetchInstallerPkg // // Created by Armin Briegel on 2021-06-15. // import Foundation struct Package: Codable { let size: Int let url: String let digest: String? let metadataURL: String? enum CodingKeys: String, CodingKey { case size = "Size" case url = "URL" case digest = "Digest" case metadataURL = "MetadataURL" } }
// // BusinessDetail.swift // Yelp // // Created by Randy Ting on 9/27/15. // Copyright © 2015 Randy Ting. All rights reserved. // import UIKit class BusinessDetail: NSObject { var id: String? var name: String? var imageUrl: String? var snippetText: String? var snippetImageUrl: NSURL? var reviewExcerpt: String? var reviewerName: String? var reviewerImageUrl: NSURL? init(dictionary: [String: AnyObject]) { id = dictionary["id"] as? String name = dictionary["name"] as? String imageUrl = dictionary["image_url"] as? String let location = dictionary["location"] as? NSDictionary var address = "" if location != nil { let addressArray = location!["display_address"] as? NSArray for field in addressArray! { address += (field as! String) + ", " } } snippetText = address let snippetImageURLString = dictionary["image_url"] as? String if snippetImageURLString != nil { snippetImageUrl = NSURL(string: snippetImageURLString!)! } else { snippetImageUrl = nil } let reviews = dictionary["reviews"] as? NSArray if reviews != nil { let reviewDictionary = reviews![0] as? NSDictionary self.reviewExcerpt = reviewDictionary!["excerpt"] as? String self.reviewerName = (reviewDictionary!["user"] as? NSDictionary)!["name"] as? String let reviewerImageURLString = (reviewDictionary!["user"] as? NSDictionary)!["image_url"] as? String if reviewerImageURLString != nil { reviewerImageUrl = NSURL(string: reviewerImageURLString!)! } else { reviewerImageUrl = nil } } } class func getDetailsForBusinessID(id: String, completion: ([String: AnyObject]!, NSError!) -> Void) { YelpClient.sharedInstance.retrieveBusinessDetailsForID(id, completion: completion) } }
// // HistoryViewController.swift // Seeda // // Created by Mobile Expert on 10/6/16. // Copyright © 2016 Илья Железников. All rights reserved. // import UIKit protocol HistoryViewControllerDelegate { func didSelectHistory(sender: HistoryViewController) } class HistoryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, HistoryTableViewCellDelegate { @IBOutlet weak var historyTableView: UITableView! // @IBOutlet weak var confirmView: UIView! @IBOutlet weak var originalView: UIView! // @IBOutlet weak var okBtn: UIButton! // @IBOutlet weak var cancelBtn: UIButton! @IBOutlet weak var deleteBtn: UIButton! @IBOutlet weak var favoriteBtn: UIButton! var delegate:HistoryViewControllerDelegate! = nil var checkMarkMode = false; var button_mode = 0; //1: delete clicked, 2: favorite clicked var points = [Point]() let defaults = NSUserDefaults.standardUserDefaults() var arrSelectedCells:NSMutableArray! var checked:[Bool] = [] override func viewDidLoad() { super.viewDidLoad() self.navigationController?.setNavigationBarHidden(false, animated: true) // self.reloadHistoryPoints() // arrSelectedCells = NSMutableArray() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let defaults = NSUserDefaults.standardUserDefaults() let language = defaults.objectForKey("language") as! String if (language == "english") { deleteBtn.setTitle("Delete", forState: .Normal) favoriteBtn.setTitle("Move to favorites", forState: .Normal) } else { deleteBtn.setTitle("مسح", forState: .Normal) favoriteBtn.setTitle("نقل الى المفضلة", forState: .Normal) } // self.confirmView.hidden = true self.deleteBtn.layer.borderWidth = 1.0 self.deleteBtn.layer.cornerRadius = 5.0 self.deleteBtn.layer.borderColor = UIColor(red: 31/255, green: 78/255, blue: 121/255, alpha: 1.0).CGColor self.favoriteBtn.layer.borderWidth = 1.0 self.favoriteBtn.layer.cornerRadius = 5.0 self.favoriteBtn.layer.borderColor = UIColor(red: 31/255, green: 78/255, blue: 121/255, alpha: 1.0).CGColor self.favoriteBtn.titleLabel?.numberOfLines = 2 self.favoriteBtn.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping self.reloadHistoryPoints() arrSelectedCells = NSMutableArray() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func convertDDtoDMS(ddLat: Double, ddLong: Double) -> [[Int]]{ var latSeconds = Int(ddLat * 3600) let latDegrees = latSeconds / 3600 latSeconds = abs(latSeconds % 3600) let latMinutes = latSeconds / 60 latSeconds %= 60 var longSeconds = Int(ddLong * 3600) let longDegrees = longSeconds / 3600 longSeconds = abs(longSeconds % 3600) let longMinutes = longSeconds / 60 longSeconds %= 60 var ret = [[Int]]() var latAry = [Int]() latAry.append(latDegrees) latAry.append(latMinutes) latAry.append(latSeconds) var longAry = [Int]() longAry.append(longDegrees) longAry.append(longMinutes) longAry.append(longSeconds) ret.append(latAry) ret.append(longAry) return ret } // func showConfirmArea() { // self.confirmView.hidden = false // self.originalView.hidden = true // UIView .animateWithDuration(0.5, animations: { // self.confirmView.frame.origin.x = 0 // }, completion: { (finished) in // }) // } // // func hideConfirmArea() { // self.confirmView.hidden = true // self.originalView.hidden = false // UIView .animateWithDuration(0.5, animations: { // self.confirmView.frame.origin.x = 2000 // }, completion: { (finished) in // }) // } func reloadHistoryPoints() { points = (defaults.arrayForKey("history") as! [NSData]).map{NSKeyedUnarchiver.unarchiveObjectWithData($0) as! Point} checked = Array<Bool>(count: points.count, repeatedValue: false) } @IBAction func deleteBtnPressed(sender: AnyObject) { // button_mode = 1 // self.showConfirmArea() var temp = [Point]() for (var i = 0; i < points.count; i += 1) { if (checked[i] == false ) { temp.append(points[i]) } } let DataPoints = temp.map{ NSKeyedArchiver.archivedDataWithRootObject($0)} defaults.setObject(DataPoints, forKey: "history") reloadHistoryPoints() dispatch_async(dispatch_get_main_queue(), { () -> Void in self.historyTableView.reloadData() }) } @IBAction func favoriteBtnPressed(sender: AnyObject) { // button_mode = 2 //// self.showConfirmArea() // checkMarkMode = true var tmpPointList = [Int]() // checkMarkMode = false for (var i = 0; i < points.count; i += 1) { if (checked[i] == true) { //favorite Points var favoritePoints = (defaults.arrayForKey("points") as! [NSData]).map{NSKeyedUnarchiver.unarchiveObjectWithData($0) as! Point} favoritePoints.append(Point(latitude: points[i].latitude, longitude: points[i].longitude, name: points[i].name)) let fDataPoints = favoritePoints.map{ NSKeyedArchiver.archivedDataWithRootObject($0)} defaults.setObject(fDataPoints, forKey: "points") tmpPointList.append(i) } // cell.check_img.image = UIImage(named: "check_off.png") } var historyPoints = (defaults.arrayForKey("history") as! [NSData]).map{NSKeyedUnarchiver.unarchiveObjectWithData($0) as! Point} for (var i = tmpPointList.count - 1; i >= 0; i -= 1) { //remove historyPoint historyPoints.removeAtIndex(tmpPointList[i]) } let hDataPoints = historyPoints.map{ NSKeyedArchiver.archivedDataWithRootObject($0)} defaults.setObject(hDataPoints, forKey: "history") reloadHistoryPoints() dispatch_async(dispatch_get_main_queue(), { () -> Void in self.historyTableView.reloadData() }) } // @IBAction func okBtnPressed(sender: AnyObject) { // if (button_mode == 1) { // defaults.setObject([Point](), forKey: "history") // defaults.synchronize() // points = [Point]() // } else { // // var tmpPointList = [Int]() // checkMarkMode = false // // for (var i = 0; i < points.count; i += 1) { // if (checked[i] == true) { // // //favorite Points // var favoritePoints = (defaults.arrayForKey("points") as! [NSData]).map{NSKeyedUnarchiver.unarchiveObjectWithData($0) as! Point} // favoritePoints.append(Point(latitude: points[i].latitude, longitude: points[i].longitude, name: points[i].name)) // let fDataPoints = favoritePoints.map{ NSKeyedArchiver.archivedDataWithRootObject($0)} // defaults.setObject(fDataPoints, forKey: "points") // // tmpPointList.append(i) // // } //// cell.check_img.image = UIImage(named: "check_off.png") // } // // var historyPoints = (defaults.arrayForKey("history") as! [NSData]).map{NSKeyedUnarchiver.unarchiveObjectWithData($0) as! Point} // // for (var i = tmpPointList.count - 1; i >= 0; i -= 1) { // //remove historyPoint // historyPoints.removeAtIndex(tmpPointList[i]) // } // // let hDataPoints = historyPoints.map{ NSKeyedArchiver.archivedDataWithRootObject($0)} // defaults.setObject(hDataPoints, forKey: "history") // } // //// button_mode = 0 // reloadHistoryPoints() //// self.hideConfirmArea() // // self.arrSelectedCells.removeAllObjects() // dispatch_async(dispatch_get_main_queue(), { () -> Void in // self.historyTableView.reloadData() // }) // } // @IBAction func cancelBtnPressed(sender: AnyObject) { // if (button_mode == 1) { // // } else { // checkMarkMode = false // for (var i = 0; i < points.count; i += 1) { // let cell = self.historyTableView.cellForRowAtIndexPath(NSIndexPath(forRow: i, inSection: 0)) as! HistoryTableViewCell //// cell.check_img.image = UIImage(named: "check_off.png") // } // } // // button_mode = 0 // self.hideConfirmArea() // arrSelectedCells = NSMutableArray() // dispatch_async(dispatch_get_main_queue(), { () -> Void in // self.historyTableView.reloadData() // }) // } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return points.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("historyCell", forIndexPath: indexPath) as! HistoryTableViewCell cell.titleLabel?.text = points[indexPath.row].name let ddLatValue:Double? = Double(points[indexPath.row].latitude) let ddLongValue:Double? = Double(points[indexPath.row].longitude) var dmsData:[[Int]] = convertDDtoDMS(ddLatValue!, ddLong: ddLongValue!) cell.detailsLabel?.text = "N: " + String(format: "%.4f", Float(points[indexPath.row].latitude)!) + " E: " + String(format: "%.4f", Float(points[indexPath.row].longitude)!) + "\n" + String(format: "N: %d.%d.%d E: %d.%d.%d", dmsData[0][0],dmsData[0][1],dmsData[0][2],dmsData[1][0],dmsData[1][1],dmsData[1][2]) // if arrSelectedCells.containsObject(indexPath) { // cell.check_img.image = UIImage(named: "check_on.png") // }else { // cell.check_img.image = UIImage(named: "check_off.png") //// cell.accessoryType = .None // } cell.check_button.selected = checked[indexPath.row] cell.delegate = self cell.indexPath = indexPath return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { points.removeAtIndex(indexPath.row) let defaults = NSUserDefaults.standardUserDefaults() let dataPoints = points.map{ NSKeyedArchiver.archivedDataWithRootObject($0)} defaults.setObject(dataPoints, forKey: "history") tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) checked.removeAtIndex(indexPath.row) } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // if (button_mode == 1) { // // } else if (button_mode == 2) { // // tableView.deselectRowAtIndexPath(indexPath, animated: true) // // if arrSelectedCells.containsObject(indexPath) { // // arrSelectedCells.removeObject(indexPath) // }else { // // arrSelectedCells.addObject(indexPath) // } // // tableView.reloadData() // } else { let point = points[indexPath.row] ViewController.startLat = point.latitude ViewController.startLong = point.longitude ViewController.startName = point.name delegate!.didSelectHistory(self) let defaults = NSUserDefaults.standardUserDefaults() var lastPoint = (defaults.arrayForKey("lastPoint") as! [NSData]).map{NSKeyedUnarchiver.unarchiveObjectWithData($0) as! Point} lastPoint.removeAll() lastPoint.append(Point(latitude: point.latitude, longitude: point.longitude, name: "lastPoint")) let lastPoint_Archiver = lastPoint.map{ NSKeyedArchiver.archivedDataWithRootObject($0)} defaults.setObject(lastPoint_Archiver, forKey: "lastPoint") self.navigationController?.popViewControllerAnimated(true) // } } // MARK: - HistoryTableViewCell delegate func historyCellPressCheck(sender: AnyObject, indexPath: NSIndexPath) { if let button = sender as? UIButton { checked[indexPath.row] = button.selected } } }
// // LocationHandler.swift // ELRDRG // // Created by Jonas Wehner on 31.12.19. // Copyright © 2019 Martin Mangold. All rights reserved. // import UIKit import Foundation import CoreData import CoreLocation class LocationHandler: NSObject, CLLocationManagerDelegate { private let locationManager : CLLocationManager = CLLocationManager() private var enabled : Bool = false //Read Only public var serviceAvailable : Bool { //not sure if it is required get{ if let _ = currentLocation { return self.enabled } else { return false } } } private var currentLocation : CLLocation? private static var locationHandler : LocationHandler = { let handler = LocationHandler() //Checking if we have Autorization for Location Abbo if(handler.checkAutorization() == false) { handler.locationManager.requestAlwaysAuthorization() if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedAlways { handler.locationManager.requestWhenInUseAuthorization() } } if(handler.checkAutorization()) { handler.start() } return handler }() private func start() { if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters locationManager.startUpdatingLocation() enabled = true } else { enabled = false print("No Location Service enabled") } } private func checkAutorization()->Bool { switch CLLocationManager.authorizationStatus() { case CLAuthorizationStatus.authorizedAlways: return true case CLAuthorizationStatus.authorizedWhenInUse: return true default: return false } } //singleton pattern private override init() { } public static func shared()->LocationHandler { return locationHandler } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { self.currentLocation = locations.last } public func getCurrentLocation() -> CLLocation? { return self.currentLocation } public func getDistance(RemoteLocation lat : Double, RemoteLocation lng : Double)->Double { let location = CLLocation(latitude: lat, longitude: lng) if let ownLocation = self.currentLocation { let distance = ownLocation.distance(from: location) return distance } else { return -1 } } }
// // TransactionsListViewController.swift // Transactions // // Created by Thiago Santiago on 1/16/19. // Copyright © 2019 Thiago Santiago. All rights reserved. // import UIKit protocol TransactionsListDisplayLogic: class { func hideLoadingView() func displayLoadingView() func displayUser(image: UIImage) func displayError(message: String) func displayTransactions(list: TransactionsListViewModel) } class TransactionsListViewController: UIViewController { //MARK: Outlets @IBOutlet weak private var errorView: UIView! @IBOutlet weak private var headerView: UIView! @IBOutlet weak private var loadingView: UIView! @IBOutlet weak private var errorMessage: UILabel! @IBOutlet weak private var tableView: UITableView! @IBOutlet weak private var tryAgainButton: UIButton! @IBOutlet weak private var userImageView: UIImageView! @IBOutlet weak private var totalBalanceLabel: UILabel! @IBOutlet weak private var balancePeriodLabel: UILabel! //MARK: Properties private var nextpage = "" private var transactionData: [TransactionViewModel] = [] private var interactor: TransactionListInteractor? //MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() setup() self.interactor?.getTransactionsList() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.interactor?.loadUserImage() } private func setup() { self.tableView.delegate = self self.tableView.dataSource = self self.registerTableViewCells() let presenter = TransactionListPresenter() let interactor = TransactionListInteractor(presenter: presenter) self.interactor = interactor presenter.viewController = self configView() } private func verifyIfHasNextPage() { let hasNext = !self.nextpage.isEmpty if hasNext { self.interactor?.getTransactionsList(page: self.nextpage) } } private func configView() { self.tryAgainButton.layer.cornerRadius = 25 self.userImageView.setImageBorder(color: UIColor.white.cgColor, width: 2.0, radius: 30) self.headerView.setGradient(startColor: Colors.pink.cgColor, finalColor: Colors.blue.cgColor) } private func registerTableViewCells() { self.tableView.register(UINib(nibName: "BalanceItemCell", bundle: nil), forCellReuseIdentifier: "BalanceItemCell") } //MARK: Actions @IBAction func userProfilePressed(_ sender: Any) { TransactionAppRouter.routeToUserProfile() } @IBAction func tryAgainPressed(_ sender: Any) { self.interactor?.getTransactionsList() self.tryAgainButton.isEnabled = false } } //MARK: TransactionsListDisplayLogic extension TransactionsListViewController: TransactionsListDisplayLogic { func hideLoadingView() { self.loadingView.isHidden = true } func displayLoadingView() { self.loadingView.isHidden = false } func displayUser(image: UIImage) { self.userImageView.image = image } func displayError(message: String) { self.errorView.isHidden = false self.errorMessage.text = message self.tryAgainButton.isEnabled = true } func displayTransactions(list: TransactionsListViewModel) { self.errorView.isHidden = true self.nextpage = list.nextPage self.transactionData.append(contentsOf: list.transactions) self.totalBalanceLabel.text = list.totalBalance if let firstDate = list.transactions.first?.date, let lastDate = list.transactions.last?.date { self.balancePeriodLabel.text = "Balance of the period:\n \(firstDate) - \(lastDate)" } else { self.balancePeriodLabel.text = "Balance of the period" } self.tableView.reloadData() } } //MARK: UITableViewDelegate / UITableViewDataSource extension TransactionsListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return transactionData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "BalanceItemCell", for: indexPath) as? BalanceItemCell else { return UITableViewCell()} let transaction = transactionData[indexPath.row] cell.setContent(transaction: transaction) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { TransactionAppRouter.routeToDetails(transaction: transactionData[indexPath.row]) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == self.transactionData.count - 1 { self.verifyIfHasNextPage() } } }
// // customView.swift // custom control // // Created by Mathew Yates on 25/08/2016. // Copyright © 2016 Appcelerate. All rights reserved. // import UIKit @IBDesignable class easyTextField: UIView,UITextFieldDelegate { //MARK : - Members var contentView: UIView! var txtField: UITextField! var imageBackgroundView: UIView! var imgView: UIImageView! //MARK : - view setup variables //main view corner radius @IBInspectable var cornerRadius: CGFloat = 8.0{ didSet{ self.setupView() } } //main view border width @IBInspectable var borderWidth: CGFloat = 1.0{ didSet{ self.setupView() } } //main view border color @IBInspectable var borderColor: UIColor = UIColor.blackColor(){ didSet{ self.setupView() } } @IBInspectable var backgrndColor: UIColor = UIColor.whiteColor(){ didSet{ self.setupView() } } private func setupView() { //bg color self.contentView.backgroundColor = backgrndColor //border color self.contentView.layer.borderColor = borderColor.CGColor //border width self.contentView.layer.borderWidth = borderWidth //corner radius self.contentView.layer.cornerRadius = cornerRadius self.contentView.layer.masksToBounds = true //setup gesture to activate text field let gesture = UITapGestureRecognizer(target: self, action: #selector(easyTextField.showKeyboard(_:))) self.addGestureRecognizer(gesture) } //MARK : - textfield setup variables @IBInspectable var placeHolder: String = ""{ didSet{ self.setupTxtField() } } @IBInspectable var fontSize: CGFloat = 17 { didSet{ self.setupTxtField() } } @IBInspectable var fontFamily: String = "" { didSet{ self.setupTxtField() } } @IBInspectable var textColor: UIColor = UIColor.blackColor() { didSet{ self.setupTxtField() } } @IBInspectable var placeholderTextColor: UIColor = UIColor.lightGrayColor() { didSet{ self.setupTxtField() } } @IBInspectable var secureTextEntry: Bool = false { didSet{ self.setupTxtField() } } private func setupTxtField() { //set delegate txtField.delegate = self txtField.borderStyle = .None //set text color txtField.textColor = textColor //set font family and size if fontFamily == "" { txtField.font = UIFont.systemFontOfSize(fontSize) } else { txtField.font = UIFont(name: fontFamily, size: fontSize) } //set placeholder and color txtField.attributedPlaceholder = NSAttributedString(string: placeHolder, attributes: [NSForegroundColorAttributeName : placeholderTextColor]) //set secure text entry txtField.secureTextEntry = secureTextEntry } //MARK : - image background view setup variables @IBInspectable var imageBackgroundViewColor: UIColor = UIColor.lightGrayColor(){ didSet{ self.setupImageBGView() } } private func setupImageBGView() { imageBackgroundView.backgroundColor = imageBackgroundViewColor } //MARK : - image setup variables @IBInspectable var image: UIImage!{ didSet{ self.setupImageView() } } private func setupImageView() { imgView.image = image } override init(frame: CGRect) { //print("override init(frame: CGRect) ") super.init(frame: frame) //xibSetup() self.setup() } required init?(coder aDecoder: NSCoder) { //print("required init?(coder aDecoder: NSCoder)") super.init(coder: aDecoder) //xibSetup() self.setup() } private func setup() { initViews() self.setupView() self.setupTxtField() self.setupImageBGView() self.setupImageView() } //MARK : - Constraint Setup func initViews() -> Void { //initialize contentView = UIView() txtField = UITextField() imageBackgroundView = UIView() imgView = UIImageView() //prep autolayout contentView.translatesAutoresizingMaskIntoConstraints = false txtField.translatesAutoresizingMaskIntoConstraints = false imageBackgroundView.translatesAutoresizingMaskIntoConstraints = false imgView.translatesAutoresizingMaskIntoConstraints = false //add to the view self.addSubview(contentView) self.contentView.addSubview(imageBackgroundView) self.contentView.addSubview(txtField) self.imageBackgroundView.addSubview(imgView) self.setupConstraints() } func setupConstraints() { //set 1:1 ratio on image background view self.imageBackgroundView.addConstraint(NSLayoutConstraint( item: imageBackgroundView, attribute: .Width, relatedBy: .Equal, toItem: imageBackgroundView, attribute: .Height, multiplier: 1, constant: 0)) let views = ["contentView" : contentView, "imgBgView" : imageBackgroundView, "imgView" : imgView, "txtField" : txtField] var allConstraints = [NSLayoutConstraint]() //setup content view //horizontal let contentViewHorizontalViewConstraints = NSLayoutConstraint.constraintsWithVisualFormat( "H:|[contentView]|", options: [], metrics: nil, views: views) allConstraints += contentViewHorizontalViewConstraints //vertical let contentViewVerticalViewConstraints = NSLayoutConstraint.constraintsWithVisualFormat( "V:|[contentView]|", options: [], metrics: nil, views: views) allConstraints += contentViewVerticalViewConstraints //setup image background view and text field //horizontal let imgBgViewHorizontalConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "H:|[imgBgView]-8-[txtField]-8-|", options: [], metrics: nil, views: views) allConstraints += imgBgViewHorizontalConstraint //vertical image background view let imgBgViewVerticalConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "V:|[imgBgView]|", options: [], metrics: nil, views: views) allConstraints += imgBgViewVerticalConstraint //vertical textfield let txtFieldVerticalConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "V:|-5-[txtField]-5-|", options: [], metrics: nil, views: views) allConstraints += txtFieldVerticalConstraint //setup image view //vertical let imgViewVerticalConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "V:|-(>=4)-[imgView]-(>=4)-|", options: [], metrics: nil, views: views) allConstraints += imgViewVerticalConstraint //vertical let imgViewHorizontalConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "H:|-(>=4)-[imgView]-(>=4)-|", options: [], metrics: nil, views: views) allConstraints += imgViewHorizontalConstraint //add visual format language constraints self.addConstraints(allConstraints) let horizontalConstraint = NSLayoutConstraint(item: imgView, attribute: .CenterX, relatedBy: .Equal, toItem: imageBackgroundView, attribute: .CenterX, multiplier: 1, constant: 0) imageBackgroundView.addConstraint(horizontalConstraint) let verticalConstraint = NSLayoutConstraint(item: imgView, attribute: .CenterY, relatedBy: .Equal, toItem: imageBackgroundView, attribute: .CenterY, multiplier: 1, constant: 0) imageBackgroundView.addConstraint(verticalConstraint) } //MARK : - Show keyboard when view is selected func showKeyboard(sender:UITapGestureRecognizer) { if !self.txtField.isFirstResponder() { // do other task self.txtField.becomeFirstResponder() } else { txtField.resignFirstResponder() } } // MARK: - TextField Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { self.txtField.resignFirstResponder() return true } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { self.txtField = textField return true } func textFieldDidEndEditing(textField: UITextField) { self.txtField.resignFirstResponder() } }
// // IceRestartEvent.swift // Callstats // // Created by Amornchai Kanokpullwad on 10/16/18. // Copyright © 2018 callstats. All rights reserved. // import Foundation /** When ICE restarts, this event should be submitted */ class IceRestartEvent: IceEvent, Event, Encodable { var localID: String = "" var deviceID: String = "" var timestamp: Int64 = 0 let remoteID: String let connectionID: String let prevIceCandidatePair: IceCandidatePair let prevIceConnectionState: String let eventType = "iceRestarted" let currIceConnectionState = "new" init( remoteID: String, connectionID: String, prevIceCandidatePair: IceCandidatePair, prevIceConnectionState: String) { self.remoteID = remoteID self.connectionID = connectionID self.prevIceCandidatePair = prevIceCandidatePair self.prevIceConnectionState = prevIceConnectionState } }
// // ViewController.swift // KKAutoScrollView // // Created by 王铁山 on 2017/6/2. // Copyright © 2017年 king. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let autoScrollView = KKAutoScrollView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 180)) autoScrollView.imageModels = imageModels self.view.addSubview(autoScrollView) } var imageModels: [KKAutoScrollViewModel] { let urls = ["http://app.shenmajr.com/config/alpha/banner/feeStandard/feeStandard.jpg", "http://app.shenmajr.com/config/alpha/banner/pause_Notification/pause_Notification.jpg", "http://mmpt.shenmajr.com/files/dealers/homebanner/85599a05-6322-4ac3-896b-5af6047185f2/weChat_banner.html"] var result = [KKAutoScrollViewModel]() for url in urls { let model = KKAutoScrollViewModel.init() model.url = url model.isLocal = false model.phImage = UIImage.init(named: "a") result.append(model) } return result } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // setup+router.swift // // Created by Denis Bystruev on 21/09/2019. // import Foundation import Kitura import KituraStencil import LoggerAPI // MARK: - Setup Router func setup(_ router: Router) { router.setDefault(templateEngine: StencilTemplateEngine()) // MARK: - GET / router.get("/") { request, response, next in try response.render("home", context: [:]) next() } // MARK: - GET /categories router.get("/categories") { request, response, next in var categories = catalog.shop?.categories ?? [] // MARK: "id" if let ids = request.queryParametersMultiValues["id"]?.compactMap({ Int($0) }), !ids.isEmpty { categories = categories.filter({ if let id = $0.id { return ids.contains(id) } return false }) } // MARK: "name" if let name = request.queryParameters["name"] { categories = categories.filter { $0.name?.lowercased().contains(name.lowercased()) == true } } // MARK: "parentId" if let parentId = request.queryParameters["parentId"] { categories = categories.filter { $0.parentId == Int(parentId) } } // MARK: "from" if let from = request.queryParameters["from"]?.int { if 0 < from { if from < categories.count { categories = Array(categories[from...]) } else { categories = [] } } } // MARK: "limit" let limit = request.queryParameters["limit"]?.int ?? 24 if 0 <= limit && limit < categories.count { categories = Array(categories[..<limit]) } // MARK: "count" if request.queryParameters["count"] == nil { response.send(json: categories) } else { response.send(json: ["count": categories.count]) } next() } // MARK: - GET /currencies router.get("/currencies") { request, response, next in let currencies = catalog.shop?.currencies // MARK: "count" if request.queryParameters["count"] == nil { response.send(json: currencies) } else { response.send(json: ["count": currencies?.count]) } next() } // MARK: - GET /date router.get("/date") { request, response, next in response.send(json: ["date": catalog.date?.toString]) next() } // MARK: - GET /flushdb router.get("flushdb") { request, response, next in if let id = request.queryParameters["id"], id == "flushredisdb" { RedisManager.flushdb() response.send(json: ["flushdate": Date().toString]) } next() } // MARK: - GET /images router.get("/images") { request, response, next in let requestStartTime = Date() var images = catalog.shop?.images ?? [] var offerNames = [String]() // MARK: "categoryId" if let categoryIds = request.queryParametersMultiValues["categoryId"]?.compactMap({ Int($0) }), !categoryIds.isEmpty { images = images.filter({ if let categoryId = $0.categoryId { return categoryIds.contains(categoryId) } return false }) } // MARK: "offerId" if let offerIds = request.queryParametersMultiValues["offerId"]?.compactMap({ $0.isEmpty ? nil : $0.lowercased() }), !offerIds.isEmpty { images = images.filter({ if let offerId = $0.offerId?.lowercased() { return offerIds.contains(offerId) } return false }) } // MARK: "offerName" if let phrases = request.queryParametersMultiValues["offerName"]?.compactMap({ $0.isEmpty ? nil : $0.lowercased() }), !phrases.isEmpty { let words = phrases.flatMap { $0.split(separator: " ") }.map { String($0) } offerNames = words images = images.filter({ if let offerName = $0.offerName?.lowercased() { for word in words { guard offerName.contains(word) else { return false } } return true } return false }) } let total = images.count // MARK: "from" var from = request.queryParameters["from"]?.int ?? 0 from = min(images.count - 24, from) from = max(0, from) images = Array(images[from...]) // MARK: "format" let isHtml = request.queryParameters["format"]?.string.lowercased() == "html" // MARK: "limit" var limit = isHtml ? 24 : request.queryParameters["limit"]?.int ?? 24 limit = min(images.count, limit) limit = max(0, limit) images = Array(images[..<limit]) // MARK: "subid" let subid = request.queryParameters["subid"] if let nonOptionalSubid = subid { for index in 0 ..< images.count { images[index].setSubid(nonOptionalSubid) } } // MARK: "duration" let isTiming = request.queryParameters["duration"] != nil if isTiming { let duration = Date().timeIntervalSince(requestStartTime) response.send(json: ["duration": duration]) } else if request.queryParameters["count"] == nil { if isHtml { let offerNameString = "&offerName=" + offerNames.joined(separator: "&offerName=") let context: [String: Codable] = [ "images": images, "first": from + 1, "last": from + limit, "left5000": from - 5000, "left1000": from - 1000, "left500": from - 500, "left100": from - 100, "left": from - 24, "offerNameString": offerNameString, "offerNames": offerNames, "right": from + 24, "right100": from + 100, "right500": from + 500, "right1000": from + 1000, "right5000": from + 5000, "subid": subid, "total": total, ] try response.render("images", context: context) } else { response.send(json: images) } // MARK: "count" } else { response.send(json: ["count": images.count]) } next() } // MARK: - GET /modified_times router.get("/modified_times") { request, response, next in let offers = catalog.shop?.offers if let modifiedTimes = offers?.compactMap({ $0.modified_time }), let minTime = modifiedTimes.min(), let maxTime = modifiedTimes.max() { #if DEBUG Log.debug("Min Time: \(minTime), Max Time: \(maxTime)") #endif response.send(json: ["modified_time_min": minTime, "modified_time_max": maxTime]) } next() } // MARK: - GET /offers router.get("/offers", middleware: RedisManager.middleware) router.get("/offers") { request, response, next in let requestStartTime = Date() var offers = catalog.shop?.offers ?? [] // Show only available offers by default if request.queryParameters["available"] == nil && request.queryParameters["deleted"] == nil { offers = offers.filter { $0.available == true } } else { // MARK: "available" if let available = request.queryParameters["available"] { offers = offers.filter { $0.available == Bool(available) } } // MARK: "deleted" if let deleted = request.queryParameters["deleted"] { offers = offers.filter { $0.deleted == Bool(deleted) } } } // MARK: "id" if let ids = request.queryParametersMultiValues["id"]?.compactMap({ $0.isEmpty ? nil : $0.lowercased() }), !ids.isEmpty { offers = offers.filter({ if let id = $0.id?.lowercased() { return ids.contains(id) } return false }) } // MARK: "categoryId" if let categoryIds = request.queryParametersMultiValues["categoryId"]?.compactMap({ Int($0) }), !categoryIds.isEmpty { offers = offers.filter({ if let categoryId = $0.categoryId { return categoryIds.contains(categoryId) } return false }) } // MARK: "corner" if let corner = request.queryParameters["corner"]?.lowercased() { let categories: [Int?] switch corner { case "bottomleft": categories = [] case "bottomright": categories = [] case "middleright": categories = [] case "topleft": categories = [] case "topright": categories = [] default: categories = catalog.shop?.categories.compactMap({ $0.id }) ?? [] } offers = offers.filter { categories.contains($0.categoryId) } } // MARK: "currencyId" if let currencyId = request.queryParameters["currencyId"] { offers = offers.filter { $0.currencyId?.lowercased() == currencyId.lowercased() } } // MARK: "description" if let description = request.queryParameters["description"] { offers = offers.filter { $0.description?.lowercased().contains(description.lowercased()) == true } } // MARK: "manufacturer_warranty" if let manufacturer_warranty = request.queryParameters["manufacturer_warranty"] { offers = offers.filter { $0.manufacturer_warranty == Bool(manufacturer_warranty) } } // MARK: "model" if let model = request.queryParameters["model"] { offers = offers.filter { $0.model?.lowercased().contains(model.lowercased()) == true } } // MARK: "modified_after" if let modified_after = request.queryParameters["modified_after"] { if let userTime = TimeInterval(modified_after) { offers = offers.filter { offer in guard let offerTime = offer.modified_time else { return false } return userTime <= offerTime } } } // MARK: "modified_before" if let modified_before = request.queryParameters["modified_before"] { if let userTime = TimeInterval(modified_before) { offers = offers.filter { offer in guard let offerTime = offer.modified_time else { return false } return offerTime <= userTime } } } // MARK: "modified_time" if let modified_time = request.queryParameters["modified_time"] { offers = offers.filter { $0.modified_time == TimeInterval(modified_time) } } // MARK: "name" if let words = request.queryParametersMultiValues["name"]?.compactMap({ $0.isEmpty ? nil : $0.lowercased() }), !words.isEmpty { offers = offers.filter({ if let name = $0.name?.lowercased() { for word in words { guard name.contains(word) else { return false } } return true } return false }) } // MARK: "oldprice" if let oldprice = request.queryParameters["oldprice"] { offers = offers.filter { $0.oldprice == Decimal(string: oldprice) } } // MARK: "oldprice_above" if let oldprice_above = request.queryParameters["oldprice_above"] { if let userOldPrice = Decimal(string: oldprice_above) { offers = offers.filter { offer in guard let offerOldPrice = offer.oldprice else { return false } return userOldPrice <= offerOldPrice } } } // MARK: "oldprice_below" if let oldprice_below = request.queryParameters["oldprice_below"] { if let userOldPrice = Decimal(string: oldprice_below) { offers = offers.filter { offer in guard let offerOldPrice = offer.oldprice else { return false } return offerOldPrice <= userOldPrice } } } // MARK: "{params}" let paramNames = offers.flatMap({ $0.params.compactMap({ param in param.name?.lowercased() }) }) for name in Set(paramNames).sorted() { if let encodedName = name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { if let value = request.queryParameters[encodedName]?.lowercased() { offers = offers.filter { offer in for param in offer.params { if param.name?.lowercased() == name && param.value?.lowercased() == value { return true } } return false } } } } // MARK: "picture" if let picture = request.queryParameters["picture"] { offers = offers.filter { offer in for url in offer.pictures { if url.absoluteString.lowercased().contains(picture.lowercased()) { return true } } return false } } // MARK: "price" if let price = request.queryParameters["price"] { offers = offers.filter { $0.price == Decimal(string: price) } } // MARK: "price_above" if let price_above = request.queryParameters["price_above"] { if let userPrice = Decimal(string: price_above) { offers = offers.filter { offer in guard let offerPrice = offer.price else { return false } return userPrice <= offerPrice } } } // MARK: "price_below" if let price_below = request.queryParameters["price_below"] { if let userPrice = Decimal(string: price_below) { offers = offers.filter { offer in guard let offerPrice = offer.price else { return false } return offerPrice <= userPrice } } } // MARK: "sales_notes" if let sales_notes = request.queryParameters["sales_notes"] { offers = offers.filter { $0.sales_notes?.lowercased().contains(sales_notes.lowercased()) == true } } // MARK: "typePrefix" if let typePrefix = request.queryParameters["typePrefix"] { offers = offers.filter { $0.typePrefix?.lowercased().contains(typePrefix.lowercased()) == true } } // MARK: "url" if let url = request.queryParameters["url"] { offers = offers.filter { $0.url?.absoluteString.lowercased().contains(url.lowercased()) == true } } // MARK: "vendor" if let vendors = request.queryParametersMultiValues["vendor"]?.compactMap({ $0.isEmpty ? nil : $0.lowercasedLetters }), !vendors.isEmpty { var maxOffersByVendor = 0 var offersByVendor = [String: [YMLOffer]]() for offer in offers { guard let offerVendor = offer.vendor?.lowercasedLetters else { continue } for vendor in vendors { if offerVendor.contains(vendor) == true { let offers = offersByVendor[vendor, default: []] + [offer] maxOffersByVendor = max(maxOffersByVendor, offers.count) offersByVendor[vendor] = offers } } } offers.removeAll() for index in 0 ..< maxOffersByVendor { for vendor in vendors { guard let offersForVendor = offersByVendor[vendor] else { continue } guard index < offersForVendor.count else { continue } offers.append(offersForVendor[index]) } } } // MARK: "vendorCode" if let vendorCode = request.queryParameters["vendorCode"] { offers = offers.filter { $0.vendorCode?.lowercased() == vendorCode.lowercased() } } // MARK: "from" if let from = request.queryParameters["from"]?.int { if 0 < from { if from < offers.count { offers = Array(offers[from...]) } else { offers = [] } } } // MARK: "limit" let limit = request.queryParameters["limit"]?.int ?? 24 if 0 <= limit && limit < offers.count { offers = Array(offers[..<limit]) } let isCounting = request.queryParameters["count"] != nil let isTiming = request.queryParameters["duration"] != nil if isTiming { // MARK: "duration" let duration = Date().timeIntervalSince(requestStartTime) response.send(json: ["duration": duration]) } else if isCounting { // MARK: "count" response.send(json: ["count": offers.count]) } else { response.send(offers) if let data = try? JSONEncoder().encode(offers), let jsonString = String(data: data, encoding: .utf8) { RedisManager.set(request: request, value: jsonString) } } next() } // MARK: - GET /params router.get("/params") { request, response, next in let isCounting = request.queryParameters["count"] != nil let offers = catalog.shop?.offers if let paramNames = offers?.flatMap({ $0.params.compactMap({ param in param.name?.lowercased() }) }) { let names = Set(paramNames).sorted() var result = [String: [String]]() for name in names { if let paramValues = offers?.flatMap({ $0.params .filter({ param in param.name?.lowercased() == name }) .compactMap({ param in param.value }) }) { result[name] = Set(paramValues).sorted() } } // MARK: "count" if isCounting { response.send(json: ["count": result.count]) } else { response.send(json: result) } } else { if isCounting { response.send(json: ["count": 0]) } else { response.send(json: [String: [String]]()) } } next() } // MARK: - GET /prices router.get("/prices") { request, response, next in let offers = catalog.shop?.offers if let priceRange = offers?.compactMap({ $0.price }), let minPrice = priceRange.min(), let maxPrice = priceRange.max() { #if DEBUG Log.debug("Min Price: \(minPrice), Max Price: \(maxPrice)") #endif response.send(json: ["price_min": minPrice, "price_max": maxPrice]) } next() } // MARK: - GET /server router.get("/server") { request, response, next in // response.send(json: ["server": "http://server.getoutfit.ru"]) response.send(json: ["server": "http://spb.getoutfit.co:8888"]) next() } // MARK: - GET /stylist router.get("/stylist") { request, response, next in var context: [String: String] = [:] guard let subid = request.queryParameters["subid"] else { try response.status(.badRequest).end() return } context["subid"] = subid if let url = request.queryParameters["url"] { let prefix = "https://modato.ru/g/3f2779c2d4f6f0a2c5434e8640d77b/?ulp=" context["delim"] = "&" context["url"] = "\(prefix)\(url)" } Log.info("Generated links for subid: \(subid)") try response.render("stylist", context: context) next() } // MARK: - GET /update router.get("/update") { request, response, next in updateCatalog() response.send(json: ["date": catalog.date?.toString]) next() } // MARK: - GET /vendors router.get("/vendors") { request, response, next in let offers = catalog.shop?.offers if let allVendors = offers?.compactMap({ $0.vendor }) { let uniqueVendors = Array(Set(allVendors)).sorted() response.send(json: ["vendors": uniqueVendors]) } next() } }
// // ProductTableViewController.swift // PupCare // // Created by Uriel Battanoli on 7/5/16. // Copyright © 2016 PupCare. All rights reserved. // import UIKit class ProductTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UITextFieldDelegate { // MARK: outlets @IBOutlet weak var tableView: UITableView! @IBOutlet weak var petShopImage: UIImageView! @IBOutlet weak var petShopName: UILabel! @IBOutlet weak var petShopAdress: UILabel! @IBOutlet weak var petShopNeighbourhood: UILabel! @IBOutlet weak var petShopDistance: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var TableViewConstraint: NSLayoutConstraint! // MARK: Variables var petShop: PetShop? var products: [Product]?{ didSet{ self.tableView.reloadData() } } var filteredProducts: [Product] = [] var tap: UITapGestureRecognizer! var refreshControl: UIRefreshControl?{ didSet{ self.refreshControl?.attributedTitle = NSAttributedString(string: "Puxe para Atualizar") self.refreshControl?.addTarget(self, action: #selector(ProductTableViewController.reloadProducts), for: .valueChanged) self.tableView.addSubview(self.refreshControl!) } } //MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() self.tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard)) self.title = "Detalhes da Pet Shop" self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Voltar", style: .plain, target: nil, action: nil) self.searchBar.delegate = self if let searchField = self.searchBar.value(forKey: "searchField") as? UITextField{ searchField.backgroundColor = self.searchBar.backgroundColor searchField.textColor = UIColor.white self.searchBar.barTintColor = UIColor.white self.searchBar.backgroundColor = UIColor.white if let placeholder = searchField.value(forKey: "placeholderLabel") as? UILabel{ placeholder.textColor = UIColor.white } } self.refreshControl = UIRefreshControl() self.tableView.tableFooterView = UIView() if let petShop = self.petShop{ self.petShopName.text = petShop.name self.petShopAdress.text = "\(petShop.address.street) - \(petShop.address.number)" self.petShopImage.loadImage(petShop.imageUrl) self.petShopNeighbourhood.text = petShop.address.neighbourhood if let location = UserManager.sharedInstance.getLocationToSearch(){ var distance = Float(petShop.address.location.distance(from: location)) distance = distance / 1000 self.petShopDistance.text = "Distância: \(distance.roundToPlaces(2)) km" } if petShop.products.count > 0{ self.products = petShop.products } else{ ProductManager.sharedInstance.getProductList(petShop.objectId, block: { (products) in petShop.products = products self.products = products }) } } } override func viewWillAppear(_ animated: Bool) { checkCart() } //MARK: Adjust Constraints func checkCart() { if Cart.sharedInstance.cartDict.petShopList.count > 0 { //.getTotalItemsAndPrice().0 > 0 { adjustConstraintsForCart() } else { adjustConstraintsToHideCart() } } func adjustConstraintsForCart() { self.TableViewConstraint.constant = 75 } func adjustConstraintsToHideCart() { self.TableViewConstraint.constant = 0 } // MARK: Table view data source func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if !(self.searchBar.text?.isEmpty)! { return self.filteredProducts.count } else{ return self.products?.count ?? 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellProduct", for: indexPath) as! ProductTableViewCell let product: Product! if !(self.searchBar.text?.isEmpty)! { product = self.filteredProducts[(indexPath as NSIndexPath).row] } else { product = self.products![(indexPath as NSIndexPath).row] } cell.product = product cell.lblPrice.text = product.price.numberToPrice() return cell } // MARK: Table view delegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 90 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var product: Product! if !(self.searchBar.text?.isEmpty)! { product = self.filteredProducts[(indexPath as NSIndexPath).row] } else { product = self.products![(indexPath as NSIndexPath).row] } performSegue(withIdentifier: "goToDetail", sender: product) tableView.deselectRow(at: indexPath, animated: false) } // MARK: SearchBar delegate func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { self.filterProductsForSearchText(searchText) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = "" self.filterProductsForSearchText("") self.view.endEditing(true) } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { view.addGestureRecognizer(tap) } override func dismissKeyboard() { view.endEditing(true) } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { view.removeGestureRecognizer(tap) } // MARK: Functions override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToDetail"{ let productDetail = segue.destination as! ProductDetailViewController productDetail.product = sender as? Product productDetail.petshop = self.petShop } } func filterProductsForSearchText(_ searchText: String, scope: String = "All") { self.filteredProducts = products!.filter { product in return product.name.lowercased().contains(searchText.lowercased()) } self.tableView.reloadData() if searchText.isEmpty{ searchBar.showsCancelButton = false }else{ searchBar.showsCancelButton = true } } func reloadProducts() { ProductManager.sharedInstance.getProductList((petShop?.objectId)!) { (products) in self.products = products self.refreshControl?.endRefreshing() } } } extension ProductTableViewController: UISearchResultsUpdating{ func updateSearchResults(for searchController: UISearchController) { filterProductsForSearchText(searchController.searchBar.text!) } }
// // iTipJarConfigurationTests.swift // iTipJarMaster // // Created by Andrew Halls on 9/26/14. // Copyright (c) 2014 Thinkful. All rights reserved. // import UIKit import XCTest class iTipJarConfigurationTests: XCTestCase { func testItShouldHaveDefaultStoreIdentifers() { let expected = "com.thinkful.iTipJarMaster.store.0" let result = iTipJarConfiguration.storeIdentifer(0) XCTAssertEqual(result, expected) } func testItShouldHaveDefaultStoreIdentifersEndofRange() { let expected = "com.thinkful.iTipJarMaster.store.2" let result = iTipJarConfiguration.storeIdentifer(2) XCTAssertEqual(result, expected) } func testItShouldSetIdentfier() { let expected = "com.thinkful.iTipJarMaster.store.special" iTipJarConfiguration.setStoreIdentifer(0, identifer: expected) let result = iTipJarConfiguration.storeIdentifer(0) XCTAssertEqual(result, expected) } }
// // DebugAlloc.swift // Server // // Created by Christopher G Prince on 8/29/20. // import Foundation import LoggerAPI class DebugAlloc { private var created = 0 private var destroyed = 0 let name: String init(name: String) { self.name = name } func create() { created += 1 Log.debug("[CREATE: \(name)] Created: \(created); destroyed: \(destroyed)") } func destroy() { destroyed += 1 Log.debug("[DESTROY: \(name)] Created: \(created); destroyed: \(destroyed)") } }
// // UserProgressionButton.swift // Apprendre les verbes irréguliers // // Created by Lauriane Mollier on 13/10/2018. // Copyright © 2018 Lauriane Mollier. All rights reserved. // import UIKit class UserProgressionButton: UIButton { var userProgression: UserProgression! private let iconImageView = UIImageView() private let nbrVerbLabel = UILabel() var borderHorizontal: CGFloat! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit(){ self.addSubview(self.iconImageView) } public func setUp(userProgression: UserProgression) { self.userProgression = userProgression self.borderHorizontal = self.frame.width * 0.048731 if let image = userProgression.image(){ // set the icon setUpIcon(image: image, borderHorizontal: borderHorizontal) setUpText(withIcon: true, userProgression: userProgression, borderHorizontal: borderHorizontal) } else{ // No icon setUpText(withIcon: false, userProgression: userProgression, borderHorizontal: borderHorizontal) } // set layer setUpLayer() } // set the icon private func setUpIcon(image: UIImage, borderHorizontal: CGFloat){ self.iconImageView.image = image let imgRation: CGFloat = 1 let imgHeight = self.frame.height * 0.7065 let imgY = (self.frame.height - imgHeight) / 2 let imgX = borderHorizontal self.iconImageView.frame = CGRect(x: imgX, y: imgY, width: imgHeight * imgRation, height: imgHeight) } // set the text private func setUpText(withIcon: Bool, userProgression: UserProgression, borderHorizontal: CGFloat){ self.contentHorizontalAlignment = .left if withIcon{ self.titleEdgeInsets.left = self.frame.width * 0.19 } else{ self.titleEdgeInsets.left = borderHorizontal } self.setTitle(userProgression.name(), for: .normal) } private func setUpLayer(){ // self.titleLabel?.font = UIFont.appBoldFontWith(size: self.titleLabel?.font.pointSize) self.layer.shadowRadius = 5 self.layer.shadowColor = UIColor(rgb: 0xa68282).cgColor self.backgroundColor = UIColor.white self.layer.shadowOffset = CGSize(width: 3, height: 3) self.layer.cornerRadius = 7 } }
import XCTest import BowLaws import Bow class ConstTest: XCTestCase { func testEquatableLaws() { EquatableKLaws<ConstPartial<Int>, Int>.check() } func testHashableLaws() { HashableKLaws<ConstPartial<Int>, Int>.check() } func testFunctorLaws() { FunctorLaws<ConstPartial<Int>>.check() } func testApplicativeLaws() { ApplicativeLaws<ConstPartial<Int>>.check() } func testSemigroupLaws() { SemigroupLaws<Const<Int, Int>>.check() } func testMonoidLaws() { MonoidLaws<Const<Int, Int>>.check() } func testCustomStringConvertibleLaws() { CustomStringConvertibleLaws<Const<Int, Int>>.check() } func testFoldableLaws() { FoldableLaws<ConstPartial<Int>>.check() } func testTraverseLaws() { TraverseLaws<ConstPartial<Int>>.check() } }
import accepton enum AcceptOnAPIPaymentMethodsInfoFactoryProperty: Equatable { case Stripe(key: String?, isBogus: Bool) case PayPalRest(key: String?, isBogus: Bool) case Braintree(key: String?, isBogus: Bool) case SupportsCreditCards case WithoutAnyCreditCardPaymentProcessors case Bogus //All security tokens, etc are 100% bogus case Sandbox //Tokens are valid and pulled from a server (but are sandboxed versions) } //This allows you to search via bogus/non-bogus keys func ==(lhs: AcceptOnAPIPaymentMethodsInfoFactoryProperty, rhs: AcceptOnAPIPaymentMethodsInfoFactoryProperty) -> Bool { switch (lhs, rhs) { case (.Stripe(_, let bl), .Stripe(_, let br)) where bl == br: return true case (.PayPalRest(_, let bl), .Stripe(_, let br)) where bl == br: return true case (.Braintree(_, let bl), .Braintree(_, let br)) where bl == br: return true case (.SupportsCreditCards, .SupportsCreditCards): return true case (.WithoutAnyCreditCardPaymentProcessors, .WithoutAnyCreditCardPaymentProcessors): return true case (.Bogus, .Bogus): return true case (.Sandbox, .Sandbox): return true default: return false } } struct AcceptOnAPIPaymentMethodsInfoFactoryResult { let paymentMethodsInfo: AcceptOnAPIPaymentMethodsInfo let transactionTokenFactoryResult: AcceptOnAPITransactionTokenFactoryResult! init(_ paymentMethodsInfo: AcceptOnAPIPaymentMethodsInfo) { self.paymentMethodsInfo = paymentMethodsInfo self.transactionTokenFactoryResult = nil } init(paymentMethodsInfo: AcceptOnAPIPaymentMethodsInfo, transactionTokenFactoryRes: AcceptOnAPITransactionTokenFactoryResult) { self.paymentMethodsInfo = paymentMethodsInfo self.transactionTokenFactoryResult = transactionTokenFactoryRes } } class AcceptOnAPIPaymentMethodsInfoFactory: Factory<AcceptOnAPIPaymentMethodsInfoFactoryResult, AcceptOnAPIPaymentMethodsInfoFactoryProperty> { required init() { super.init() context(.SupportsCreditCards, .Bogus) { self.product(.WithoutAnyCreditCardPaymentProcessors) { AcceptOnAPIPaymentMethodsInfoFactoryResult(AcceptOnAPIPaymentMethodsInfo.parseConfig([ "payment_methods": ["credit-card"], "processor_information": [ "credit-card": [] ] ])!) } var stripePublishableKey: String { return "bogus-stripe-publishable-key-xxxxx>" } self.context(.Stripe(key: stripePublishableKey, isBogus: true)) { self.product { AcceptOnAPIPaymentMethodsInfoFactoryResult( AcceptOnAPIPaymentMethodsInfo.parseConfig([ "payment_methods": ["credit-card"], "processor_information": [ "credit-card": [ "stripe": ["publishable_key": stripePublishableKey] ] ] ])!) } } var paypalClientId: String { return "bogus-paypal-client-id-xxxxx" } self.context(.PayPalRest(key: paypalClientId, isBogus: true)) { self.product { AcceptOnAPIPaymentMethodsInfoFactoryResult( AcceptOnAPIPaymentMethodsInfo.parseConfig([ "payment_methods": ["credit-card"], "processor_information": [ "credit-card": [ "paypal_rest": ["client_id": paypalClientId] ] ] ])!) } } } context(.Sandbox) { AcceptOnAPITransactionTokenFactory.withAtleast(.Sandbox).each { tokenInfo, desc in self.product(properties: [], withExtraDesc: ["tokenDesc": desc]) { let sem = dispatch_semaphore_create(0) var paymentMethodsRes: AcceptOnAPIPaymentMethodsInfo! tokenInfo.api!.getAvailablePaymentMethodsForTransactionWithId(tokenInfo.token.id, completion: { (paymentMethods, error) -> () in paymentMethodsRes = paymentMethods dispatch_semaphore_signal(sem) }) dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) return AcceptOnAPIPaymentMethodsInfoFactoryResult(paymentMethodsInfo: paymentMethodsRes, transactionTokenFactoryRes: tokenInfo) } } } } }
// // FloraDetailsViewController.swift // florafinder // // Created by Andrew Tokeley on 26/04/16. // Copyright © 2016 Andrew Tokeley . All rights reserved. // import Foundation import NYTPhotoViewer //class specialButton: UIButton, NYTPhotoCaptionViewLayoutWidthHinting //{ // var preferredMaxLayoutWidth: CGFloat // { // set{} // get{return 100} // } //} class FloraDetailsViewController: UITableViewController, NYTPhotosViewControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIActionSheetDelegate { var isFound = false let SESSION_KEY_PREFIX = "FloraDetailsImageRecords_" let ACTION_FOUND = "Found it!" let ACTION_NOT_FOUND = "Not Found!" let ACTION_SHOW_MAP = "View Map" var flora: Flora? var showAllDetails: Bool = false var photos: [NYTPhoto] = [] var layoutGigDone: Bool = false //MARK: - Constants let COLLECTIONVIEW_ICONS = 0 let COLLECTIONVIEW_PHOTOS = 1 let NO_INFO = "-" let SEGUE_EDIT = "edit" let SEGUE_REFERENCE = "reference" let SECTION_HEADER = 0 let ROW_DETAILS = 0 let HEIGHT_DETAILS_LESS_LABEL: CGFloat = 70 let MAX_HEIGHT_OF_DESCRIPTION_BEFORE_MORE_BUTTON: CGFloat = 118 let SECTION_PHOTOS = 1 let ROW_PHOTOS = 1 let SECTION_REFERENCES = 2 let ROW_REFERENCE_1 = 0 //MARK: Outlets @IBOutlet weak var iconsCollectionView: UICollectionView! //@IBOutlet weak var moreDetailsButton: UIButton! @IBOutlet weak var photosView: UICollectionView! @IBOutlet weak var fullDescription: UILabel! @IBOutlet weak var externalReferenceURL: UIButton! @IBOutlet weak var commonName: UILabel! @IBOutlet weak var latinName: UILabel! @IBOutlet weak var photoCell: UITableViewCell! @IBOutlet weak var moreButtonItem: UIBarButtonItem! var leafDescriptions = [String]() //MARK: UIViewController override func viewDidLoad() { configureView() } override func viewWillLayoutSubviews() { // Required to ensure the correct size of the header tablecell. When relying on the tableView:heightForRowAtIndexPath it doesn't have the correct label height until this method is called. if (!layoutGigDone) { //super.viewWillLayoutSubviews() self.tableView.beginUpdates() self.tableView.endUpdates() layoutGigDone = true } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == SEGUE_EDIT) { if let controller = segue.destinationViewController as? FloraViewController { if let flora = self.flora { self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) controller.prepareForEdit(flora) } } } else if (segue.identifier == SEGUE_REFERENCE) { if let controller = segue.destinationViewController as? ReferenceViewController { if let flora = self.flora { controller.prepareForView(flora) } } } } lazy var spinner: UIActivityIndicatorView = { let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) spinner.hidesWhenStopped = true spinner.stopAnimating() return spinner }() //MARK: Functions func configureView() { let session = ServiceFactory.shareInstance.sessionStateService if let imageRoot = flora?.imagePath { // Check cache first let sessionKey = SESSION_KEY_PREFIX + imageRoot if let imageRecords = session.state[sessionKey] as? [ImageRecord] { self.photos = imageRecords self.photosView.reloadData() } else { photoCell.accessoryView = spinner spinner.startAnimating() let service = ServiceFactory.shareInstance.imageService var imageRecords = [ImageRecord]() service.getImageRecords(imageRoot, recordFound: { (imageRecord, index, count) in imageRecords.append(imageRecord) session.state[sessionKey] = imageRecords self.photos.append(imageRecord) self.photosView.reloadData() print("index \(index), count \(count)") if (index == (count - 1)) { self.spinner.stopAnimating() } }) } } iconsCollectionView.backgroundColor = UIColor.whiteColor() photosView.backgroundColor = UIColor.whiteColor() externalReferenceURL.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left commonName.text = flora?.commonName fullDescription.text = flora?.description fullDescription.sizeToFit() latinName.text = flora?.scientificName ?? "-" if let reference = flora?.externalURL { externalReferenceURL.setAttributedTitle(NSAttributedString(string: reference), forState: UIControlState.Normal) } iconsCollectionView.transform = CGAffineTransformMakeScale(-1, 1) } func prepareForView(flora: Flora) { self.flora = flora self.title = "" } lazy var iconImages: [UIImage] = { var images = [UIImage]() if let flowerColor = self.flora?.flowerColor?.color as? UIColor { if let image = UIImage(named: "flower.png") { images.append(image.changeColor(flowerColor)!) } } if let fruitColor = self.flora?.fruitColor?.color as? UIColor { if let image = UIImage(named: "fruit.png") { images.append(image.changeColor(fruitColor)!) } } if let edge = self.flora?.leafUpper?.edgeType { if let type = LeafEdgeTypeEnum(rawValue: edge.name!) { images.append(type.image()) } } if let formation = self.flora?.leafUpper?.formationType { if let type = LeafFormationTypeEnum(rawValue: formation.name!) { images.append(type.image()) } } return images }() func previewImage(photo: NYTPhoto) { let controller = NYTPhotosViewController(photos: self.photos, initialPhoto: photo) controller.delegate = self self.presentViewController(controller, animated: false, completion: nil) } //MARK: TableView override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let PADDING: CGFloat = 8 // For all rows in the Leaves section, apart from the header row if (indexPath.section == SECTION_HEADER && indexPath.row == ROW_DETAILS) { return fullDescription.frame.height + HEIGHT_DETAILS_LESS_LABEL + PADDING } return super.tableView(tableView, heightForRowAtIndexPath: indexPath) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == SECTION_REFERENCES && flora?.externalURL == nil) { return 0 } return super.tableView(tableView, numberOfRowsInSection: section) } //MARK: - NYTPhotosViewControllerDelegate func photosViewController(photosViewController: NYTPhotosViewController, handleActionButtonTappedForPhoto photo: NYTPhoto) -> Bool { if UIDevice.currentDevice().userInterfaceIdiom == .Pad { guard let photoImage = photo.image else { return false } let shareActivityViewController = UIActivityViewController(activityItems: [photoImage], applicationActivities: nil) shareActivityViewController.completionWithItemsHandler = {(activityType: String?, completed: Bool, items: [AnyObject]?, error: NSError?) in if completed { photosViewController.delegate?.photosViewController!(photosViewController, actionCompletedWithActivityType: activityType!) } } shareActivityViewController.popoverPresentationController?.barButtonItem = photosViewController.rightBarButtonItem photosViewController.presentViewController(shareActivityViewController, animated: true, completion: nil) return true } return false } // func photosViewController(photosViewController: NYTPhotosViewController, captionViewForPhoto photo: NYTPhoto) -> UIView? // { // return nil // } // func deletePhoto(sender: UILabel) // { // photos.removeAtIndex(sender.tag) // } //MARK: Actions @IBAction func moreButton(sender: UIBarButtonItem) { var action: UIActionSheet if (isFound) { action = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: ACTION_NOT_FOUND , ACTION_SHOW_MAP) } else { action = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: ACTION_FOUND , ACTION_SHOW_MAP) } action.showInView(self.view) } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { if let selectedTitle = actionSheet.buttonTitleAtIndex(buttonIndex) { switch selectedTitle { case ACTION_FOUND: isFound = true break case ACTION_NOT_FOUND: isFound = false break case ACTION_SHOW_MAP: break default: break } } } //MARK: Photo CollectionView func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var count = photos.count if (collectionView.tag == COLLECTIONVIEW_ICONS) { count = iconImages.count } return count } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if collectionView.tag == COLLECTIONVIEW_PHOTOS { previewImage(self.photos[indexPath.row]) } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath:indexPath) as! ImageCollectionViewCell if collectionView.tag == COLLECTIONVIEW_PHOTOS { cell.image.image = photos[indexPath.row].image } else if collectionView.tag == COLLECTIONVIEW_ICONS { cell.rightAlign = true cell.image.image = iconImages[indexPath.row] } return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var size = CGSize(width: 100, height: 100) if collectionView.tag == COLLECTIONVIEW_ICONS { size = CGSize(width: 20, height: 20) } return size } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { var insets = UIEdgeInsets(top: 2, left: 10, bottom: 0, right: 10) if collectionView.tag == COLLECTIONVIEW_ICONS { insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } return insets } }
// // PlanWorkoutVC.swift // PUSH_IT // // Created by Katherine Reinhart on 1/30/18. // Copyright © 2018 reinhart.digital. All rights reserved. // import UIKit class PlanWorkoutVC: UIViewController, UITableViewDataSource, UITableViewDelegate, SaveWorkoutDelegate, SaveExerciseCellDelegate { // Outlets @IBOutlet weak var menuBtn: UIButton! @IBOutlet weak var planWorkoutTV: UITableView! // Variables var exercises = WorkoutDataService.instance.activeWorkout?.exercises // Lifecycle override func viewDidLoad() { super.viewDidLoad() planWorkoutTV.dataSource = self planWorkoutTV.delegate = self if WorkoutDataService.instance.activeWorkoutID == nil { WorkoutDataService.instance.createNewWorkout() } // Keyboard slide up/down stuff NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) // hide keyboard when tapped around self.hideKeyboardWhenTappedAround() // Menu button stuff menuBtn.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) } // Table view methods func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { if exercises == nil { return 0 } else { return exercises!.count } } else if section == 1 { return 1 } return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = indexPath.section if section == 0 { let cell = Bundle.main.loadNibNamed(EXERCISE_TV_CELL, owner: self, options: nil)?.first as! ExerciseTVCell cell.exerciseNameLbl.text = exercises![indexPath.row].type cell.weightLbl.text = String(exercises![indexPath.row].goalWeight) cell.repsLbl.text = String(exercises![indexPath.row].goalRepsPerSet) cell.setsLbl.text = String(exercises![indexPath.row].goalSets) cell.selectionStyle = .none return cell } else if section == 1 { let cell = Bundle.main.loadNibNamed(NEW_EX_TV_CELL, owner: self, options: nil)?.first as! NewExerciseTVCell cell.selectionStyle = .none cell.delegate = self return cell } else { let cell = Bundle.main.loadNibNamed(SAVE_TV_CELL, owner: self, options: nil)?.first as! SaveWorkoutTVCell cell.selectionStyle = .none cell.delegate = self return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let section = indexPath.section if section == 0 { return 155.5 } else if section == 1 { return 253 } else { return 64 } } // Custom delegate methods func didPressSaveWorkoutButton(_ sender: SaveWorkoutTVCell) { if WorkoutDataService.instance.activeWorkout == nil || WorkoutDataService.instance.activeWorkout!.exercises.count == 0 { return } WorkoutDataService.instance.markWorkoutSaved() self.performSegue(withIdentifier: BACK_TO_DASHBOARD, sender: self) } func didPressSaveBtn(_ sender: NewExerciseTVCell, exercise: Exercise) { WorkoutDataService.instance.addExerciseToActiveWorkout(exercise: exercise) exercises = WorkoutDataService.instance.activeWorkout?.exercises self.planWorkoutTV.reloadData() } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window) } // Keyboard slide up and down functions @objc func keyboardWillShow(notification: NSNotification) { if exercises != nil, exercises!.count > 0, let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0{ self.view.frame.origin.y -= keyboardSize.height } } } @objc func keyboardWillHide(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0{ self.view.frame.origin.y += keyboardSize.height } } } }
// // File.swift // // // Created by Ganesh Somani on 04/07/21. // import Danger let danger = Danger() let editedFiles = danger.git.modifiedFiles + danger.git.createdFiles message("These files have changed: \(editedFiles.joined(separator: ", "))")
// // DatabaseController.swift // CountriesTask // // Created by Amr Mohamed on 4/12/20. // Copyright © 2020 amr. All rights reserved. // import Foundation import RealmSwift class DatabaseController { let realm = try! Realm() func save(countryname:Country) { try! realm.write { countryname.isFavourite = true realm.add(countryname ,update:.modified) } } func delete(countryname:Country) { if (getSaved().contains(countryname)) { try? realm.write { realm.delete(countryname) } } } func getSaved() -> [Country] { let countries = realm.objects(Country.self).filter("isFavourite == true") return countries.toArray(ofType: Country.self) } }
// // ServiceInformation.swift // mobil grpB part calculator // // Created by Sium on 7/22/17. // Copyright © 2017 Mobioapp. All rights reserved. // import UIKit import os.log class ServiceInformation: NSObject, NSCoding { //Mark: Type struct PropertyKey { static let vehicleNameProperty = "vehicleName" static let districtNameProperty = "districtName" static let areaNameProperty = "areaName" static let workShopNameProperty = "workShopName" } //Mark: properties var vehicleName: String var districtName: String var areaName: String var workShopName: String //Mark: Archiving Paths static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! static let ArchiveURL = DocumentsDirectory.appendingPathComponent("allAppointments") init(vehicleNameInit: String, districtNameInit: String , areaNameInit: String, workShopNameInit: String ) { vehicleName = vehicleNameInit districtName = districtNameInit areaName = areaNameInit workShopName = workShopNameInit } //Mark: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(vehicleName, forKey: PropertyKey.vehicleNameProperty) aCoder.encode(districtName, forKey: PropertyKey.districtNameProperty) aCoder.encode(areaName, forKey: PropertyKey.areaNameProperty) aCoder.encode(workShopName, forKey: PropertyKey.workShopNameProperty ) } required convenience init?(coder aDecoder: NSCoder) { guard let vehicleName = aDecoder.decodeObject(forKey: PropertyKey.vehicleNameProperty) as? String else { os_log("Unable to decode the name for a ServiceInformation object.", log: OSLog.default, type: .debug) return nil } let districtName = aDecoder.decodeObject(forKey: PropertyKey.districtNameProperty) as? String let areaName = aDecoder.decodeObject(forKey: PropertyKey.areaNameProperty) as? String let workShopName = aDecoder.decodeObject(forKey: PropertyKey.workShopNameProperty) as? String self.init(vehicleNameInit: vehicleName, districtNameInit: districtName!, areaNameInit: areaName!, workShopNameInit: workShopName!) } }
// // UsersAPI.swift // Carly // // Created by Mitch Lusas on 5/9/15. // Copyright (c) 2015 hiddenPlanet. All rights reserved. // import Foundation
// // Question.swift // quiz // // Created by Brian Xu on 6/7/2018. // Copyright © 2018 Fake Name. All rights reserved. // import Foundation class Question : CustomStringConvertible { var question: String = "" var answers: [String] = [] // MARK: CustomStringConvertible var description: String { return "\(question)\n" } }
import UIKit class AcceptWIFIViewController: UIViewController, OnboardingChild { var state: OnboardingState = .none weak var delegate: OnboardingDelegate? var parentOnboardingViewController: OnboardingViewController? @IBOutlet weak var headerLabel: UILabel! @IBOutlet weak var switchDescriptionLabel: UILabel! @IBOutlet weak var acceptWifiButton: LightRoundButton! var wifiName: String? override func viewDidLoad() { super.viewDidLoad() acceptWifiButton.isEnabled = false NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { [weak self] (notificaiton) in self?.receiveWifiName() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) receiveWifiName() } func receiveWifiName() { parentOnboardingViewController?.gameCoordinator?.receiveSSID({ [weak self] (ssid, error) in guard let strongSelf = self else { return } if let error = error { switch error { case .general: strongSelf.headerLabel.text = "Etwas ist schiefgelaufen beim Abfragen deines Wifi's." break case .noLocationService: strongSelf.headerLabel.text = "Du musst deinen Standort aktivieren, damit wir auf deine Wifi-Einstellungen zugreifen können!" break case .noWifi: strongSelf.headerLabel.text = "Du bist mit keinem Wifi Netzwerk verbunden!" break } strongSelf.switchDescriptionLabel.isEnabled = false strongSelf.acceptWifiButton.isEnabled = false return } strongSelf.wifiName = ssid strongSelf.acceptWifiButton.isEnabled = true }) } @IBAction func acceptWifiButtonTapped(_ sender: Any) { state = .done delegate?.stateChanged(self, to: state) acceptWifiButton.isEnabled = false acceptWifiButton.setTitle("Super, danke!", for: .disabled) acceptWifiButton.backgroundColor = acceptWifiButton.backgroundColor?.withAlphaComponent(0.5) } }
// // BubbleNode.swift // Example // // Created by Neverland on 15.08.15. // Copyright (c) 2015 ProudOfZiggy. All rights reserved. // import Foundation import UIKit import SpriteKit enum BubbleNodeColor { case Red case Blue } class Circle : SKSpriteNode { var fillSprite : SKSpriteNode! var cropNode : SKCropNode! var maskNode : SKSpriteNode! var lightColor: UIColor! var darkColor: UIColor! override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) if (color == UIColor.redColor()) { fillSprite = SKSpriteNode(imageNamed: "redcircle") } else if (color == UIColor.blueColor()) { fillSprite = SKSpriteNode(imageNamed: "bluecircle") } maskNode = SKSpriteNode(color: UIColor.blackColor(), size: CGSize(width: self.size.width, height: self.size.height)) maskNode.position.y -= self.size.height/2 cropNode = SKCropNode() cropNode.addChild(fillSprite) cropNode.maskNode = maskNode cropNode.zPosition = 1 self.addChild(cropNode) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setFillAmount(amount: CGFloat) { // amount parameter must be float value between 0.0 and 1.0 let newHeight = amount * (self.size.height*2) maskNode.size = CGSize(width: self.size.width, height: newHeight) } } class BubbleNode: SIFloatingNode { var labelNode = SKLabelNode(fontNamed: "Avenir-Black") class func instantiate(name:String,color:BubbleNodeColor, value: CGFloat) -> BubbleNode! { let node = BubbleNode(circleOfRadius: 75) configureNode(node, andName: name,color:color, value: value) return node } class func configureNode(node: BubbleNode!, andName:String,color:BubbleNodeColor, value: CGFloat) { let boundingBox = CGPathGetBoundingBox(node.path); let radius = boundingBox.size.width / 2.0; node.physicsBody = SKPhysicsBody(circleOfRadius: radius + 1.5) var circle: Circle? if (color == .Red) { circle = Circle(texture: SKTexture(imageNamed: "lightredcircle"), color: UIColor.redColor(), size: CGSize(width: radius * 2, height: radius * 2)) } else if (color == .Blue) { circle = Circle(texture: SKTexture(imageNamed: "lightbluecircle"), color: UIColor.blueColor(), size: CGSize(width: radius * 2, height: radius * 2)) } circle!.setFillAmount(value) circle!.zPosition = -1 node.addChild(circle!) node.labelNode.text = andName node.labelNode.position = CGPointZero node.labelNode.fontColor = UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0) node.labelNode.fontSize = 25 node.labelNode.userInteractionEnabled = false node.labelNode.verticalAlignmentMode = .Center node.labelNode.horizontalAlignmentMode = .Center node.zPosition = 1 node.addChild(node.labelNode) } override func selectingAnimation() -> SKAction? { removeActionForKey(BubbleNode.removingKey) return SKAction.scaleTo(1.3, duration: 0.2) } override func normalizeAnimation() -> SKAction? { removeActionForKey(BubbleNode.removingKey) return SKAction.scaleTo(1, duration: 0.2) } override func removeAnimation() -> SKAction? { removeActionForKey(BubbleNode.removingKey) return SKAction.fadeOutWithDuration(0.2) } override func removingAnimation() -> SKAction { let pulseUp = SKAction.scaleTo(xScale + 0.13, duration: 0) let pulseDown = SKAction.scaleTo(xScale, duration: 0.3) let pulse = SKAction.sequence([pulseUp, pulseDown]) let repeatPulse = SKAction.repeatActionForever(pulse) return repeatPulse } }
// // FileClient.swift // AppEnv // // Created by Paul Colton on 4/28/21. // import Combine import Foundation struct FileClient { var documentDirectory: () -> URL var loadFile: (URL) -> AnyPublisher<Data, Error> var saveFile: (URL, Data) -> AnyPublisher<Never, Error> } extension FileClient { public static var preview: Self { return Self( documentDirectory: { let mypath = #file let outputDirectory = mypath .components(separatedBy: "/") .dropLast() + ["Preview Content"] let pathString = outputDirectory.joined(separator: "/") let outputDirURL = URL(fileURLWithPath: pathString, isDirectory: true) return outputDirURL }, loadFile: Self.live.loadFile, saveFile: Self.live.saveFile ) } } extension FileClient { public static var live: Self { return Self( documentDirectory: { FileManager.default .urls(for: .documentDirectory, in: .userDomainMask) .first! }, loadFile: { url in Deferred { Future<Data, Error> { promise in do { let data = try Data(contentsOf: url) promise(.success(data)) } catch { promise(.failure(error)) } } } .eraseToAnyPublisher() }, saveFile: { url, data in #if NEVER // Alternate version using Future, but no explicit .success is possible Deferred { Future<Never, Error> { promise in do { try data.write(to: url) // promise(.success(Never)) // Not possible } catch { promise(.failure(error)) } } } .eraseToAnyPublisher() #endif do { try data.write(to: url) return Just(()) .ignoreOutput() .setFailureType(to: Error.self) .eraseToAnyPublisher() } catch { return Fail(error: error) .eraseToAnyPublisher() } } ) } }
//Value Types //Int, Character, Float, Double, String //Enums, Arrays, Struct //Compiler Generates Following Code //getter and setter for width //getter and setter for height //Memberwise Constructor // Resolution(width: 0, height: 0) struct Resolution { var width = 0 var height = 0 } //Reference Types class VideoMode { var resolution = Resolution() var framerate = 0.0 var name: String? } func playWithClassesAndStructures() { let hd = Resolution(width: 1920, height: 1080) print(hd) var cinema = hd cinema.width = 2048 print("HD : \(hd)") print("cinema : \(cinema)") let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.framerate = 60 tenEighty.name = "1080i" let alsoTenEighty = tenEighty alsoTenEighty.framerate = 75 print(tenEighty.framerate) print(alsoTenEighty.framerate) if tenEighty === alsoTenEighty { print("Aiyeooo Aiyeeooooo....") } // if tenEighty == alsoTenEighty { // print("Aiyeooo Aiyeeooooo....") // } } func main() { print("\nFunction : playWithClassesAndStructures") playWithClassesAndStructures() } main()
// // PrefixeStringTests.swift // // // Created by Vladislav Fitc on 18/07/2022. // import Foundation import XCTest @testable import AlgoliaSearchClient class PrefixedStringTests: XCTestCase { func testPrefixedString() { let prefixedString = PrefixedString(rawValue: "prefix(value)") XCTAssertEqual(prefixedString?.prefix, "prefix") XCTAssertEqual(prefixedString?.value, "value") } func testPrefixedStringFailure() { let prefixedString = PrefixedString(rawValue: "prefix(value") XCTAssertNil(prefixedString) } func testPrefixedStringDecoding() throws { let data = try JSONEncoder().encode(JSON.string("prefix(value)")) let prefixedString = try JSONDecoder().decode(PrefixedString.self, from: data) XCTAssertEqual(prefixedString.prefix, "prefix") XCTAssertEqual(prefixedString.value, "value") } func testPrefixedStringDecodingFailure() throws { let data = try JSONEncoder().encode(JSON.string("prefix(value")) XCTAssertThrowsError(try JSONDecoder().decode(PrefixedString.self, from: data), "decoding of prefixed in wrong format might throw an error") { error in if case(.dataCorrupted(let context)) = error as? DecodingError { print(context.debugDescription) } else { XCTFail("unexpected error throws") } } } }
// // ViewController.swift // TestFBWKWebView // // Created by An Tran on 06/07/16. // Copyright © 2016 TBA. All rights reserved. // import UIKit import WebKit class WKWebViewController: UIViewController { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() setupWebView() if let url = NSURL(string: "https://www.payback.de") { webView.loadRequest(NSURLRequest(URL: url)) } } private func setupWebView() { webView = WKWebView(frame: self.view.frame) webView.UIDelegate = self webView.navigationDelegate = self webView.backgroundColor = UIColor.whiteColor() // Constraint webView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(webView) self.view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("|[v]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v" : webView]) ) self.view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("V:|[v]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v" : webView]) ) } } extension WKWebViewController: WKNavigationDelegate { func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { decisionHandler(.Allow) } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { } func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { print(error) } } extension WKWebViewController: WKUIDelegate { func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { return nil } }
import MetalKit class LightManager { private var _lightObjects: [LightObject] = [] func addLightObject(_ lightObject: LightObject) { self._lightObjects.append(lightObject) } private func gatherLightData()->[LightData] { var result: [LightData] = [] for lightObject in _lightObjects { result.append(lightObject.lightData) } return result } func setLightData(_ renderCommandEncoder: MTLRenderCommandEncoder) { var lightDatas = gatherLightData() var lightCount = lightDatas.count renderCommandEncoder.setFragmentBytes(&lightCount, length: Int32.size, index: 2) renderCommandEncoder.setFragmentBytes(&lightDatas, length: LightData.stride(lightCount), index: 3) } } class LightObject: GameObject { var lightData = LightData() override func update(deltaTime: Float) { self.lightData.position = self.getPosition() super.update(deltaTime: deltaTime) } } extension LightObject { // Light Color public func setLightColor(_ color: float3) { self.lightData.color = color } public func getLightColor()->float3 { return self.lightData.color } }
// // TxScrollView.swift // BCWallet // // Created by Miroslav Djukic on 21/07/2020. // Copyright © 2020 Miroslav Djukic. All rights reserved. // import UIKit import BCWalletModel class TxScrollView: UIScrollView { private var transaction: TransactionViewModel var dismissCallback: (()->())? lazy private var scrollContainerView = TxScrollContentView(transaction: transaction) init(transaction: TransactionViewModel) { self.transaction = transaction super.init(frame: .zero) scrollContainerView.dismissCallback = { [weak self] in guard let dismiss = self?.dismissCallback else { return } dismiss() } addSubviews() addConstraints() } private func addSubviews() { addSubview(scrollContainerView) } private func addConstraints() { scrollContainerView.translatesAutoresizingMaskIntoConstraints = false let scrollContainerViewLeading = scrollContainerView.leadingAnchor .constraint(equalTo: leadingAnchor) let scrollContainerViewTop = scrollContainerView.topAnchor .constraint(equalTo: topAnchor) let scrollContainerViewBottom = scrollContainerView.bottomAnchor .constraint(equalTo: bottomAnchor) let scrollContainerViewTrailing = scrollContainerView.trailingAnchor .constraint(equalTo: trailingAnchor) let scrollContainerViewWidth = scrollContainerView.widthAnchor .constraint(equalTo: widthAnchor) NSLayoutConstraint.activate([ scrollContainerViewLeading, scrollContainerViewTop, scrollContainerViewBottom, scrollContainerViewTrailing, scrollContainerViewWidth ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // ContainerController+HomeControllerDelegate.swift // FundooApp // // Created by admin on 01/06/20. // Copyright © 2020 admin. All rights reserved. // import Foundation extension ContainerController: HomeControllerDelegate { func handleMenuToggle(forMenuOprion menuOption: MenuOption?) { if !isExpanded { configureMenuController() } isExpanded = !isExpanded animatePanel(shouldExpand: isExpanded, menuOption: menuOption) } }